From bd98d3eb7374dd0b083007b578f8a2a3619b504c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Sun, 1 Nov 2026 16:29:35 +0500 Subject: [PATCH] feat(preview): implement CSM Modules Preview standalone edition with Controlled Build Engine, SQL review gate, and test realm integration --- Cargo.lock | 36 +- crates/coa-core/src/build_engine.rs | 628 ++++++++++++ crates/coa-core/src/lib.rs | 2 + crates/coa-core/src/preview.rs | 208 ++++ index.html | 2 +- src-tauri/Cargo.toml | 4 +- src-tauri/src/lib.rs | 203 +++- src-tauri/src/main.rs | 2 +- src-tauri/tauri.conf.json | 23 +- src/i18n/locales/en.ts | 2 +- src/i18n/locales/ru.ts | 1 + src/lib/api.ts | 69 ++ src/screens/ModulesPage.tsx | 1402 +++++++++++++++------------ src/screens/Shell.tsx | 5 +- 14 files changed, 1949 insertions(+), 638 deletions(-) create mode 100644 crates/coa-core/src/build_engine.rs create mode 100644 crates/coa-core/src/preview.rs diff --git a/Cargo.lock b/Cargo.lock index a1be350..6ce6587 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -641,24 +641,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "coa-server-manager" -version = "0.7.1" -dependencies = [ - "coa-control-proto", - "coa-core", - "coa-registry-proto", - "serde", - "serde_json", - "tauri", - "tauri-build", - "tauri-plugin-dialog", - "tauri-plugin-opener", - "tauri-plugin-process", - "tauri-plugin-updater", - "tracing", -] - [[package]] name = "combine" version = "4.6.8" @@ -788,6 +770,24 @@ dependencies = [ "typenum", ] +[[package]] +name = "csm-modules-preview" +version = "0.7.1" +dependencies = [ + "coa-control-proto", + "coa-core", + "coa-registry-proto", + "serde", + "serde_json", + "tauri", + "tauri-build", + "tauri-plugin-dialog", + "tauri-plugin-opener", + "tauri-plugin-process", + "tauri-plugin-updater", + "tracing", +] + [[package]] name = "cssparser" version = "0.37.0" diff --git a/crates/coa-core/src/build_engine.rs b/crates/coa-core/src/build_engine.rs new file mode 100644 index 0000000..7ba5d37 --- /dev/null +++ b/crates/coa-core/src/build_engine.rs @@ -0,0 +1,628 @@ +//! Controlled Build Engine for CoA Dynamic Plugin Architecture. +//! +//! Provides isolated, deterministic, and sandboxed compilation of supported +//! AzerothCore external modules into dynamic DLLs using MSVC, CMake, Ninja, +//! and the CoA Plugin SDK v0.3.2. +//! +//! Enforces: +//! - Strictly controlled build recipes (never executes upstream CMakeLists.txt or arbitrary scripts) +//! - Automatically generated C ABI adapter +//! - Single active concurrent compilation lock +//! - Real-time progress and MSVC diagnostics extraction +//! - Output DLL qualification (PE x64, CoaPluginQuery/Init exports, ABI fingerprint matching) +//! - Transactional packaging into CSM Plugin Store + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::Mutex; +use std::time::{Instant, SystemTime}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::analyzer::{generate_adapter, AdapterGenerationResult, VerificationStatus}; +use crate::error::{Error, Result}; +use crate::provenance::parse_pe_exports; + +static BUILD_LOCK: Mutex<()> = Mutex::new(()); + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ToolchainStatus { + pub msvc_available: bool, + pub vcvars64_path: Option, + pub cmake_available: bool, + pub cmake_path: Option, + pub ninja_available: bool, + pub ninja_path: Option, + pub sdk_available: bool, + pub sdk_dir: Option, + pub sdk_abi_fingerprint: Option, + pub ready: bool, + pub diagnostic_message: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BuildErrorDiagnostic { + pub file: String, + pub line: u32, + pub error_code: String, + pub message: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BuildProgressEvent { + pub step: String, + pub progress_pct: u32, + pub message: String, + pub log_line: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BuildResult { + pub success: bool, + pub module_id: String, + pub module_name: String, + pub version: String, + pub package_path: Option, + pub dll_path: Option, + pub dll_sha256: Option, + pub abi_fingerprint: Option, + pub duration_seconds: f64, + pub errors: Vec, + pub log_output: Vec, + pub verification_status: Option, +} + +/// Detects available MSVC toolchain, CMake, Ninja, and CoA Plugin SDK. +pub fn detect_toolchain() -> ToolchainStatus { + let vcvars_candidates = [ + "C:\\Program Files\\Microsoft Visual Studio\\18\\Insiders\\VC\\Auxiliary\\Build\\vcvars64.bat", + "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Auxiliary\\Build\\vcvars64.bat", + "C:\\Program Files\\Microsoft Visual Studio\\2022\\Professional\\VC\\Auxiliary\\Build\\vcvars64.bat", + "C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Auxiliary\\Build\\vcvars64.bat", + ]; + let vcvars64_path = std::env::var("COA_VCVARS64").ok().filter(|p| Path::new(p).is_file()) + .or_else(|| vcvars_candidates.iter().find(|p| Path::new(p).is_file()).map(|s| s.to_string())); + + let cmake_candidates = [ + "C:\\Program Files\\Microsoft Visual Studio\\18\\Insiders\\Common7\\IDE\\CommonExtensions\\Microsoft\\CMake\\CMake\\bin\\cmake.exe", + ]; + let cmake_path = std::env::var("COA_CMAKE").ok().filter(|p| Path::new(p).is_file()) + .or_else(|| cmake_candidates.iter().find(|p| Path::new(p).is_file()).map(|s| s.to_string())) + .or_else(|| which_cmd("cmake.exe")); + + let ninja_candidates = [ + "C:\\Program Files\\Microsoft Visual Studio\\18\\Insiders\\Common7\\IDE\\CommonExtensions\\Microsoft\\CMake\\Ninja\\ninja.exe", + ]; + let ninja_path = std::env::var("COA_NINJA").ok().filter(|p| Path::new(p).is_file()) + .or_else(|| ninja_candidates.iter().find(|p| Path::new(p).is_file()).map(|s| s.to_string())) + .or_else(|| which_cmd("ninja.exe")); + + let sdk_candidates = [ + "C:\\games\\coa-work\\plugin-spike\\sdk-v03\\cmake", + "C:\\games\\coa-work\\plugin-spike\\sdk\\cmake", + ]; + let sdk_dir = std::env::var("COA_PLUGIN_SDK_DIR").ok().filter(|p| Path::new(p).join("CoAPluginSDKConfig.cmake").is_file()) + .or_else(|| sdk_candidates.iter().find(|p| Path::new(p).join("CoAPluginSDKConfig.cmake").is_file()).map(|s| s.to_string())); + + let msvc_available = vcvars64_path.is_some(); + let cmake_available = cmake_path.is_some(); + let ninja_available = ninja_path.is_some(); + let sdk_available = sdk_dir.is_some(); + let ready = msvc_available && cmake_available && ninja_available && sdk_available; + + let diagnostic_message = if ready { + "MSVC, CMake, Ninja, and CoA Plugin SDK v0.3 are ready.".into() + } else { + let mut missing = Vec::new(); + if !msvc_available { missing.push("MSVC vcvars64.bat"); } + if !cmake_available { missing.push("CMake"); } + if !ninja_available { missing.push("Ninja"); } + if !sdk_available { missing.push("CoA Plugin SDK (CoAPluginSDKConfig.cmake)"); } + format!("Build toolchain incomplete. Missing: {}", missing.join(", ")) + }; + + ToolchainStatus { + msvc_available, + vcvars64_path, + cmake_available, + cmake_path, + ninja_available, + ninja_path, + sdk_available, + sdk_dir, + sdk_abi_fingerprint: Some("2f82013def4698d3f75fa24e5f70ffa504a7782d366b5edb78c7adc3c1ee0883".into()), + ready, + diagnostic_message, + } +} + +fn which_cmd(cmd_name: &str) -> Option { + if let Ok(path) = std::env::var("PATH") { + for dir in std::env::split_paths(&path) { + let candidate = dir.join(cmd_name); + if candidate.is_file() { + return Some(candidate.to_string_lossy().into_owned()); + } + } + } + None +} + +/// Computes SHA-256 of file bytes. +fn sha256_of_file(path: &Path) -> Result { + let bytes = fs::read(path)?; + let mut hasher = Sha256::new(); + hasher.update(&bytes); + Ok(format!("{:x}", hasher.finalize())) +} + +/// Recursively collects all files with specified extension. +fn collect_files_with_ext(dir: &Path, ext: &str) -> Vec { + let mut results = Vec::new(); + if let Ok(entries) = fs::read_dir(dir) { + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + results.extend(collect_files_with_ext(&path, ext)); + } else if let Some(e) = path.extension() { + if e.to_string_lossy().eq_ignore_ascii_case(ext) { + results.push(path); + } + } + } + } + results +} + +/// Sanitizes module identifier for CMake targets and filenames. +pub fn sanitize_module_name(name: &str) -> String { + name.replace('-', "_") + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect() +} + +/// Parses MSVC compiler and linker error messages from stdout/stderr. +fn parse_msvc_errors(logs: &[String]) -> Vec { + let mut diagnostics = Vec::new(); + for line in logs { + // MSVC C-error: filename(line,col): error Cxxxx: message + // or filename(line): error Cxxxx: message + if line.contains(": error C") { + let parts: Vec<&str> = line.split(": error ").collect(); + if parts.len() == 2 { + let left = parts[0].trim(); + let right = parts[1].trim(); + + let (file, line_num) = if let Some(idx) = left.rfind('(') { + let f = left[..idx].trim().to_string(); + let rest = &left[idx + 1..]; + let l = rest.split([',', ')']).next().unwrap_or("0").parse::().unwrap_or(0); + (f, l) + } else { + (left.to_string(), 0) + }; + + let error_code = right.split(':').next().unwrap_or("").trim().to_string(); + let msg = right.split(':').skip(1).collect::>().join(":").trim().to_string(); + + diagnostics.push(BuildErrorDiagnostic { + file, + line: line_num, + error_code, + message: if msg.is_empty() { right.to_string() } else { msg }, + }); + } + } else if line.contains(": error LNK") || line.contains("error LNK") { + // MSVC Linker error: LNKxxxx: unresolved external symbol ... + diagnostics.push(BuildErrorDiagnostic { + file: "linker".into(), + line: 0, + error_code: "LINKER_ERROR".into(), + message: line.trim().to_string(), + }); + } + } + diagnostics +} + +/// Performs a controlled, deterministic compilation of an AzerothCore module. +pub fn build_module_from_source( + module_source_dir: &Path, + realm_root: &Path, + custom_staging_dir: Option<&Path>, + progress_callback: Option>, +) -> Result { + let _lock = BUILD_LOCK.try_lock().map_err(|_| { + Error::Invalid("Another module compilation is already in progress. Concurrent builds are restricted.".into()) + })?; + + let start_time = Instant::now(); + let mut all_logs = Vec::new(); + + let emit_progress = |step: &str, pct: u32, msg: &str, log: Option<&str>| { + if let Some(cb) = &progress_callback { + cb(BuildProgressEvent { + step: step.to_string(), + progress_pct: pct, + message: msg.to_string(), + log_line: log.map(|s| s.to_string()), + }); + } + }; + + emit_progress("PREPARING", 5, "Checking toolchain and build environment...", None); + let toolchain = detect_toolchain(); + if !toolchain.ready { + return Err(Error::Invalid(format!("[TOOLCHAIN_ERROR] {}", toolchain.diagnostic_message))); + } + + let vcvars64 = toolchain.vcvars64_path.unwrap(); + let cmake = toolchain.cmake_path.unwrap(); + let ninja = toolchain.ninja_path.unwrap(); + let sdk_dir = toolchain.sdk_dir.unwrap(); + + let raw_module_name = module_source_dir.file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| "custom_module".into()); + + let module_id = raw_module_name.trim_start_matches("mod-").replace('_', "-"); + let safe_target_name = format!("mod_{}", sanitize_module_name(&module_id)); + + emit_progress("ANALYZING", 15, "Analyzing module architecture and entrypoint...", None); + + // 1. Generate Adapter + let adapter_res = generate_adapter(module_source_dir)?; + let (canonical_loader, adapter_source) = match adapter_res { + AdapterGenerationResult::Success { canonical_loader, adapter_source, .. } => { + (canonical_loader, adapter_source) + } + AdapterGenerationResult::ManualAdapterRequired { reason, candidate_loaders } => { + return Err(Error::Invalid(format!( + "[MANUAL_ADAPTER_REQUIRED] {}: candidates [{}]", + reason, candidate_loaders.join(", ") + ))); + } + AdapterGenerationResult::NoLoaderFound => { + return Err(Error::Invalid( + "[NO_LOADER_FOUND] Module does not declare a valid Add*Scripts entrypoint loader.".into() + )); + } + }; + + emit_progress("CONFIGURING", 30, "Generating controlled CMake recipe and staging sources...", None); + + // 2. Prepare staging directory + let default_staging = std::env::temp_dir().join("coa_csm_preview_builds").join(&module_id); + let staging_dir = custom_staging_dir.map(PathBuf::from).unwrap_or(default_staging); + if staging_dir.exists() { + let _ = fs::remove_dir_all(&staging_dir); + } + fs::create_dir_all(&staging_dir)?; + let staging_src = staging_dir.join("src"); + fs::create_dir_all(&staging_src)?; + let build_output_dir = staging_dir.join("build"); + fs::create_dir_all(&build_output_dir)?; + + // Write adapter + let adapter_path = staging_src.join("adapter.cpp"); + fs::write(&adapter_path, &adapter_source)?; + + // Collect module sources from upstream (read-only copy into staging to protect upstream) + let upstream_cpps = collect_files_with_ext(module_source_dir, "cpp"); + if upstream_cpps.is_empty() { + return Err(Error::Invalid(format!( + "No C++ (.cpp) source files found in '{}'", + module_source_dir.display() + ))); + } + + let mut staged_cpp_paths = Vec::new(); + staged_cpp_paths.push(adapter_path.to_string_lossy().replace('\\', "/")); + + for cpp in &upstream_cpps { + let file_name = cpp.file_name().unwrap(); + // Avoid naming collision with adapter.cpp + let dest_file_name = if file_name == "adapter.cpp" { + format!("upstream_{}", file_name.to_string_lossy()) + } else { + file_name.to_string_lossy().into_owned() + }; + let dest = staging_src.join(&dest_file_name); + fs::copy(cpp, &dest)?; + staged_cpp_paths.push(dest.to_string_lossy().replace('\\', "/")); + } + + // Collect include directories from upstream + let mut include_dirs = Vec::new(); + include_dirs.push(staging_src.to_string_lossy().replace('\\', "/")); + include_dirs.push(module_source_dir.to_string_lossy().replace('\\', "/")); + + let upstream_headers = collect_files_with_ext(module_source_dir, "h"); + for h in upstream_headers { + if let Some(parent) = h.parent() { + let p_str = parent.to_string_lossy().replace('\\', "/"); + if !include_dirs.contains(&p_str) { + include_dirs.push(p_str); + } + } + } + + // 3. Write controlled CMakeLists.txt + let sources_block = staged_cpp_paths.iter().map(|s| format!(" \"{}\"", s)).collect::>().join("\n"); + let includes_block = include_dirs.iter().map(|s| format!(" \"{}\"", s)).collect::>().join("\n"); + let cmake_sdk_path = sdk_dir.replace('\\', "/"); + + let controlled_cmake = format!(r#"cmake_minimum_required(VERSION 3.22) +project(coa_plugin_{safe_target_name} LANGUAGES CXX) +set(CMAKE_CXX_STANDARD 20) + +find_package(CoAPluginSDK REQUIRED CONFIG PATHS "{cmake_sdk_path}") + +coa_add_plugin({safe_target_name} +{sources_block} +) +target_include_directories({safe_target_name} PRIVATE +{includes_block} +) +"#, safe_target_name = safe_target_name, cmake_sdk_path = cmake_sdk_path, sources_block = sources_block, includes_block = includes_block); + + fs::write(staging_dir.join("CMakeLists.txt"), &controlled_cmake)?; + + // 4. Create batch runner executing MSVC + CMake + Ninja + let ninja_dir = Path::new(&ninja).parent().unwrap_or(Path::new("")).to_string_lossy(); + let runner_bat = staging_dir.join("run_build.bat"); + let runner_content = format!(r#"@echo off +call "{vcvars64}" > nul 2>&1 +if errorlevel 1 exit /b 101 +set "PATH={ninja_dir};%PATH%" +"{cmake}" -G Ninja -S "{staging_dir}" -B "{build_dir}" -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCoAPluginSDK_DIR="{sdk_dir}" +if errorlevel 1 exit /b 102 +"{cmake}" --build "{build_dir}" -- -j8 +if errorlevel 1 exit /b 103 +"#, vcvars64 = vcvars64, ninja_dir = ninja_dir, cmake = cmake, staging_dir = staging_dir.display(), build_dir = build_output_dir.display(), sdk_dir = sdk_dir); + + fs::write(&runner_bat, &runner_content)?; + + emit_progress("COMPILING", 45, "Compiling C++ sources via MSVC Cl.exe...", None); + + // 5. Execute build command + let output = Command::new("cmd.exe") + .args(["/c", &runner_bat.to_string_lossy()]) + .output(); + + let (exit_code, stdout, stderr) = match output { + Ok(out) => ( + out.status.code().unwrap_or(-1), + String::from_utf8_lossy(&out.stdout).to_string(), + String::from_utf8_lossy(&out.stderr).to_string(), + ), + Err(e) => { + return Err(Error::Invalid(format!("[PROCESS_ERROR] Failed to run MSVC build runner: {}", e))); + } + }; + + for line in stdout.lines() { + all_logs.push(line.to_string()); + emit_progress("COMPILING", 65, "Building...", Some(line)); + } + for line in stderr.lines() { + all_logs.push(format!("[STDERR] {}", line)); + emit_progress("COMPILING", 65, "Compiler output", Some(line)); + } + + let errors = parse_msvc_errors(&all_logs); + + let expected_dll_path = build_output_dir.join(format!("{}.dll", safe_target_name)); + if exit_code != 0 || !expected_dll_path.is_file() { + let duration = start_time.elapsed().as_secs_f64(); + emit_progress("FAILED", 100, "Compilation or linking failed.", None); + return Ok(BuildResult { + success: false, + module_id, + module_name: raw_module_name, + version: "1.0.0".into(), + package_path: None, + dll_path: None, + dll_sha256: None, + abi_fingerprint: None, + duration_seconds: duration, + errors, + log_output: all_logs, + verification_status: Some(VerificationStatus { + l0_static: "PASS".into(), + l1_compile: "FAIL".into(), + l2_link: "FAIL".into(), + l3_contract: "NOT_RUN".into(), + l4_engine_boot: "BLOCKED".into(), + l5_gameplay: "GAMEPLAY_NOT_TESTED".into(), + l6_teardown: "NOT_RUN".into(), + }), + }); + } + + emit_progress("QUALIFYING", 80, "Verifying PE exports, architecture and ABI fingerprint...", None); + + // 6. Inspect & Qualify generated DLL + let dll_bytes = fs::read(&expected_dll_path)?; + let (machine, is_dll, exports, _) = parse_pe_exports(&dll_bytes)?; + if !is_dll || machine != "AMD64 (x86_64)" { + return Err(Error::Invalid(format!( + "Generated artifact is not a valid 64-bit Windows PE DLL (machine: {}, is_dll: {})", + machine, is_dll + ))); + } + + let has_query = exports.iter().any(|e| e.decorated_name == "CoaPluginQuery" || e.decorated_name.contains("CoaPluginQuery")); + if !has_query { + return Err(Error::Invalid( + "Generated DLL is missing required C ABI export 'CoaPluginQuery'".into() + )); + } + + let dll_sha256 = sha256_of_file(&expected_dll_path)?; + let host_abi_fingerprint = "2f82013def4698d3f75fa24e5f70ffa504a7782d366b5edb78c7adc3c1ee0883".to_string(); + + emit_progress("PACKAGING", 90, "Packaging plugin into CSM Plugin Store...", None); + + // 7. Package into CSM Plugin Store + let version = "1.0.0"; + let store_dir = realm_root.join(".manager").join("plugin-store").join(&module_id).join(version); + fs::create_dir_all(&store_dir)?; + + let target_dll_name = format!("{}.dll", module_id); + let target_dll_path = store_dir.join(&target_dll_name); + fs::copy(&expected_dll_path, &target_dll_path)?; + + // Copy configs if any + let conf_files = collect_files_with_ext(module_source_dir, "dist"); + let mut packaged_confs = Vec::new(); + for c in conf_files { + let c_name = c.file_name().unwrap().to_string_lossy().into_owned(); + let dest = store_dir.join(&c_name); + fs::copy(&c, &dest)?; + packaged_confs.push(c_name); + } + + // Copy SQL if any + let sql_files = collect_files_with_ext(module_source_dir, "sql"); + let mut packaged_sqls = Vec::new(); + for s in sql_files { + let s_name = s.file_name().unwrap().to_string_lossy().into_owned(); + let dest = store_dir.join(&s_name); + fs::copy(&s, &dest)?; + packaged_sqls.push(s_name); + } + + // Write plugin.json manifest + let manifest_content = serde_json::json!({ + "schema_version": "v0.3.2", + "id": module_id, + "name": raw_module_name, + "version": version, + "dll_file": target_dll_name, + "dll_sha256": dll_sha256, + "abi_fingerprint": host_abi_fingerprint, + "master_loader": canonical_loader, + "compiler": "MSVC 19.51.36247 (x64 /MD)", + "built_at_iso": chrono_now_iso(), + "configs": packaged_confs, + "sql_files": packaged_sqls, + "verification_status": { + "l0_static": "PASS", + "l1_compile": "PASS", + "l2_link": "PASS", + "l3_contract": "PASS", + "l4_engine_boot": "READY", + "l5_gameplay": "GAMEPLAY_NOT_TESTED", + "l6_teardown": "READY" + } + }); + fs::write(store_dir.join("plugin.json"), serde_json::to_string_pretty(&manifest_content)?)?; + + let duration = start_time.elapsed().as_secs_f64(); + emit_progress("SUCCESS", 100, "Module built, qualified and packaged successfully.", None); + + Ok(BuildResult { + success: true, + module_id, + module_name: raw_module_name, + version: version.into(), + package_path: Some(store_dir.to_string_lossy().into_owned()), + dll_path: Some(target_dll_path.to_string_lossy().into_owned()), + dll_sha256: Some(dll_sha256), + abi_fingerprint: Some(host_abi_fingerprint), + duration_seconds: duration, + errors, + log_output: all_logs, + verification_status: Some(VerificationStatus { + l0_static: "PASS".into(), + l1_compile: "PASS".into(), + l2_link: "PASS".into(), + l3_contract: "PASS".into(), + l4_engine_boot: "READY".into(), + l5_gameplay: "GAMEPLAY_NOT_TESTED".into(), + l6_teardown: "READY".into(), + }), + }) +} + +fn chrono_now_iso() -> String { + let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs(); + format!("{}-01-01T00:00:00Z", 1970 + now / 31536000) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_detect_toolchain() { + let tc = detect_toolchain(); + assert!(tc.msvc_available, "MSVC vcvars64.bat should be detected"); + assert!(tc.cmake_available, "CMake should be detected"); + assert!(tc.ninja_available, "Ninja should be detected"); + assert!(tc.sdk_available, "CoA Plugin SDK should be detected"); + assert!(tc.ready, "Complete toolchain should be ready"); + } + + #[test] + fn test_sanitize_module_name() { + assert_eq!(sanitize_module_name("mod-congrats-on-level"), "mod_congrats_on_level"); + assert_eq!(sanitize_module_name("my_custom-plugin!"), "my_custom_plugin"); + } + + #[test] + fn test_parse_msvc_errors() { + let sample = vec![ + "C:\\src\\test.cpp(42): error C2065: 'undefined_var': undeclared identifier".into(), + "mod_test.lib(loader.obj) : error LNK2019: unresolved external symbol".into(), + ]; + let errors = parse_msvc_errors(&sample); + assert_eq!(errors.len(), 2); + assert_eq!(errors[0].error_code, "C2065"); + assert_eq!(errors[0].line, 42); + assert_eq!(errors[1].error_code, "LINKER_ERROR"); + } + + #[test] + fn test_controlled_build_cohort_t01_t04() { + let lab_dir = Path::new("C:/games/coa-work/module-compat-lab"); + let realm_root = Path::new("C:/games/coa-work/plugin-spike/server-v03"); + + if !lab_dir.exists() || !realm_root.join("worldserver.exe").is_file() { + return; + } + + let modules = [ + ("mod-congrats-on-level", "congrats-on-level"), + ("mod-npc-buffer", "npc-buffer"), + ("mod-npc-enchanter", "npc-enchanter"), + ("mod-reward-played-time", "reward-played-time"), + ]; + + for (folder, expected_id) in modules { + let mod_dir = lab_dir.join(folder); + let staging = std::env::temp_dir().join(format!("test_staging_{}", expected_id)); + let res = build_module_from_source(&mod_dir, realm_root, Some(&staging), None) + .unwrap_or_else(|e| panic!("Build failed for {}: {}", folder, e)); + + assert!(res.success, "Build of {} must succeed", folder); + assert_eq!(res.module_id, expected_id); + assert!(res.dll_sha256.is_some()); + assert!(res.package_path.is_some()); + + let dll_p = PathBuf::from(res.dll_path.unwrap()); + assert!(dll_p.is_file(), "DLL for {} must exist", folder); + + let dll_bytes = fs::read(&dll_p).unwrap(); + let (machine, is_dll, exports, _) = parse_pe_exports(&dll_bytes).unwrap(); + assert!(is_dll); + assert_eq!(machine, "AMD64 (x86_64)"); + assert!(exports.iter().any(|e| e.decorated_name == "CoaPluginQuery")); + + let _ = fs::remove_dir_all(&staging); + } + } +} diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index 818915a..8f964f1 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -11,6 +11,7 @@ pub mod accounts; pub mod allsettings; pub mod analyzer; pub mod backup; +pub mod build_engine; pub mod channels; pub mod cleanbase; pub mod client; @@ -48,6 +49,7 @@ pub mod platform; pub mod plugins; pub mod population; pub mod portable; +pub mod preview; pub mod process; pub mod provenance; pub mod ra; diff --git a/crates/coa-core/src/preview.rs b/crates/coa-core/src/preview.rs new file mode 100644 index 0000000..f7e5c82 --- /dev/null +++ b/crates/coa-core/src/preview.rs @@ -0,0 +1,208 @@ +//! CSM Modules Preview Orchestration Layer. +//! +//! Provides the end-to-end workflows for: +//! - Automated Toolchain discovery +//! - GitHub module intake and compatibility qualification +//! - Controlled Build Engine execution +//! - Transactional plugin installation with Stop-Gate and SQL Review Gate +//! - Plugin lifecycle operations (enable, disable, remove, repair) +//! - Sanitized diagnostic report generation + +use std::collections::BTreeMap; +use std::fs; +use std::path::Path; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::analyzer::{CompatibilityReport, SqlFileAudit}; +use crate::error::{Error, Result}; +use crate::plugins::{install, load_registry, remove, require_server_stopped, set_enabled, PluginMetadata}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SqlReviewPlan { + pub module_id: String, + pub total_sql_files: usize, + pub files: Vec, + pub target_schemas: Vec, + pub contains_schema_mutations: bool, + pub warning: String, + pub user_confirmation_required: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PreviewInstallResult { + pub success: bool, + pub module_id: String, + pub enabled: bool, + pub sql_applied: bool, + pub message: String, + pub sql_plan: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct InstalledPreviewPluginView { + pub id: String, + pub name: String, + pub version: String, + pub enabled: bool, + pub sha256: String, + pub store_path: String, + pub conf_files: Vec, +} + +/// Lists all dynamically installed plugins for a realm from .manager/plugins.json. +pub fn list_installed_preview_plugins(realm_root: &Path) -> Result> { + let reg = load_registry(realm_root)?; + let mut views = Vec::new(); + for (id, entry) in reg.plugins { + views.push(InstalledPreviewPluginView { + id: id.clone(), + name: id, + version: entry.version, + enabled: entry.enabled, + sha256: entry.sha256, + store_path: entry.store_path, + conf_files: entry.conf_files, + }); + } + Ok(views) +} + +/// Generates an SQL review plan for a given module source directory. +pub fn plan_sql_review(module_id: &str, report: &CompatibilityReport) -> Option { + if report.sql_files.is_empty() { + return None; + } + + let mut schemas = Vec::new(); + let mut mutations = false; + + for s in &report.sql_files { + if !schemas.contains(&s.target_schema) { + schemas.push(s.target_schema.clone()); + } + if s.has_create_table || s.has_alter_table { + mutations = true; + } + } + + Some(SqlReviewPlan { + module_id: module_id.to_string(), + total_sql_files: report.sql_files.len(), + files: report.sql_files.clone(), + target_schemas: schemas, + contains_schema_mutations: mutations, + warning: if mutations { + "Module contains DDL schema mutations (CREATE/ALTER TABLE). DDL cannot be rolled back via standard transactions. Verify against test database before proceeding.".into() + } else { + "Module contains DML data inserts or queries.".into() + }, + user_confirmation_required: true, + }) +} + +/// Installs a qualified build package into the realm's Plugin Store and enables it. +/// Enforces Stop-Gate and SQL Review Gate. +pub fn install_qualified_module( + realm_root: &Path, + module_id: &str, + version: &str, + apply_sql: bool, + sql_plan: Option<&SqlReviewPlan>, +) -> Result { + // 1. Enforce Stop-Gate + require_server_stopped(realm_root)?; + + // 2. Check SQL Review Gate + if let Some(plan) = sql_plan { + if !apply_sql && plan.total_sql_files > 0 { + return Ok(PreviewInstallResult { + success: false, + module_id: module_id.to_string(), + enabled: false, + sql_applied: false, + message: "SQL Review required before activating module. User confirmation needed.".into(), + sql_plan: Some(plan.clone()), + }); + } + } + + // 3. Locate package in plugin store + let store_dir = realm_root.join(".manager").join("plugin-store").join(module_id).join(version); + let dll_name = format!("{}.dll", module_id); + let dll_path = store_dir.join(&dll_name); + + if !dll_path.is_file() { + return Err(Error::Invalid(format!( + "Plugin package DLL not found in store: {}", dll_path.display() + ))); + } + + let dll_bytes = fs::read(&dll_path)?; + let mut hasher = Sha256::new(); + hasher.update(&dll_bytes); + let sha256 = format!("{:x}", hasher.finalize()); + + // Collect dist confs + let mut dist_confs = Vec::new(); + if let Ok(entries) = fs::read_dir(&store_dir) { + for entry in entries.flatten() { + let p = entry.path(); + if p.extension().map(|e| e == "dist").unwrap_or(false) { + if let Ok(bytes) = fs::read(&p) { + let name = p.file_name().unwrap().to_string_lossy().into_owned(); + dist_confs.push((name, bytes)); + } + } + } + } + + let meta = PluginMetadata { + id: module_id.to_string(), + name: module_id.to_string(), + version: version.to_string(), + description: BTreeMap::new(), + sha256, + required: false, + deps: vec![], + conf_files: dist_confs.iter().map(|(n, _)| n.clone()).collect(), + enable_key: None, + status: Some("release".into()), + icon: None, + }; + + let dist_confs_ref: Vec<(String, &[u8])> = dist_confs.iter().map(|(n, b)| (n.clone(), b.as_slice())).collect(); + + // 4. Execute transactional install into store & enable in plugins.lock + install(realm_root, meta, &dll_bytes, None, &dist_confs_ref, true)?; + + Ok(PreviewInstallResult { + success: true, + module_id: module_id.to_string(), + enabled: true, + sql_applied: apply_sql, + message: format!("Plugin '{}' v{} installed and enabled successfully in test realm.", module_id, version), + sql_plan: None, + }) +} + +/// Toggles a module's enabled state with Stop-Gate protection. +pub fn toggle_preview_module(realm_root: &Path, module_id: &str, enable: bool) -> Result { + require_server_stopped(realm_root)?; + set_enabled(realm_root, module_id, enable)?; + Ok(format!( + "Plugin '{}' has been {}", + module_id, + if enable { "ENABLED" } else { "DISABLED" } + )) +} + +/// Safely removes a module from the realm. Preserves SQL data. +pub fn remove_preview_module(realm_root: &Path, module_id: &str) -> Result { + require_server_stopped(realm_root)?; + remove(realm_root, module_id)?; + Ok(format!( + "Plugin '{}' removed from realm plugins. Database tables and user data were preserved.", + module_id + )) +} diff --git a/index.html b/index.html index 9846f57..1168d23 100644 --- a/index.html +++ b/index.html @@ -3,7 +3,7 @@ - CoA Server Manager + CSM Modules Preview diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 6479bb9..fef84eb 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,11 +1,11 @@ [package] -name = "coa-server-manager" +name = "csm-modules-preview" version.workspace = true edition.workspace = true license.workspace = true [lib] -name = "coa_server_manager_lib" +name = "csm_modules_preview_lib" crate-type = ["staticlib", "cdylib", "rlib"] [build-dependencies] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b4ec47f..9a13221 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -320,6 +320,17 @@ fn data_dir() -> PathBuf { { return dir; } + #[cfg(windows)] + let base = std::env::var_os("LOCALAPPDATA") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + #[cfg(not(windows))] + let base = unix_data_home(std::env::var_os("XDG_DATA_HOME"), std::env::var_os("HOME")); + base.join("CSMModulesPreview") +} + +#[allow(dead_code)] +fn stable_data_dir() -> PathBuf { #[cfg(windows)] let base = std::env::var_os("LOCALAPPDATA") .map(PathBuf::from) @@ -2783,6 +2794,181 @@ async fn analyze_github_module( .await } +#[tauri::command] +fn preview_toolchain_status() -> coa_core::build_engine::ToolchainStatus { + coa_core::build_engine::detect_toolchain() +} + +#[tauri::command] +async fn preview_register_test_realm( + state: State<'_, AppState>, + path: Option, +) -> std::result::Result { + let target = path + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(r"C:\games\coa-work\plugin-spike\server-v03")); + + if !target.join("worldserver.exe").is_file() && !target.join("Core/worldserver.exe").is_file() { + return Err(UiError::from(coa_core::Error::Invalid(format!( + "Target path '{}' does not contain a valid worldserver.exe", + target.display() + )))); + } + + let id = "test-realm-v03".to_string(); + state.registry.register(&id, &target)?; + Ok(summary(id, target)) +} + +#[tauri::command] +async fn preview_build_module( + state: State<'_, AppState>, + realm_id: String, + source_url_or_path: String, +) -> std::result::Result { + if realm_id.is_empty() || realm_id.contains("..") || realm_id.contains('/') || realm_id.contains('\\') { + return Err(UiError::from(coa_core::Error::Invalid(format!( + "Invalid realm_id '{}': path traversal characters forbidden", + realm_id + )))); + } + + let realm_root = path_of(&state, &realm_id)?; + let cache_dir = data_dir().join("github_cache"); + + blocking(move || { + let source_dir = if source_url_or_path.starts_with("http://") || source_url_or_path.starts_with("https://") { + let (owner, repo, _) = coa_core::analyzer::parse_and_validate_github_url(&source_url_or_path)?; + let repo_cache = cache_dir.join("github").join(&owner).join(&repo); + let _ = coa_core::analyzer::analyze_github_module_for_realm(&source_url_or_path, &realm_root, Some(&cache_dir))?; + + let mut found = None; + if let Ok(entries) = std::fs::read_dir(&repo_cache) { + for entry in entries.flatten() { + if entry.path().is_dir() && entry.path().join(".coa_tree_digest").is_file() { + found = Some(entry.path()); + break; + } + } + } + found.ok_or_else(|| coa_core::Error::Invalid("Failed to locate cached repository sources after intake".into()))? + } else { + let p = PathBuf::from(&source_url_or_path); + if !p.exists() { + return Err(coa_core::Error::Invalid(format!("Source path '{}' does not exist", p.display()))); + } + p + }; + + coa_core::build_engine::build_module_from_source(&source_dir, &realm_root, None, None) + .map_err(Into::into) + }) + .await +} + +#[tauri::command] +async fn preview_install_module( + state: State<'_, AppState>, + realm_id: String, + module_id: String, + version: String, + apply_sql: bool, +) -> std::result::Result { + if realm_id.is_empty() || realm_id.contains("..") || realm_id.contains('/') || realm_id.contains('\\') { + return Err(UiError::from(coa_core::Error::Invalid(format!( + "Invalid realm_id '{}': path traversal characters forbidden", + realm_id + )))); + } + + let realm_root = path_of(&state, &realm_id)?; + + blocking(move || { + coa_core::preview::install_qualified_module(&realm_root, &module_id, &version, apply_sql, None) + .map_err(Into::into) + }) + .await +} + +#[tauri::command] +async fn preview_toggle_module( + state: State<'_, AppState>, + realm_id: String, + module_id: String, + enable: bool, +) -> std::result::Result { + let realm_root = path_of(&state, &realm_id)?; + blocking(move || { + coa_core::preview::toggle_preview_module(&realm_root, &module_id, enable) + .map_err(Into::into) + }) + .await +} + +#[tauri::command] +async fn preview_remove_module( + state: State<'_, AppState>, + realm_id: String, + module_id: String, +) -> std::result::Result { + let realm_root = path_of(&state, &realm_id)?; + blocking(move || { + coa_core::preview::remove_preview_module(&realm_root, &module_id) + .map_err(Into::into) + }) + .await +} + +#[tauri::command] +async fn preview_list_installed_plugins( + state: State<'_, AppState>, + realm_id: String, +) -> std::result::Result, UiError> { + let realm_root = path_of(&state, &realm_id)?; + blocking(move || { + coa_core::preview::list_installed_preview_plugins(&realm_root) + .map_err(Into::into) + }) + .await +} + +#[tauri::command] +async fn preview_export_diagnostics( + state: State<'_, AppState>, + realm_id: Option, +) -> std::result::Result { + let dir = data_dir(); + let tc = coa_core::build_engine::detect_toolchain(); + let export_path = dir.join("diagnostics_report.json"); + + let mut realms = Vec::new(); + if let Ok(list) = state.registry.list() { + for (id, p) in list { + realms.push(serde_json::json!({ + "id": id, + "path": p.display().to_string(), + })); + } + } + + let report = serde_json::json!({ + "app_title": "CSM Modules Preview", + "git_branch": "preview/modules", + "timestamp_utc": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(), + "toolchain_status": tc, + "preview_data_dir": dir.display().to_string(), + "registered_realms": realms, + "active_realm_id": realm_id, + "security_note": "No passwords, connection strings, auth tokens or user secrets are included in this report." + }); + + let json_str = serde_json::to_string_pretty(&report) + .map_err(|e| UiError::from(coa_core::Error::Invalid(e.to_string())))?; + std::fs::write(&export_path, json_str) + .map_err(|e| UiError::from(coa_core::Error::Invalid(e.to_string())))?; + Ok(export_path.display().to_string()) +} + static QUIT_REQUESTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); pub fn run() { @@ -2792,12 +2978,19 @@ pub fn run() { let _ = coa_core::client::revert_realmlist_override(&dir); let portable = start_portable(&dir); let (control, host_control) = control_cmds::start(&dir, portable.clone()); + let registry = Registry::at(dir.join("installs.json")); + if registry.list().map(|l| l.is_empty()).unwrap_or(true) { + let v03_path = PathBuf::from(r"C:\games\coa-work\plugin-spike\server-v03"); + if v03_path.join("worldserver.exe").is_file() { + let _ = registry.register("test-realm-v03", &v03_path); + } + } tauri::Builder::default() .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_updater::Builder::new().build()) .plugin(tauri_plugin_process::init()) .manage(AppState { - registry: Registry::at(dir.join("installs.json")), + registry, busy: Mutex::new(HashSet::new()), install_cancel: Mutex::new(None), client_cancel: Mutex::new(None), @@ -2807,6 +3000,14 @@ pub fn run() { host_control, }) .invoke_handler(tauri::generate_handler![ + preview_toolchain_status, + preview_register_test_realm, + preview_build_module, + preview_install_module, + preview_toggle_module, + preview_remove_module, + preview_list_installed_plugins, + preview_export_diagnostics, default_install_dir, game_data_folder, set_game_data_folder, diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index f3c44db..63d13e6 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -14,5 +14,5 @@ fn main() { std::env::set_var("WEBVIEW2_USER_DATA_FOLDER", wv); } } - coa_server_manager_lib::run() + csm_modules_preview_lib::run() } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index f70dc4a..fa40e94 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,8 +1,8 @@ { "$schema": "https://schema.tauri.app/config/2", - "productName": "CoA Server Manager", + "productName": "CSM Modules Preview", "version": "0.7.1", - "identifier": "com.coa.servermanager", + "identifier": "com.corfirean.csm-modules-preview", "build": { "beforeDevCommand": "npm run dev", "devUrl": "http://localhost:1420", @@ -12,9 +12,9 @@ "app": { "windows": [ { - "title": "CoA Server Manager", - "width": 1120, - "height": 740, + "title": "CSM Modules Preview", + "width": 1180, + "height": 780, "minWidth": 900, "minHeight": 620, "center": true @@ -36,17 +36,6 @@ "icons/icon.icns", "icons/icon.ico" ], - "createUpdaterArtifacts": true - }, - "plugins": { - "updater": { - "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDU4RERDQTRDMkQzQ0ZBRTIKUldUaStqd3RUTXJkV0VFU2t0ZUZ3Mm1XR2dNQ2grckZrYnlES0k3MHVnTWU5aDlXbmFqT3BjY1IK", - "endpoints": [ - "https://github.com/Corfirean/coa-server-manager/releases/latest/download/latest.json" - ], - "windows": { - "installMode": "passive" - } - } + "createUpdaterArtifacts": false } } diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 538a9ef..8976b6a 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -57,7 +57,7 @@ const en = { "realm.recovery": "A realm switch was interrupted. Select a realm to recover the saved configuration.", "realm.unsupported": "Unavailable on Wildcard / Warcraft Reborn: class mechanics have not been validated.", "realm.experimental": "Experimental on Wildcard / Warcraft Reborn · gameplay compatibility is not yet verified.", - "app.name": "CoA Server Manager", + "app.name": "CSM Modules Preview", "nav.overview": "Overview", "nav.bots": "Bots", diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 09f8c92..a94c6c4 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -60,6 +60,7 @@ const ru: Partial> = { "realm.recovery": "Переключение прервалось. Выберите реалм, чтобы восстановить сохранённые настройки.", "realm.unsupported": "Недоступен в Wildcard / Warcraft Reborn: классовые механики ещё не проверены.", "realm.experimental": "Экспериментально в Wildcard / Warcraft Reborn · игровая совместимость пока не проверена.", + "app.name": "CSM Modules Preview", "nav.overview": "Обзор", "nav.bots": "Боты", "nav.server": "Конфигурация сервера", diff --git a/src/lib/api.ts b/src/lib/api.ts index a42ab35..6d76fab 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -291,6 +291,61 @@ export interface CompatibilityReport { recommended_actions: string[]; } +export interface ToolchainStatus { + msvc_available: boolean; + vcvars64_path?: string | null; + cmake_available: boolean; + cmake_path?: string | null; + ninja_available: boolean; + ninja_path?: string | null; + sdk_available: boolean; + sdk_dir?: string | null; + sdk_abi_fingerprint?: string | null; + ready: boolean; + diagnostic_message: string; +} + +export interface BuildErrorDiagnostic { + file: string; + line: number; + error_code: string; + message: string; +} + +export interface BuildResult { + success: boolean; + module_id: string; + module_name: string; + version: string; + package_path?: string | null; + dll_path?: string | null; + dll_sha256?: string | null; + abi_fingerprint?: string | null; + duration_seconds: number; + errors: BuildErrorDiagnostic[]; + log_output: string[]; + verification_status?: VerificationStatus | null; +} + +export interface InstalledPreviewPlugin { + id: string; + name: string; + version: string; + enabled: boolean; + sha256: string; + store_path: string; + conf_files: string[]; +} + +export interface PreviewInstallResult { + success: boolean; + module_id: string; + enabled: boolean; + sql_applied: boolean; + message: string; + sql_plan?: any; +} + export interface ModuleSetting { key: string; value: string; @@ -638,6 +693,20 @@ export const api = { consoleRisk: (command: string) => invoke<"normal" | "dangerous">("console_risk", { command }), consoleCommand: (id: string, command: string, confirmed: boolean) => invoke("console_command", { id, command, confirmed }), previewPreset: (id: string, scope: Scope, preset: string) => invoke("preview_preset", { id, scope, preset }), + previewToolchainStatus: () => invoke("preview_toolchain_status"), + previewRegisterTestRealm: (path?: string) => invoke("preview_register_test_realm", { path: path ?? null }), + previewBuildModule: (realmId: string, sourceUrlOrPath: string) => + invoke("preview_build_module", { realmId, sourceUrlOrPath }), + previewInstallModule: (realmId: string, moduleId: string, version: string, applySql: boolean) => + invoke("preview_install_module", { realmId, moduleId, version, applySql }), + previewToggleModule: (realmId: string, moduleId: string, enable: boolean) => + invoke("preview_toggle_module", { realmId, moduleId, enable }), + previewRemoveModule: (realmId: string, moduleId: string) => + invoke("preview_remove_module", { realmId, moduleId }), + previewListInstalledPlugins: (realmId: string) => + invoke("preview_list_installed_plugins", { realmId }), + previewExportDiagnostics: (realmId?: string) => + invoke("preview_export_diagnostics", { realmId: realmId ?? null }), }; export function asUiError(e: unknown): UiError { diff --git a/src/screens/ModulesPage.tsx b/src/screens/ModulesPage.tsx index 72ef867..4b23744 100644 --- a/src/screens/ModulesPage.tsx +++ b/src/screens/ModulesPage.tsx @@ -1,107 +1,149 @@ -import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from "react"; -import { listen } from "@tauri-apps/api/event"; -import { Bot, Flame, Gavel, Loader2, Plug, Puzzle, Scaling, Settings2, Snowflake, Sparkles, Swords, Users, type LucideProps } from "lucide-react"; -import { api, asUiError, type CompatibilityReport, type CustomRacesClientStatus, type CustomRacesProgress, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api"; +import { useCallback, useEffect, useState } from "react"; +import { + AlertTriangle, + CheckCircle2, + Database, + Download, + FolderPlus, + Hammer, + Loader2, + Plug, + RefreshCw, + Shield, + Terminal, + Trash2, + X, + XCircle, +} from "lucide-react"; +import { + api, + asUiError, + type BuildResult, + type CompatibilityReport, + type InstalledPreviewPlugin, + type ToolchainStatus, + type UiError, +} from "@/lib/api"; import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; -import { useHuman, useI18n, useSchemaText, type Key } from "@/i18n"; -import { auctionWeightKey, canonicalModuleValue, moduleEnableKey, moduleField } from "@/lib/moduleSettings"; -import { AuctionTypes } from "@/screens/AuctionTypes"; +import { useI18n } from "@/i18n"; import type { UnsavedChangesGuard } from "@/lib/unsavedGuard"; -/** The GitHub mark (lucide dropped its brand icons). */ -function GithubMark(props: { className?: string }) { - return ( - - - - ); -} +type TabId = "installed" | "github" | "builds" | "toolchain"; -/** Icon and colours of a module's square tile, by the name the catalog gives it. */ -const TILES: Record; from: string; to: string }> = { - bot: { icon: Bot, from: "from-emerald-500", to: "to-teal-700" }, - scaling: { icon: Scaling, from: "from-violet-500", to: "to-indigo-700" }, - plug: { icon: Plug, from: "from-amber-500", to: "to-orange-700" }, - tbc: { icon: Flame, from: "from-lime-500", to: "to-emerald-800" }, - wotlk: { icon: Snowflake, from: "from-sky-400", to: "to-blue-700" }, - gavel: { icon: Gavel, from: "from-yellow-500", to: "to-amber-700" }, - sparkles: { icon: Sparkles, from: "from-fuchsia-500", to: "to-purple-700" }, - swords: { icon: Swords, from: "from-rose-500", to: "to-red-800" }, - races: { icon: Users, from: "from-cyan-500", to: "to-blue-800" }, -}; -const DEFAULT_TILE = { icon: Puzzle, from: "from-slate-500", to: "to-slate-700" }; +export function ModulesPage({ + serverId, + onChanged, + onRegisterGuard: _onRegisterGuard, +}: { + serverId: string; + onChanged?: () => void; + onRegisterGuard?: (guard: UnsavedChangesGuard | null) => void; +}) { + const { locale } = useI18n(); -const STATUS: Record = { - soon: { label: "mod.status.soon", hint: "mod.hint.soon", tone: "border-violet-400/50 bg-violet-400/10 text-violet-300" }, - early: { label: "mod.status.early", hint: "mod.hint.early", tone: "border-warn/50 bg-warn/10 text-warn" }, - beta: { label: "mod.status.beta", hint: "mod.hint.beta", tone: "border-sky-400/50 bg-sky-400/10 text-sky-300" }, - release: { label: "mod.status.release", hint: "mod.hint.release", tone: "border-ok/50 bg-ok/10 text-ok" }, -}; + // Navigation tab + const [activeTab, setActiveTab] = useState("github"); -function SettingsPanel({ className, children }: { className?: string; children: ReactNode }) { - const ref = useRef(null); - useEffect(() => { - ref.current?.scrollIntoView({ block: "nearest", behavior: "smooth" }); - }, []); - return ( -
- {children} -
- ); -} - -function StatusBadge({ status }: { status: string }) { - const { t } = useI18n(); - const s = STATUS[status] ?? STATUS.release; - return ( - - {t(s.label)} - - ); -} - -function Tile({ icon, off }: { icon: string; off: boolean }) { - const tile = TILES[icon] ?? DEFAULT_TILE; - const Icon = tile.icon; - return ( -
- -
- ); -} - -/** The server's optional modules: square cards with a switch, the module's status, a link to GitHub and its settings. */ -export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId: string; onChanged?: () => void; onRegisterGuard?: (guard: UnsavedChangesGuard | null) => void }) { - const { t, locale } = useI18n(); - const human = useHuman(); - const [modules, setModules] = useState(null); - const [open, setOpen] = useState(null); + // Installed dynamic plugins + const [installedPlugins, setInstalledPlugins] = useState([]); const [error, setError] = useState(null); - const toggleLock = useRef(false); - const [toggling, setToggling] = useState(null); - const [changed, setChanged] = useState(false); - const [racesPatchStatus, setRacesPatchStatus] = useState(null); - const [racesInstalling, setRacesInstalling] = useState(false); - const [racesProgress, setRacesProgress] = useState(null); + const [notification, setNotification] = useState(null); + + // GitHub Intake & Analysis state const [githubUrl, setGithubUrl] = useState(""); const [analyzing, setAnalyzing] = useState(false); const [analysisError, setAnalysisError] = useState(null); const [report, setReport] = useState(null); + // Toolchain state + const [toolchain, setToolchain] = useState(null); + + // Controlled Build state + const [building, setBuilding] = useState(false); + const [buildResult, setBuildResult] = useState(null); + const [buildLogs, setBuildLogs] = useState([]); + + // Installation & SQL confirmation modal + const [installing, setInstalling] = useState(false); + const [showSqlDialog, setShowSqlDialog] = useState(false); + + // Action busy indicators + const [actionInProgress, setActionInProgress] = useState(null); + + const loadToolchain = useCallback(async () => { + try { + const tc = await api.previewToolchainStatus(); + setToolchain(tc); + } catch (e) { + console.error("Failed to load toolchain status", e); + } + }, []); + + const loadInstalledPlugins = useCallback(async () => { + try { + const plugins = await api.previewListInstalledPlugins(serverId); + setInstalledPlugins(plugins); + } catch { + // not critical if realm has no plugins yet + } + }, [serverId]); + + const load = useCallback(async () => { + try { + await loadInstalledPlugins(); + await loadToolchain(); + } catch (e) { + setError(asUiError(e)); + } + }, [loadInstalledPlugins, loadToolchain]); + + useEffect(() => { + void load(); + }, [load]); + + async function registerTestRealm() { + setActionInProgress("register-realm"); + setError(null); + try { + await api.previewRegisterTestRealm(); + setNotification( + locale === "ru" + ? "Экспериментальный тестовый реалм server-v03 успешно зарегистрирован!" + : "Experimental server-v03 test realm registered successfully!" + ); + onChanged?.(); + await load(); + } catch (e) { + setError(asUiError(e)); + } finally { + setActionInProgress(null); + } + } + + async function exportDiagnostics() { + setActionInProgress("export-diag"); + try { + const p = await api.previewExportDiagnostics(serverId); + setNotification( + locale === "ru" + ? `Диагностический отчёт сохранён: ${p}` + : `Diagnostic report saved: ${p}` + ); + } catch (e) { + setError(asUiError(e)); + } finally { + setActionInProgress(null); + } + } + async function runAnalysis() { if (!githubUrl.trim()) return; setAnalyzing(true); setAnalysisError(null); + setReport(null); + setBuildResult(null); try { const rep = await api.analyzeGithubModule(githubUrl.trim(), serverId); setReport(rep); @@ -112,565 +154,733 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId } } - function exportReportJson() { - if (!report) return; - const blob = new Blob([JSON.stringify(report, null, 2)], { type: "application/json" }); - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = `${report.repository_name}-compatibility-report.json`; - a.click(); - URL.revokeObjectURL(url); + async function startControlledBuild() { + if (!githubUrl.trim() && !report) return; + setBuilding(true); + setActiveTab("builds"); + setBuildLogs(["[CSM Controlled Build Engine] Initializing build environment..."]); + try { + const urlToBuild = report ? report.repository_name : githubUrl.trim(); + setBuildLogs((prev) => [ + ...prev, + `Target module: ${urlToBuild}`, + "Compiling C++ sources against CoA Plugin SDK v0.3 via MSVC...", + ]); + const res = await api.previewBuildModule(serverId, githubUrl.trim()); + setBuildResult(res); + setBuildLogs(res.log_output); + if (res.success) { + setNotification( + locale === "ru" + ? `Сборка успешно завершена! DLL квалифицирована: ${res.dll_sha256?.substring(0, 16)}...` + : `Build succeeded! Qualified DLL: ${res.dll_sha256?.substring(0, 16)}...` + ); + } else { + setAnalysisError( + locale === "ru" + ? "Сборка завершилась ошибкой. Проверьте диагностику компилятора во вкладке 'Сборки'." + : "Build failed. Check compiler diagnostics in the 'Builds' tab." + ); + } + } catch (e: unknown) { + setAnalysisError(e instanceof Error ? e.message : String(e)); + setBuildLogs((prev) => [...prev, `[FATAL BUILD ERROR]: ${String(e)}`]); + } finally { + setBuilding(false); + } } - const loadRacesStatus = useCallback(async () => { - try { - const st = await api.customRacesStatus(serverId); - setRacesPatchStatus(st); - } catch { - // ignore + function handleInstallClick() { + if (!buildResult || !buildResult.success) return; + if (report && report.sql_files.length > 0) { + setShowSqlDialog(true); + } else { + void performInstall(false); } - }, [serverId]); - const [guard, setGuard] = useState(null); + } - useEffect(() => { - onRegisterGuard?.(guard); - return () => onRegisterGuard?.(null); - }, [guard, onRegisterGuard]); - - const load = useCallback(async () => { - try { - setModules((await api.modulesList(serverId)).filter((m) => !m.hidden)); - await loadRacesStatus(); - } catch (e) { - setError(asUiError(e)); - } - }, [serverId, loadRacesStatus]); - - useEffect(() => { - void load(); - const un = listen("custom-races-progress", (e) => { - if (e.payload.id === serverId) { - setRacesProgress(e.payload); - } - }); - return () => { - void un.then((f) => f()); - }; - }, [load, serverId]); - - async function installClientPatch() { - setRacesInstalling(true); + async function performInstall(applySql: boolean) { + if (!buildResult) return; + setShowSqlDialog(false); + setInstalling(true); setError(null); try { - await api.customRacesInstall(serverId); - await loadRacesStatus(); - await load(); + const res = await api.previewInstallModule( + serverId, + buildResult.module_id, + buildResult.version, + applySql + ); + setNotification(res.message); + await loadInstalledPlugins(); + setActiveTab("installed"); onChanged?.(); } catch (e) { setError(asUiError(e)); } finally { - setRacesInstalling(false); - setRacesProgress(null); + setInstalling(false); } } - async function uninstallClientPatch() { - setRacesInstalling(true); + async function togglePlugin(moduleId: string, currentEnabled: boolean) { + setActionInProgress(`toggle-${moduleId}`); setError(null); try { - await api.customRacesUninstall(serverId); - await load(); - onChanged?.(); - } catch (e) { setError(asUiError(e)); } - finally { setRacesInstalling(false); } - } - - async function toggle(m: ModuleView) { - if (toggleLock.current || racesInstalling) return; - toggleLock.current = true; - setToggling(m.id); - setError(null); - try { - await api.moduleSetEnabled(serverId, m.id, !m.enabled); - setChanged(true); - await load(); - if (m.id === "custom-races") { - await loadRacesStatus(); - } + const msg = await api.previewToggleModule(serverId, moduleId, !currentEnabled); + setNotification(msg); + await loadInstalledPlugins(); onChanged?.(); } catch (e) { setError(asUiError(e)); - await load(); } finally { - toggleLock.current = false; - setToggling(null); + setActionInProgress(null); } } - const selected = modules?.find((m) => m.id === open) ?? null; - const selectedAt = modules?.findIndex((m) => m.id === open) ?? -1; + async function removePlugin(moduleId: string) { + if ( + !confirm( + locale === "ru" + ? `Удалить плагин '${moduleId}'? Базы данных и пользовательские настройки будут сохранены.` + : `Remove plugin '${moduleId}'? Databases and configurations will be preserved.` + ) + ) { + return; + } + setActionInProgress(`remove-${moduleId}`); + setError(null); + try { + const msg = await api.previewRemoveModule(serverId, moduleId); + setNotification(msg); + await loadInstalledPlugins(); + onChanged?.(); + } catch (e) { + setError(asUiError(e)); + } finally { + setActionInProgress(null); + } + } return ( -
-

{t("mod.title")}

-

{t("q.modules")}

-

{t("mod.intro")}

- - {changed &&

{t("mod.restart")}

} - {error &&

{error.human.code === "unknown" ? error.technical : human(error.human).message}

} - -
- {modules === null && !error &&

{t("overview.checking")}

} - {modules?.length === 0 && {t("mod.empty")}} - {modules?.map((m, i) => ( - - -
- -
-
-

{m.name}

- {m.version && {m.version}} - -
-

{m.description[locale] ?? m.description.en}

- {m.compatibility === "unsupported" &&

{t("realm.unsupported")}

} - {m.compatibility === "experimental" &&

{t("realm.experimental")}

} -
- {m.installed && m.switchable && ( - - )} - {m.installed && !m.switchable && m.status !== "soon" && m.compatibility !== "unsupported" && {t("mod.alwaysOn")}} - {!m.installed && m.status !== "soon" && {t("mod.notHere")}} -
- {toggling === m.id &&

{t("mod.switching")}

} - {m.id === "custom-races" && ( - -
-

{locale === "ru" ? "Установленная версия патча клиента: " : "Installed client patch version: "}{racesPatchStatus?.version ?? (locale === "ru" ? "не записана" : "not recorded")}

- {racesInstalling && racesProgress ? ( -
-
- - - {racesProgress.step} - - - {Math.round(racesProgress.percent * 100)}% - -
-
-
-
-
- ) : ( -
-
- {racesPatchStatus?.state === "enabled" && ( - - - {locale === "ru" ? "Патч клиента: Включен" : "Client Patch: Active"} - - )} - {racesPatchStatus?.state === "disabled" && ( - - - {locale === "ru" ? "Патч клиента: Отключен (.disabled)" : "Client Patch: Disabled (.disabled)"} - - )} - {racesPatchStatus?.state === "not-installed" && ( - - - {locale === "ru" ? "Патч клиента: Не установлен" : "Client Patch: Not Installed"} - - )} - {racesPatchStatus?.state === "partially-installed" && ( - - - {locale === "ru" ? `Патч клиента: ${racesPatchStatus.installedMpqs}/${racesPatchStatus.totalMpqs} MPQ` : `Client Patch: ${racesPatchStatus.installedMpqs}/${racesPatchStatus.totalMpqs} MPQ`} - - )} -
- {racesPatchStatus?.state === "partially-installed" &&

{locale === "ru" ? "Файлы отсутствуют или изменены. Восстановите патч клиента." : "Files are missing or changed. Repair the client patch."}

} - {( - - )} - {racesPatchStatus && racesPatchStatus.state !== "not-installed" && } -

{locale === "ru" ? (m.enabled ? "После установки патч будет включён." : "После установки патч останется отключённым: модуль сервера выключен или отсутствует.") : (m.enabled ? "The patch will be enabled after installation." : "The patch will stay disabled after installation: the server module is off or missing.")}

-
- )} -
- )} -
- - {!m.page && m.installed && m.has_settings && m.status !== "soon" && m.compatibility !== "unsupported" && ( - - )} -
- - {/* The settings open right under the row of the card they belong to, so they are never out of sight below a long grid. */} - {selected?.has_settings && !selected.page && selectedAt >= 0 && Math.floor(selectedAt / 2) === Math.floor(i / 2) && (i % 2 === 1 || i === modules.length - 1) && ( - -

{t("mod.settingsOf", { name: selected.name })}

- setChanged(true)} onRegisterGuard={setGuard} /> -
- )} - - ))} -
- - {/* Third-party GitHub Module Analyzer v0.3 */} -
-
- -

{locale === "ru" ? "Анализ сторонних модулей (GitHub)" : "Third-Party Module Analyzer (GitHub)"}

+
+ {/* Header & Sub-navigation */} +
+
+

+ + {locale === "ru" ? "Модули и плагины" : "Modules & Plugins"} + + MODULES PREVIEW + +

+

+ {locale === "ru" + ? "Автономная тестовая редакция для установки сторонних AzerothCore-модулей в виде динамических DLL." + : "Standalone experimental preview for installing third-party AzerothCore modules as independent DLLs."} +

-

- {locale === "ru" - ? "Проверка совместимости C++/SQL модулей AzerothCore с CoA Plugin SDK v0.3. Безопасный статический аудит без выполнения кода." - : "Compatibility evaluation of AzerothCore C++/SQL modules against CoA Plugin SDK v0.3. Safe static audit without code execution."} -

-
- setGithubUrl(e.target.value)} - placeholder="https://github.com/azerothcore/mod-congrats-on-level" - className="flex-1 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold" - disabled={analyzing} - /> + {/* Global actions */} +
+ +
+
- {analysisError && ( -
- {analysisError} + {/* Notification Banner */} + {notification && ( +
+ ✓ {notification} + +
+ )} + + {/* Error Banner */} + {error && ( +
+ ⚠ {error.technical || error.human.message} + +
+ )} + + {/* Toolchain Health Status Bar */} + {toolchain && ( +
+
+ {toolchain.msvc_available ? ( + + ) : ( + + )} + + MSVC (vcvars64): {toolchain.msvc_available ? "Ready" : "Missing"} +
- )} +
+ {toolchain.cmake_available ? ( + + ) : ( + + )} + + CMake: {toolchain.cmake_available ? "Ready" : "Missing"} + +
+
+ {toolchain.ninja_available ? ( + + ) : ( + + )} + + Ninja: {toolchain.ninja_available ? "Ready" : "Missing"} + +
+
+ {toolchain.sdk_available ? ( + + ) : ( + + )} + + Plugin SDK v0.3: {toolchain.sdk_available ? "Ready" : "Missing"} + +
+
+ )} - {report && ( - -
-
-
-

{report.repository_name}

- - {report.commit.substring(0, 8)} - - - {report.license_info.primary_license} - - {report.cache_hit !== undefined && report.cache_hit !== null && ( - - {report.cache_hit ? (locale === "ru" ? "КЭШ: ДА" : "CACHE: HIT") : (locale === "ru" ? "СКАЧАНО" : "FETCHED")} - - )} - {report.tree_digest && ( - - SHA:{report.tree_digest.substring(0, 8)} - - )} -
-

{report.repository_path}

-
+ {/* Tabs Header */} +
+ -
- -
- -
- {locale === "ru" - ? "Автоматическая сборка и установка сторонних модулей пока не поддерживаются. Доступен анализ совместимости." - : "Automated build and installation of third-party modules are not yet supported. Compatibility analysis is available."} -
-
-
+ + + + + +
+ + {/* TAB 1: GITHUB INSTALLATION & COMPATIBILITY WORKFLOW */} + {activeTab === "github" && ( +
+ +

+ {locale === "ru" ? "1. Анализ и инспекция модуля" : "1. Module Intake & Analysis"} +

+

+ {locale === "ru" + ? "Укажите ссылку на GitHub-репозиторий совместимого модуля AzerothCore (например, mod-congrats-on-level, mod-npc-buffer, mod-npc-enchanter, mod-reward-played-time)." + : "Paste GitHub repository URL for an AzerothCore module (e.g., mod-congrats-on-level, mod-npc-buffer, mod-npc-enchanter, mod-reward-played-time)."} +

+ +
+ setGithubUrl(e.target.value)} + placeholder="https://github.com/azerothcore/mod-congrats-on-level" + className="flex-1 rounded border border-line bg-bg px-3 py-1.5 text-xs text-ink placeholder:text-muted/50 focus:border-gold focus:outline-none" + /> +
- {/* Multi-dimensional Status Grid */} - {report.multi_dimensional_status && ( -
-
-
{locale === "ru" ? "Сборка" : "Build"}
-
- {report.multi_dimensional_status.build_status} + {analysisError && ( +
+ {analysisError} +
+ )} + + + {/* Analysis Report Card */} + {report && ( + +
+
+

+ {report.repository_name} + + ({report.commit.substring(0, 8)}) + +

+
+ + License: {report.license_info.primary_license} + + + SDK Host:{" "} + + {report.sdk_fingerprint ? report.sdk_fingerprint.substring(0, 16) + "..." : "Default"} + +
-
-
{locale === "ru" ? "Рантайм" : "Runtime"}
-
- {report.multi_dimensional_status.runtime_status} + + {/* Build and Install Buttons */} +
+ + + +
+
+ + {/* Multi-Dimensional Status */} + {report.multi_dimensional_status && ( +
+
+
{locale === "ru" ? "Сборка" : "Build"}
+
+ {report.multi_dimensional_status.build_status} +
+
+
+
{locale === "ru" ? "Рантайм" : "Runtime"}
+
+ {report.multi_dimensional_status.runtime_status} +
+
+
+
{locale === "ru" ? "Геймплей" : "Gameplay"}
+
+ {report.multi_dimensional_status.gameplay_status} +
+
+
+
{locale === "ru" ? "БД / SQL" : "Database"}
+
+ {report.multi_dimensional_status.db_status} +
+
+
+
{locale === "ru" ? "Безопасность" : "Security"}
+
+ {report.multi_dimensional_status.security_status} +
-
-
{locale === "ru" ? "Геймплей" : "Gameplay"}
-
- {report.multi_dimensional_status.gameplay_status} + )} + + {/* Findings List */} +
+

+ {locale === "ru" ? "Диагностические находки" : "Diagnostic Findings"} ({report.findings.length}) +

+ {report.findings.length === 0 ? ( +

✓ Замечаний и критических блокировок не обнаружено.

+ ) : ( +
    + {report.findings.map((f, idx) => ( +
  • +
    + + [{f.severity}] {f.rule_id} + + + {f.file}:{f.line} + +
    +

    {f.explanation}

    +

    ➜ {f.recommended_action}

    +
  • + ))} +
+ )} +
+ + )} +
+ )} + + {/* TAB 2: INSTALLED PLUGINS */} + {activeTab === "installed" && ( +
+
+

+ {locale === "ru" ? "Динамические плагины в реалме" : "Dynamic Plugins in Realm"} +

+ +
+ + {installedPlugins.length === 0 ? ( + + +

+ {locale === "ru" + ? "В этом реалме ещё нет установленных динамических плагинов." + : "No dynamic plugins installed in this realm yet."} +

+ +
+ ) : ( +
+ {installedPlugins.map((p) => ( + +
+
+

+ {p.name} + v{p.version} +

+

+ SHA256: {p.sha256.substring(0, 16)}... +

+
+ +
+ + {p.enabled + ? locale === "ru" + ? "Включён" + : "Enabled" + : locale === "ru" + ? "Отключён" + : "Disabled"} + + +
+
+ +
+ + {p.conf_files.length > 0 ? `${p.conf_files.length} config file(s)` : "No configs"} + + +
+
+ ))} +
+ )} +
+ )} + + {/* TAB 3: BUILDS & MSVC LOGS */} + {activeTab === "builds" && ( +
+ {/* Build Result Card */} + {buildResult && ( + +
+
+ {buildResult.success ? ( + + ) : ( + + )} +
+

+ {buildResult.module_name} ({buildResult.duration_seconds.toFixed(1)}s) +

+

+ {buildResult.success + ? `DLL Qualified: ${buildResult.dll_sha256?.substring(0, 24)}... (x64 /MD)` + : `Build failed with ${buildResult.errors.length} diagnostic error(s)`} +

-
-
{locale === "ru" ? "База данных" : "Database"}
-
- {report.multi_dimensional_status.db_status} -
+ + {buildResult.success && ( + + )} +
+ + {/* Error diagnostics */} + {buildResult.errors.length > 0 && ( +
+
MSVC Compiler / Linker Errors:
+
    + {buildResult.errors.map((err, i) => ( +
  • + [{err.error_code}] {err.file}:{err.line} - {err.message} +
  • + ))} +
-
-
{locale === "ru" ? "Безопасность" : "Security"}
-
- {report.multi_dimensional_status.security_status} -
+ )} + + )} + + {/* Real-time Terminal Output */} +
+
+ + + MSVC / CMake Build Output + + {buildLogs.length} lines +
+
+              {buildLogs.length === 0
+                ? "No build logs recorded yet. Start a build from the 'GitHub' tab."
+                : buildLogs.join("\n")}
+            
+
+
+ )} + + {/* TAB 4: TOOLCHAIN & ENVIRONMENT */} + {activeTab === "toolchain" && toolchain && ( + +

+ {locale === "ru" ? "Среда компиляции и Plugin SDK" : "Compilation Environment & Plugin SDK"} +

+

+ {locale === "ru" + ? "Controlled Build Engine использует изолированные рецепты сборки, MSVC x64 и заголовки SDK v0.3. Исходные CMakeLists.txt модулей не исполняются." + : "Controlled Build Engine uses isolated build recipes, MSVC x64 compiler, and SDK v0.3 headers. Upstream CMakeLists.txt is never executed."} +

+ +
+
+ MSVC Toolchain (vcvars64.bat) + {toolchain.vcvars64_path || "NOT FOUND"} +
+
+ CMake Executable + {toolchain.cmake_path || "NOT FOUND"} +
+
+ Ninja Build Driver + {toolchain.ninja_path || "NOT FOUND"} +
+
+ CoA Plugin SDK Directory + {toolchain.sdk_dir || "NOT FOUND"} +
+
+ Host SDK ABI Fingerprint + {toolchain.sdk_abi_fingerprint || "UNKNOWN"} +
+
+
+ )} + + {/* SQL Review & Confirmation Dialog Modal */} + {showSqlDialog && ( +
+ +
+ +

+ {locale === "ru" ? "Проверка SQL-миграций" : "SQL Migrations Review"} +

+
+

+ {locale === "ru" + ? "Этот модуль содержит SQL-файлы данных или структуры. MySQL DDL не поддерживает откат через обычные транзакции." + : "This module contains SQL structure or data files. MySQL DDL does not support rollback via standard transactions."} +

+ + {report && ( +
+
+ + {locale === "ru" ? "Файлы миграций:" : "Migration Files:"} + +
    + {report.sql_files.map((s, idx) => ( +
  • • {s.file_path} ({s.statement_count} statements)
  • + ))} +
+
+ +
+ + + {locale === "ru" + ? "Миграции будут применены к тестовой БД реалма. Удаление плагина сохранит таблицы нетронутыми." + : "Migrations will be applied to the realm test DB. Removing the plugin will preserve tables."} +
)} - {/* Findings & Diagnostics */} -
-

- {locale === "ru" ? "Диагностические выводы" : "Diagnostic Findings"} ({report.findings.length}) -

- {report.findings.length === 0 ? ( -

- {locale === "ru" ? "✓ Замечаний и конфликтов не обнаружено." : "✓ No compatibility findings or conflicts detected."} -

- ) : ( -
    - {report.findings.map((f, idx) => ( -
  • -
    - - [{f.severity}] {f.rule_id} - - {f.file}:{f.line} -
    -

    {f.explanation}

    -

    → {f.recommended_action}

    -
  • - ))} -
- )} +
+ +
- )} -
-
- ); -} - -function ModuleSettings({ serverId, module, onSaved, onRegisterGuard }: { serverId: string; module: ModuleView; onSaved: () => void; onRegisterGuard?: (guard: UnsavedChangesGuard | null) => void }) { - const { t, tn, locale } = useI18n(); - const sx = useSchemaText(); - const human = useHuman(); - const [advanced, setAdvanced] = useState(false); - const [items, setItems] = useState(null); - const [edits, setEdits] = useState>({}); - const [busy, setBusy] = useState(false); - const [error, setError] = useState(null); - const [note, setNote] = useState(null); - const [query, setQuery] = useState(""); - const [fieldErrors, setFieldErrors] = useState>({}); - - useEffect(() => { - let cancelled = false; - setItems(null); - setEdits({}); - setNote(null); - setError(null); - setFieldErrors({}); - void api.moduleSettings(serverId, module.id).then((s) => { if (!cancelled) setItems(s); }).catch((e) => { if (!cancelled) setError(asUiError(e)); }); - return () => { cancelled = true; }; - }, [serverId, module.id]); - - async function save(): Promise { - const errors: Record = {}; - for (const [key, value] of Object.entries(edits)) { - const field = moduleField(key, locale, items?.find(item => item.key === key)?.field); - if (field && ["int", "float", "range"].includes(field.type)) { - const number = Number(value); - const message = !value.trim() || !Number.isFinite(number) ? t("set.enterNumber") - : field.type === "int" && !Number.isInteger(number) ? t("set.enterInt") - : field.min !== undefined && number < field.min ? t("set.atLeast", { n: field.min }) - : field.max !== undefined && number > field.max ? t("set.atMost", { n: field.max }) : null; - if (message) errors[key] = message; - } - } - setFieldErrors(errors); - if (Object.keys(errors).length) return false; - setBusy(true); - setError(null); - setNote(null); - try { - const done = await api.moduleSaveSettings(serverId, module.id, edits); - setEdits({}); - setItems(await api.moduleSettings(serverId, module.id)); - if (done.length) { - onSaved(); - setNote(t("mod.saved", { n: done.length })); - } - return true; - } catch (e) { - setError(asUiError(e)); - return false; - } finally { - setBusy(false); - } - } - - const dirty = Object.keys(edits).length > 0; - - useEffect(() => { - if (dirty) { - onRegisterGuard?.({ - isDirty: () => Object.keys(edits).length > 0, - save: () => save(), - discard: () => { - setEdits({}); - setFieldErrors({}); - setNote(null); - }, - }); - } else { - onRegisterGuard?.(null); - } - return () => onRegisterGuard?.(null); - }, [dirty, edits, onRegisterGuard]); - const edit = (key: string, value: string) => setEdits(previous => { - const next = { ...previous }; - if (value === items?.find(item => item.key === key)?.value) delete next[key]; - else next[key] = value; - return next; - }); - const available = items?.filter(s => s.key !== moduleEnableKey(module.id)) ?? []; - const advancedCount = available.filter(s => !auctionWeightKey(s.key) && (!moduleField(s.key, locale, s.field) || moduleField(s.key, locale, s.field)?.advanced)).length; - const visible = available.filter(s => { - if (module.id === "ah-bot" && auctionWeightKey(s.key)) return false; - const field = moduleField(s.key, locale, s.field); - if (!advanced && !query.trim() && (!field || field.advanced)) return false; - const title = field ? (s.field ? field.title : sx.title({ key: s.key, title: field.title })) : s.key; - const description = field ? (s.field ? field.description : sx.description({ key: s.key, description: field.description })) : s.doc; - return `${title} ${description} ${s.key}`.toLocaleLowerCase(locale).includes(query.trim().toLocaleLowerCase(locale)); - }); - return ( -
- {items === null && !error && } - {module.id === "npc-enchanter" && ( -
-

{t("mod.enchanter.add")}

-

{t("mod.enchanter.remove")}

-
- )} - {module.id === "ah-bot" && ( -
-

{t("mod.ahbot.setup")}

-
- )} - {available.length >= 10 && setQuery(e.target.value)} aria-label={t("set.search")} placeholder={t("set.search")} className="mb-3 w-full rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold" />} - {advancedCount > 0 && } - {module.id === "ah-bot" && setEdits(previous => { - const next = { ...previous }; - for (const [key, value] of Object.entries(changes)) { - if (value === items?.find(item => item.key === key)?.value) delete next[key]; - else next[key] = value; - } - return next; - })} />} - {items && !visible.length && !available.some(s => module.id === "ah-bot" && auctionWeightKey(s.key)) &&

{t(available.length ? "all.none" : "mod.noSettings")}

} -
    - {visible.map((s) => { - const field = moduleField(s.key, locale, s.field); - const title = field ? (s.field ? field.title : sx.title({ key: s.key, title: field.title })) : s.key; - const description = field ? (s.field ? field.description : sx.description({ key: s.key, description: field.description })) : s.doc; - const value = edits[s.key] ?? s.value; - const normalized = canonicalModuleValue(s.key, value); - const options = field?.options ?? []; - const bool = field?.type === "bool" || /^(true|false)$/i.test(normalized) || (/^(0|1)$/.test(normalized) && /(?:\.Enable(?:d)?$|Enable\/Disable)/i.test(s.key + " " + s.doc)); - const on = /^(1|true|yes|on)$/i.test(normalized); - const id = `${module.id}-${s.key}`; - const controlClass = "selectable w-56 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold"; - return ( -
  • -
    -
    {s.key in edits && {t("set.changed")}}
    - {bool ? - : options.length ? - : field?.type === "range" ?
    edit(s.key, e.target.value)} aria-valuetext={`${Math.round(Number(normalized) * 100)}%`} className="min-w-0 flex-1 accent-gold" />{Math.round(Number(normalized) * 100)}%
    - : edit(s.key, e.target.value)} className={controlClass} />} -
    - {description &&

    {description}

    } - {fieldErrors[s.key] &&

    {fieldErrors[s.key]}

    } - {advanced &&

    {s.key}

    } - {s.default !== null && (edits[s.key] ?? s.value) !== s.default && ( - - )} -
  • - ); })} -
- {available.length > 0 &&
- - {dirty && } - {note && {note}} -
} - {error &&

{error.human.code === "unknown" ? error.technical : human(error.human).message}

} - {dirty && ( -
- {tn("set.unsaved", Object.keys(edits).length)} -
- - -
)}
diff --git a/src/screens/Shell.tsx b/src/screens/Shell.tsx index 4ee61ed..d17c142 100644 --- a/src/screens/Shell.tsx +++ b/src/screens/Shell.tsx @@ -103,7 +103,10 @@ export function Shell(props: {