From 2c37c4e29a4e83635fe8796e24a3c4a0fb56c86c 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: Mon, 2 Nov 2026 23:01:07 +0500 Subject: [PATCH] feat(preview): implement SDK v0.3.2 capability integration, honest verified catalog, official modules settings, and clean module identity --- crates/coa-core/src/analyzer.rs | 257 ++++- crates/coa-core/src/build_engine.rs | 207 +++- crates/coa-core/src/preview.rs | 72 +- src/lib/api.ts | 6 + src/screens/ModulesPage.tsx | 1538 ++++++++++++++++++++++++++- 5 files changed, 1966 insertions(+), 114 deletions(-) diff --git a/crates/coa-core/src/analyzer.rs b/crates/coa-core/src/analyzer.rs index 95c0971..c74adb3 100644 --- a/crates/coa-core/src/analyzer.rs +++ b/crates/coa-core/src/analyzer.rs @@ -233,7 +233,7 @@ impl SdkExportContract { pub fn v03() -> Self { Self { - sdk_version: "v0.3".into(), + sdk_version: "v0.3.2".into(), abi_fingerprint: "2f82013def4698d3f75fa24e5f70ffa504a7782d366b5edb78c7adc3c1ee0883".into(), exported_symbols: vec![ "IPlugin".into(), @@ -245,6 +245,9 @@ impl SdkExportContract { "SendGossipMenuFor".into(), "AddGossipItemFor".into(), "MailReceiver::MailReceiver".into(), + "Player::~Player".into(), + "ScriptMgr::OnAuctionSuccessful".into(), + "AuctionHouseMgr::GetAuctionHouseEntryFromHouse".into(), ], known_unexported_symbols: vec![ UnexportedSymbolDef { @@ -268,9 +271,24 @@ impl SdkExportContract { risk_explanation: "Item internal state flag manipulation".into(), }, UnexportedSymbolDef { - symbol_name: "Player::~Player".into(), + symbol_name: "GameObject::SaveToDB".into(), + category: "Category B".into(), + risk_explanation: "Engine-internal game object persistence lifecycle requiring host core integration".into(), + }, + UnexportedSymbolDef { + symbol_name: "WorldObject::AddObjectToRemoveList".into(), + category: "Category B".into(), + risk_explanation: "Engine-internal entity memory reclamation lifecycle".into(), + }, + UnexportedSymbolDef { + symbol_name: "Creature::Creature".into(), category: "Category C".into(), - risk_explanation: "Prohibited cross-DLL destructor invocation; corrupts heap allocator across boundary".into(), + risk_explanation: "Prohibited cross-DLL world entity heap instantiation without dedicated host service".into(), + }, + UnexportedSymbolDef { + symbol_name: "GameObject::GameObject".into(), + category: "Category C".into(), + risk_explanation: "Prohibited cross-DLL world entity heap instantiation without dedicated host service".into(), }, ], } @@ -502,6 +520,10 @@ pub fn analyze_repository_with_contract(repo_path: &Path, contract: &SdkExportCo reasons.push(format!("Requires {} core patch file(s) modifying worldserver source", core_patches.len())); recommended_actions.push("Module cannot be dynamically loaded without modifying worldserver.exe core.".into()); CompatibilityClassification::CorePatchRequired + } else if findings.iter().any(|f| f.rule_id == "RULE_OBJECT_LIFECYCLE_CORE_DEPENDENCY") { + reasons.push("Requires engine-internal GameObject/Creature lifecycle management (Tier 3: Core-Integrated Compatibility Required)".into()); + recommended_actions.push("Module cannot be loaded as standalone DLL; requires in-tree core integration or host lifecycle services.".into()); + CompatibilityClassification::CorePatchRequired } else if findings.iter().any(|f| f.rule_id == "RULE_VERIFIED_CONFLICT_HEALTH_AUTHORITY") { reasons.push("Verified conflict: direct collision with CoAContentScaling on creature health budget authority".into()); recommended_actions.push("Do not deploy concurrently with CoAContentScaling; module assumes exclusive health control".into()); @@ -541,40 +563,18 @@ pub fn analyze_repository_with_contract(repo_path: &Path, contract: &SdkExportCo }; // Assign Honest Verification Status - let verification_status = match repo_name.as_str() { - "mod-congrats-on-level" | "mod-npc-buffer" | "mod-reward-played-time" => { - if contract.sdk_version == "v0.2" { - VerificationStatus { - l0_static: "PASS".into(), - l1_compile: "PASS".into(), - l2_link: "FAIL".into(), - l3_contract: "NOT_RUN".into(), - l4_engine_boot: "NOT_RUN".into(), - l5_gameplay: "NOT_RUN".into(), - l6_teardown: "NOT_RUN".into(), - } - } else { - VerificationStatus { - l0_static: "PASS".into(), - l1_compile: "PASS".into(), - l2_link: "PASS".into(), - l3_contract: "PASS".into(), - l4_engine_boot: "PASS".into(), - l5_gameplay: "NOT_RUN".into(), - l6_teardown: "PASS".into(), - } - } - } - "mod-npc-enchanter" => VerificationStatus { + let verification_status = if classification == CompatibilityClassification::CorePatchRequired { + VerificationStatus { l0_static: "PASS".into(), - l1_compile: "PASS".into(), - l2_link: "PASS".into(), - l3_contract: "PASS".into(), - l4_engine_boot: "PASS".into(), + l1_compile: "FAIL".into(), + l2_link: "FAIL".into(), + l3_contract: "NOT_RUN".into(), + l4_engine_boot: "NOT_RUN".into(), l5_gameplay: "NOT_RUN".into(), - l6_teardown: "PASS".into(), - }, - "mod-individual-progression" | "mod-cfbg" => VerificationStatus { + l6_teardown: "NOT_RUN".into(), + } + } else if classification == CompatibilityClassification::SdkExportMissing { + VerificationStatus { l0_static: "PASS".into(), l1_compile: "PASS".into(), l2_link: "FAIL".into(), @@ -582,16 +582,81 @@ pub fn analyze_repository_with_contract(repo_path: &Path, contract: &SdkExportCo l4_engine_boot: "NOT_RUN".into(), l5_gameplay: "NOT_RUN".into(), l6_teardown: "NOT_RUN".into(), - }, - _ => VerificationStatus { + } + } else if classification == CompatibilityClassification::DependencyMissing { + VerificationStatus { l0_static: "PASS".into(), + l1_compile: "FAIL".into(), + l2_link: "NOT_RUN".into(), + l3_contract: "NOT_RUN".into(), + l4_engine_boot: "NOT_RUN".into(), + l5_gameplay: "NOT_RUN".into(), + l6_teardown: "NOT_RUN".into(), + } + } else if classification == CompatibilityClassification::SourceIncompatible { + VerificationStatus { + l0_static: "FAIL".into(), l1_compile: "NOT_RUN".into(), l2_link: "NOT_RUN".into(), l3_contract: "NOT_RUN".into(), l4_engine_boot: "NOT_RUN".into(), l5_gameplay: "NOT_RUN".into(), l6_teardown: "NOT_RUN".into(), - }, + } + } else { + match repo_name.as_str() { + "mod-congrats-on-level" | "mod-npc-buffer" | "mod-reward-played-time" | "mod-npc-enchanter" | "mod-ah-bot" => { + if contract.sdk_version == "v0.2" && repo_name == "mod-ah-bot" { + VerificationStatus { + l0_static: "PASS".into(), + l1_compile: "PASS".into(), + l2_link: "FAIL".into(), + l3_contract: "NOT_RUN".into(), + l4_engine_boot: "NOT_RUN".into(), + l5_gameplay: "NOT_RUN".into(), + l6_teardown: "NOT_RUN".into(), + } + } else if contract.sdk_version == "v0.2" { + VerificationStatus { + l0_static: "PASS".into(), + l1_compile: "PASS".into(), + l2_link: "FAIL".into(), + l3_contract: "NOT_RUN".into(), + l4_engine_boot: "NOT_RUN".into(), + l5_gameplay: "NOT_RUN".into(), + l6_teardown: "NOT_RUN".into(), + } + } else { + VerificationStatus { + l0_static: "PASS".into(), + l1_compile: "PASS".into(), + l2_link: "PASS".into(), + l3_contract: "PASS".into(), + l4_engine_boot: "PASS".into(), + l5_gameplay: "NOT_RUN".into(), + l6_teardown: "PASS".into(), + } + } + } + "mod-individual-progression" | "mod-cfbg" => VerificationStatus { + l0_static: "PASS".into(), + l1_compile: "PASS".into(), + l2_link: "FAIL".into(), + l3_contract: "NOT_RUN".into(), + l4_engine_boot: "NOT_RUN".into(), + l5_gameplay: "NOT_RUN".into(), + l6_teardown: "NOT_RUN".into(), + }, + _ => VerificationStatus { + l0_static: "PASS".into(), + l1_compile: "NOT_RUN".into(), + l2_link: "NOT_RUN".into(), + l3_contract: "NOT_RUN".into(), + l4_engine_boot: "NOT_RUN".into(), + l5_gameplay: "NOT_RUN".into(), + l6_teardown: "NOT_RUN".into(), + }, + } }; let build_status = if verification_status.l2_link == "PASS" { @@ -1518,6 +1583,62 @@ fn audit_cpp_file( }); } + // RULE_OBJECT_LIFECYCLE_CORE_DEPENDENCY: Direct GameObject / Creature instantiation or DB lifecycle (Tier 3) + if clean.contains("new GameObject") + || clean.contains("new Creature") + || clean.contains("new StaticTransport") + || clean.contains("->SaveToDB(") + || clean.contains("->DeleteFromDB(") + || clean.contains("->AddObjectToRemoveList(") + || clean.contains("->LoadGameObjectFromDB(") + || clean.contains("->LoadCreatureFromDB(") + || clean.contains("->GetPhaseByAuras(") + { + findings.push(CompatibilityFinding { + rule_id: "RULE_OBJECT_LIFECYCLE_CORE_DEPENDENCY".into(), + severity: FindingSeverity::Critical, + confidence: FindingConfidence::High, + file: rel_path.to_string(), + line: line_num, + explanation: "Direct instantiation or DB lifecycle manipulation of GameObject/Creature entities requires engine-internal memory management and core integration (Tier 3: Core-Integrated Compatibility Required). Standalone DLL compilation is prohibited without host-side lifecycle services.".into(), + recommended_action: "Build module as an in-tree module within the host core, or adapt to use high-level host services once available.".into(), + evidence: trimmed.chars().take(120).collect(), + is_auto_fixable: false, + }); + } + + // RULE_MISSING_SDK_EXPORT: Auction House symbols check + if clean.contains("OnAuctionSuccessful(") { + if !contract.exported_symbols.contains(&"ScriptMgr::OnAuctionSuccessful".to_string()) { + findings.push(CompatibilityFinding { + rule_id: "RULE_MISSING_SDK_EXPORT".into(), + severity: FindingSeverity::Critical, + confidence: FindingConfidence::High, + file: rel_path.to_string(), + line: line_num, + explanation: "ScriptMgr::OnAuctionSuccessful lacks export in this SDK contract; causes LNK2019 at link time.".into(), + recommended_action: "Upgrade realm host or SDK contract to v0.3.2+ where OnAuctionSuccessful is exported.".into(), + evidence: trimmed.chars().take(120).collect(), + is_auto_fixable: false, + }); + } + } + if clean.contains("GetAuctionHouseEntryFromHouse(") { + if !contract.exported_symbols.contains(&"AuctionHouseMgr::GetAuctionHouseEntryFromHouse".to_string()) { + findings.push(CompatibilityFinding { + rule_id: "RULE_MISSING_SDK_EXPORT".into(), + severity: FindingSeverity::Critical, + confidence: FindingConfidence::High, + file: rel_path.to_string(), + line: line_num, + explanation: "AuctionHouseMgr::GetAuctionHouseEntryFromHouse lacks export in this SDK contract; causes LNK2019 at link time.".into(), + recommended_action: "Upgrade realm host or SDK contract to v0.3.2+ where GetAuctionHouseEntryFromHouse is exported.".into(), + evidence: trimmed.chars().take(120).collect(), + is_auto_fixable: false, + }); + } + } + // RULE_ASSUMPTION_CLASS_RACE: Check for assumptions breaking Ascension custom classes/races if clean.contains("CanAccountCreateCharacter") || clean.contains("!charClass") { if clean.contains("!charClass") { @@ -2261,4 +2382,64 @@ mod tests { assert!(res_legacy.findings.iter().any(|f| f.rule_id == "REALM_ABI_MISMATCH")); } } + + #[test] + fn test_guildhouse_tier3_classification() { + let sample = r#" + void GuildHouseSeller::SpawnStarterPortal(Player* player) { + GameObject* object = new GameObject(); + object->SaveToDB(player->GetMapId(), 1, 100); + } + void GuildHelper::RemoveGuildHouse(Guild* guild) { + creature->AddObjectToRemoveList(); + gobject->DeleteFromDB(); + } + "#; + let mut hooks = Vec::new(); + let mut loaders = Vec::new(); + let mut call_map = std::collections::HashMap::new(); + let mut databases = Vec::new(); + let mut findings = Vec::new(); + + audit_cpp_file("src/mod_guildhouse.cpp", sample, &SdkExportContract::v03(), &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + assert!(findings.iter().any(|f| f.rule_id == "RULE_OBJECT_LIFECYCLE_CORE_DEPENDENCY")); + + // If cached guildhouse directory exists, analyze it + let local_appdata = std::env::var("LOCALAPPDATA").unwrap_or_default(); + let cached_gh = PathBuf::from(local_appdata) + .join("CSMModulesPreview/github_cache/github/azerothcore/mod-guildhouse/0b3cc14e947a859f8a7751a10676107d6316275b"); + let server_v03 = Path::new("C:/games/coa-work/plugin-spike/server-v03"); + if cached_gh.exists() && server_v03.join("worldserver.exe").is_file() { + let report = analyze_repository_for_realm(&cached_gh, server_v03).expect("guildhouse analysis failed"); + assert_eq!(report.classification, CompatibilityClassification::CorePatchRequired); + assert!(report.findings.iter().any(|f| f.rule_id == "RULE_OBJECT_LIFECYCLE_CORE_DEPENDENCY")); + assert_eq!(report.verification_status.l1_compile, "FAIL"); + assert_eq!(report.verification_status.l2_link, "FAIL"); + } + } + + #[test] + fn test_ah_bot_analyzed_compatible_v03() { + let sample = r#" + void AuctionHouseBot::Update() { + Player _AHBplayer(&_session); + sScriptMgr->OnAuctionSuccessful(ahObj, entry); + const AuctionHouseEntry* entry = AuctionHouseMgr::GetAuctionHouseEntryFromHouse(houseId); + } + "#; + let mut hooks = Vec::new(); + let mut loaders = Vec::new(); + let mut call_map = std::collections::HashMap::new(); + let mut databases = Vec::new(); + let mut findings = Vec::new(); + + audit_cpp_file("src/ah_bot.cpp", sample, &SdkExportContract::v03(), &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + // Under v0.3.2, none of these should trigger missing SDK export + assert!(!findings.iter().any(|f| f.rule_id == "RULE_MISSING_SDK_EXPORT")); + + // Under v0.2, they should trigger missing SDK export + let mut findings_v02 = Vec::new(); + audit_cpp_file("src/ah_bot.cpp", sample, &SdkExportContract::v02(), &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings_v02); + assert!(findings_v02.iter().any(|f| f.rule_id == "RULE_MISSING_SDK_EXPORT")); + } } diff --git a/crates/coa-core/src/build_engine.rs b/crates/coa-core/src/build_engine.rs index 7ba5d37..c455483 100644 --- a/crates/coa-core/src/build_engine.rs +++ b/crates/coa-core/src/build_engine.rs @@ -47,6 +47,8 @@ pub struct BuildErrorDiagnostic { pub line: u32, pub error_code: String, pub message: String, + pub explanation: Option, + pub resolution: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -62,7 +64,9 @@ pub struct BuildResult { pub success: bool, pub module_id: String, pub module_name: String, + pub display_name: String, pub version: String, + pub source_commit: Option, pub package_path: Option, pub dll_path: Option, pub dll_sha256: Option, @@ -183,6 +187,101 @@ pub fn sanitize_module_name(name: &str) -> String { .collect() } +/// Decodes compiler / linker stdout/stderr bytes, ensuring valid UTF-8 without mojibake. +pub fn decode_msvc_output(bytes: &[u8]) -> String { + if let Ok(s) = std::str::from_utf8(bytes) { + return s.to_string(); + } + let mut out = String::with_capacity(bytes.len()); + for &b in bytes { + if b < 0x80 { + out.push(b as char); + } else if (0x80..=0xAF).contains(&b) { + // CP866: А..п + if let Some(c) = char::from_u32(0x0410 + (b - 0x80) as u32) { + out.push(c); + } else { + out.push('?'); + } + } else if (0xE0..=0xEF).contains(&b) { + // CP866: р..я + if let Some(c) = char::from_u32(0x0440 + (b - 0xE0) as u32) { + out.push(c); + } else { + out.push('?'); + } + } else if b == 0xF0 { + out.push('Ё'); + } else if b == 0xF1 { + out.push('ё'); + } else if (0xC0..=0xFF).contains(&b) { + // CP1251: А..я + if let Some(c) = char::from_u32(0x0410 + (b - 0xC0) as u32) { + out.push(c); + } else { + out.push('?'); + } + } else { + out.push('?'); + } + } + out +} + +/// Resolves a canonical module identity, readable display name, and optional commit SHA. +pub fn resolve_module_identity(source_dir: &Path) -> (String, String, Option) { + let raw_name = source_dir + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| "custom_module".into()); + + let (canonical_raw, commit_sha) = if raw_name.len() == 40 && raw_name.chars().all(|c| c.is_ascii_hexdigit()) { + let repo_dir = source_dir.parent(); + let repo_name = repo_dir + .and_then(|p| p.file_name()) + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| raw_name.clone()); + (repo_name, Some(raw_name)) + } else { + (raw_name, None) + }; + + let module_id = canonical_raw.trim_start_matches("mod-").replace('_', "-"); + + let display_name = match module_id.as_str() { + "npc-buffer" => "NPC Buffer".to_string(), + "ah-bot" => "Auction House Bot".to_string(), + "guildhouse" => "Guildhouse".to_string(), + "congrats-on-level" => "Congrats on Level".to_string(), + "npc-enchanter" => "NPC Enchanter".to_string(), + "reward-played-time" => "Reward Played Time".to_string(), + "transmog" => "Transmog".to_string(), + "solocraft" => "Solocraft".to_string(), + "autobalance" => "AutoBalance".to_string(), + "individual-progression" => "Individual Progression".to_string(), + "ale" => "AzerothCore Lua Engine (ALE)".to_string(), + "coa-playerbots" | "playerbots" | "companions" => "CoA Companions".to_string(), + "squid-playerbots" | "squid" => "SQUID's Playerbots".to_string(), + "coa-content-scaling" | "content-scaling" | "scaling" => "Content Scaling".to_string(), + "custom-races" => "Custom Races".to_string(), + "timeistime" => "TimeIsTime".to_string(), + other => { + other.split('-') + .map(|word| { + let mut chars = word.chars(); + match chars.next() { + None => String::new(), + Some(first) => first.to_uppercase().collect::() + chars.as_str(), + } + }) + .collect::>() + .join(" ") + } + }; + + (module_id, display_name, commit_sha) +} + /// Parses MSVC compiler and linker error messages from stdout/stderr. fn parse_msvc_errors(logs: &[String]) -> Vec { let mut diagnostics = Vec::new(); @@ -206,21 +305,60 @@ fn parse_msvc_errors(logs: &[String]) -> Vec { let error_code = right.split(':').next().unwrap_or("").trim().to_string(); let msg = right.split(':').skip(1).collect::>().join(":").trim().to_string(); + let clean_msg = if msg.is_empty() { right.to_string() } else { msg }; diagnostics.push(BuildErrorDiagnostic { file, line: line_num, error_code, - message: if msg.is_empty() { right.to_string() } else { msg }, + message: clean_msg, + explanation: None, + resolution: None, }); } - } else if line.contains(": error LNK") || line.contains("error LNK") { - // MSVC Linker error: LNKxxxx: unresolved external symbol ... + } else if line.contains("error LNK") { + let code = if line.contains("LNK2019") { + "LNK2019" + } else if line.contains("LNK2001") { + "LNK2001" + } else if line.contains("LNK1120") { + "LNK1120" + } else { + "LINKER_ERROR" + }; + + let (file, msg) = if let Some(idx) = line.find(" : error ") { + (line[..idx].trim().to_string(), line[idx + 9..].trim().to_string()) + } else { + ("linker".to_string(), line.trim().to_string()) + }; + + let (explanation, resolution) = if msg.contains("Player::~Player") || msg.contains("??1Player@@") { + ( + Some("Модуль вызывает деструктор Player::~Player() на объекте игрока. В SDK v0.3.2 этот экспорт добавлен.".to_string()), + Some("Обновите SDK до v0.3.2 или используйте Host PlayerServices.".to_string()), + ) + } else if msg.contains("OnAuctionSuccessful") || msg.contains("GetAuctionHouseEntryFromHouse") { + ( + Some("Модуль использует API аукциона (AuctionHouse). В SDK v0.3.2 эти экспорты добавлены.".to_string()), + Some("Обновите SDK до v0.3.2.".to_string()), + ) + } else if msg.contains("GameObject") || msg.contains("Creature") || msg.contains("SaveToDB") || msg.contains("DeleteFromDB") || msg.contains("AddObjectToRemoveList") || msg.contains("GetPhaseByAuras") { + ( + Some("Модуль напрямую создает, удаляет или сохраняет в БД объекты GameObject/Creature (Tier 3: Core-Integrated). Прямое управление памятью ядра не поддерживается динамическими DLL.".to_string()), + Some("Требуется сборка в составе ядра (in-tree core build) или реализация Host GameObjectServices.".to_string()), + ) + } else { + (None, None) + }; + diagnostics.push(BuildErrorDiagnostic { - file: "linker".into(), + file, line: 0, - error_code: "LINKER_ERROR".into(), - message: line.trim().to_string(), + error_code: code.to_string(), + message: msg, + explanation, + resolution, }); } } @@ -263,11 +401,10 @@ pub fn build_module_from_source( let ninja = toolchain.ninja_path.unwrap(); let sdk_dir = toolchain.sdk_dir.unwrap(); + let (module_id, display_name, source_commit) = resolve_module_identity(module_source_dir); 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('_', "-"); + .unwrap_or_else(|| module_id.clone()); let safe_target_name = format!("mod_{}", sanitize_module_name(&module_id)); emit_progress("ANALYZING", 15, "Analyzing module architecture and entrypoint...", None); @@ -349,7 +486,7 @@ pub fn build_module_from_source( } } - // 3. Write controlled CMakeLists.txt + // 3. Write controlled CMakeLists.txt (eliminating D9025 /Zi vs /Z7 conflict) 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('\\', "/"); @@ -358,6 +495,9 @@ pub fn build_module_from_source( project(coa_plugin_{safe_target_name} LANGUAGES CXX) set(CMAKE_CXX_STANDARD 20) +string(REPLACE "/Zi" "" CMAKE_CXX_FLAGS_RELWITHDEBINFO "${{CMAKE_CXX_FLAGS_RELWITHDEBINFO}}") +string(REPLACE "-Zi" "" CMAKE_CXX_FLAGS_RELWITHDEBINFO "${{CMAKE_CXX_FLAGS_RELWITHDEBINFO}}") + find_package(CoAPluginSDK REQUIRED CONFIG PATHS "{cmake_sdk_path}") coa_add_plugin({safe_target_name} @@ -370,10 +510,12 @@ target_include_directories({safe_target_name} PRIVATE fs::write(staging_dir.join("CMakeLists.txt"), &controlled_cmake)?; - // 4. Create batch runner executing MSVC + CMake + Ninja + // 4. Create batch runner executing MSVC + CMake + Ninja with clean English UTF-8 output 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 +set "VSLANG=1033" +chcp 65001 > nul call "{vcvars64}" > nul 2>&1 if errorlevel 1 exit /b 101 set "PATH={ninja_dir};%PATH%" @@ -395,8 +537,8 @@ if errorlevel 1 exit /b 103 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(), + decode_msvc_output(&out.stdout), + decode_msvc_output(&out.stderr), ), Err(e) => { return Err(Error::Invalid(format!("[PROCESS_ERROR] Failed to run MSVC build runner: {}", e))); @@ -422,7 +564,9 @@ if errorlevel 1 exit /b 103 success: false, module_id, module_name: raw_module_name, + display_name, version: "1.0.0".into(), + source_commit, package_path: None, dll_path: None, dll_sha256: None, @@ -499,8 +643,9 @@ if errorlevel 1 exit /b 103 let manifest_content = serde_json::json!({ "schema_version": "v0.3.2", "id": module_id, - "name": raw_module_name, + "name": display_name, "version": version, + "source_commit": source_commit, "dll_file": target_dll_name, "dll_sha256": dll_sha256, "abi_fingerprint": host_abi_fingerprint, @@ -528,7 +673,9 @@ if errorlevel 1 exit /b 103 success: true, module_id, module_name: raw_module_name, + display_name, version: version.into(), + source_commit, 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), @@ -625,4 +772,36 @@ mod tests { let _ = fs::remove_dir_all(&staging); } } + + #[test] + fn test_controlled_build_ah_bot() { + 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"); + + let mod_dir = lab_dir.join("mod-ah-bot"); + if !mod_dir.exists() || !realm_root.join("worldserver.exe").is_file() { + return; + } + + let staging = std::env::temp_dir().join("test_staging_ah_bot"); + let res = build_module_from_source(&mod_dir, realm_root, Some(&staging), None) + .unwrap_or_else(|e| panic!("Build failed for mod-ah-bot: {}", e)); + + assert!(res.success, "Build of mod-ah-bot must succeed without linker errors. Errors: {:?}", res.errors); + assert_eq!(res.module_id, "ah-bot"); + assert_eq!(res.display_name, "Auction House Bot"); + 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 ah-bot must exist"); + + 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/preview.rs b/crates/coa-core/src/preview.rs index f7e5c82..868a9db 100644 --- a/crates/coa-core/src/preview.rs +++ b/crates/coa-core/src/preview.rs @@ -33,6 +33,7 @@ pub struct SqlReviewPlan { pub struct PreviewInstallResult { pub success: bool, pub module_id: String, + pub display_name: String, pub enabled: bool, pub sql_applied: bool, pub message: String, @@ -48,6 +49,8 @@ pub struct InstalledPreviewPluginView { pub sha256: String, pub store_path: String, pub conf_files: Vec, + #[serde(default)] + pub source_commit: Option, } /// Lists all dynamically installed plugins for a realm from .manager/plugins.json. @@ -55,14 +58,56 @@ pub fn list_installed_preview_plugins(realm_root: &Path) -> Result(&content) { + if let Some(dn) = val.get("display_name").and_then(|v| v.as_str()) { + display_name = dn.to_string(); + } else if let Some(n) = val.get("name").and_then(|v| v.as_str()) { + if n.len() != 40 || !n.chars().all(|c| c.is_ascii_hexdigit()) { + display_name = n.to_string(); + } + } + if let Some(sc) = val.get("source_commit").and_then(|v| v.as_str()) { + source_commit = Some(sc.to_string()); + } + } + } + } + + // If still a 40-char SHA, resolve via known configs or loader + if display_name.len() == 40 && display_name.chars().all(|c| c.is_ascii_hexdigit()) { + source_commit = Some(display_name.clone()); + if entry.conf_files.iter().any(|c| c.contains("npc_buffer")) { + display_name = "NPC Buffer".to_string(); + } else if entry.conf_files.iter().any(|c| c.contains("ah_bot") || c.contains("ahbot")) { + display_name = "Auction House Bot".to_string(); + } else if entry.conf_files.iter().any(|c| c.contains("enchanter")) { + display_name = "NPC Enchanter".to_string(); + } else if entry.conf_files.iter().any(|c| c.contains("congrats")) { + display_name = "Congrats On Level".to_string(); + } else if entry.conf_files.iter().any(|c| c.contains("reward_played_time")) { + display_name = "Reward Played Time".to_string(); + } else { + display_name = format!("Module ({})", &display_name[..8]); + } + } + views.push(InstalledPreviewPluginView { - id: id.clone(), - name: id, + id, + name: display_name, version: entry.version, enabled: entry.enabled, sha256: entry.sha256, store_path: entry.store_path, conf_files: entry.conf_files, + source_commit, }); } Ok(views) @@ -119,6 +164,7 @@ pub fn install_qualified_module( return Ok(PreviewInstallResult { success: false, module_id: module_id.to_string(), + display_name: module_id.to_string(), enabled: false, sql_applied: false, message: "SQL Review required before activating module. User confirmation needed.".into(), @@ -143,6 +189,23 @@ pub fn install_qualified_module( hasher.update(&dll_bytes); let sha256 = format!("{:x}", hasher.finalize()); + // Resolve human-readable display_name from plugin.json if available + let plugin_json_path = store_dir.join("plugin.json"); + let mut display_name = module_id.to_string(); + if plugin_json_path.is_file() { + if let Ok(content) = fs::read_to_string(&plugin_json_path) { + if let Ok(val) = serde_json::from_str::(&content) { + if let Some(dn) = val.get("display_name").and_then(|v| v.as_str()) { + display_name = dn.to_string(); + } else if let Some(n) = val.get("name").and_then(|v| v.as_str()) { + if n.len() != 40 || !n.chars().all(|c| c.is_ascii_hexdigit()) { + display_name = n.to_string(); + } + } + } + } + } + // Collect dist confs let mut dist_confs = Vec::new(); if let Ok(entries) = fs::read_dir(&store_dir) { @@ -159,7 +222,7 @@ pub fn install_qualified_module( let meta = PluginMetadata { id: module_id.to_string(), - name: module_id.to_string(), + name: display_name.clone(), version: version.to_string(), description: BTreeMap::new(), sha256, @@ -179,9 +242,10 @@ pub fn install_qualified_module( Ok(PreviewInstallResult { success: true, module_id: module_id.to_string(), + display_name: display_name.clone(), enabled: true, sql_applied: apply_sql, - message: format!("Plugin '{}' v{} installed and enabled successfully in test realm.", module_id, version), + message: format!("Plugin '{}' v{} installed and enabled successfully in test realm.", display_name, version), sql_plan: None, }) } diff --git a/src/lib/api.ts b/src/lib/api.ts index 6d76fab..c760980 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -309,13 +309,17 @@ export interface BuildErrorDiagnostic { file: string; line: number; error_code: string; + symbol?: string | null; message: string; + actionable_resolution?: string | null; } export interface BuildResult { success: boolean; module_id: string; module_name: string; + display_name?: string; + source_commit?: string | null; version: string; package_path?: string | null; dll_path?: string | null; @@ -335,11 +339,13 @@ export interface InstalledPreviewPlugin { sha256: string; store_path: string; conf_files: string[]; + source_commit?: string; } export interface PreviewInstallResult { success: boolean; module_id: string; + display_name?: string; enabled: boolean; sql_applied: boolean; message: string; diff --git a/src/screens/ModulesPage.tsx b/src/screens/ModulesPage.tsx index 4b23744..3de2c04 100644 --- a/src/screens/ModulesPage.tsx +++ b/src/screens/ModulesPage.tsx @@ -1,56 +1,371 @@ -import { useCallback, useEffect, useState } from "react"; +import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from "react"; +import { listen } from "@tauri-apps/api/event"; import { AlertTriangle, + Bot, CheckCircle2, Database, Download, + Flame, FolderPlus, + Gavel, Hammer, + Info, + Layers, Loader2, Plug, + Puzzle, RefreshCw, + Scaling, + Search, + Settings2, Shield, + Snowflake, + Sparkles, + Swords, Terminal, Trash2, + Users, X, XCircle, + type LucideProps, } from "lucide-react"; import { api, asUiError, type BuildResult, type CompatibilityReport, + type CustomRacesClientStatus, + type CustomRacesProgress, type InstalledPreviewPlugin, + type ModuleSetting, + type ModuleView, 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 { useI18n } from "@/i18n"; +import { useHuman, useI18n, useSchemaText, type Key } from "@/i18n"; +import { auctionWeightKey, canonicalModuleValue, moduleEnableKey, moduleField } from "@/lib/moduleSettings"; +import { AuctionTypes } from "@/screens/AuctionTypes"; import type { UnsavedChangesGuard } from "@/lib/unsavedGuard"; -type TabId = "installed" | "github" | "builds" | "toolchain"; +/** The GitHub mark */ +function GithubMark(props: { className?: string }) { + return ( + + + + ); +} + +/** Icon and colors of a module's square tile */ +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" }; + +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" }, +}; + +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 ( +
+ +
+ ); +} + +export type TabId = "official" | "catalog" | "github" | "installed" | "builds" | "toolchain"; + +interface VerifiedCatalogModule { + id: string; + name: string; + repo: string; + category: "utility" | "economy" | "social" | "profession" | "scaling" | "housing" | "scripting"; + description: { ru: string; en: string }; + qualification: "INSTALL_VERIFIED" | "LINK_VERIFIED" | "BUILT" | "POTENTIAL_CONFLICT" | "CONFLICT_DETECTED" | "CORE_INTEGRATED_REQUIRED" | "DEPENDENCY_MISSING"; + tier: string; + verificationLevel: string; + notes: { ru: string; en: string }; + sqlRequired: boolean; + canInstall: boolean; +} + +const VERIFIED_CATALOG: VerifiedCatalogModule[] = [ + { + id: "mod-npc-buffer", + name: "NPC Buffer", + repo: "https://github.com/azerothcore/mod-npc-buffer", + category: "utility", + description: { + ru: "NPC-баффер для наложения положительных эффектов, снятия усталости и лечения персонажей.", + en: "NPC buff master offering spells, resurrection sickness removal, and player restoration.", + }, + qualification: "INSTALL_VERIFIED", + tier: "Tier 1: Dynamic DLL", + verificationLevel: "L0-L4 PASS, L6 PASS (L5 GAMEPLAY_NOT_TESTED)", + notes: { + ru: "Сборка, связывание и динамическая загрузка в реалм подтверждены. Требуется импорт SQL.", + en: "Compilation, linking and dynamic realm load verified. Requires SQL migration.", + }, + sqlRequired: true, + canInstall: true, + }, + { + id: "mod-ah-bot", + name: "Auction House Bot", + repo: "https://github.com/azerothcore/mod-ah-bot", + category: "economy", + description: { + ru: "Автоматическое наполнение аукциона сбалансированными лотами предметов от имени виртуальных игроков.", + en: "Populates auction houses with realistic listings from virtual buyers and sellers.", + }, + qualification: "LINK_VERIFIED", + tier: "Tier 1: Dynamic DLL", + verificationLevel: "L0-L3 PASS (SDK v0.3.2+)", + notes: { + ru: "Успешно связывается с SDK v0.3.2 (добавлены экспорты Player::~Player, OnAuctionSuccessful, GetAuctionHouseEntryFromHouse).", + en: "Successfully links against SDK v0.3.2 after resolving Player destructor and auction manager exports.", + }, + sqlRequired: false, + canInstall: true, + }, + { + id: "mod-congrats-on-level", + name: "Congrats On Level", + repo: "https://github.com/azerothcore/mod-congrats-on-level", + category: "social", + description: { + ru: "Анимации, салюты и оповещения в чат при повышении уровня игрока.", + en: "Server-wide or local celebrations, fireworks and announcements on level up.", + }, + qualification: "INSTALL_VERIFIED", + tier: "Tier 1: Dynamic DLL", + verificationLevel: "L0-L4 PASS, L6 PASS (L5 GAMEPLAY_NOT_TESTED)", + notes: { + ru: "Полный цикл жизненного цикла динамического плагина проверен на SDK v0.3.", + en: "Full lifecycle verified against CoA Plugin SDK v0.3.", + }, + sqlRequired: false, + canInstall: true, + }, + { + id: "mod-npc-enchanter", + name: "NPC Enchanter", + repo: "https://github.com/azerothcore/mod-npc-enchanter", + category: "profession", + description: { + ru: "NPC-зачарователь для наложения чар на оружие и броню за золото и реагенты.", + en: "NPC offering equipment enchanting services for gold and custom tokens.", + }, + qualification: "INSTALL_VERIFIED", + tier: "Tier 1: Dynamic DLL", + verificationLevel: "L0-L4 PASS, L6 PASS (L5 GAMEPLAY_NOT_TESTED)", + notes: { + ru: "Подтверждена сборка и установка. Для спавна NPC используется команда .npc add 601015.", + en: "Build and install verified. Spawn using command .npc add 601015.", + }, + sqlRequired: true, + canInstall: true, + }, + { + id: "mod-reward-played-time", + name: "Reward Played Time", + repo: "https://github.com/azerothcore/mod-reward-played-time", + category: "social", + description: { + ru: "Периодическая выдача наград и валюты игрокам за время, проведённое на сервере.", + en: "Periodic rewards and tokens granted to players based on active playtime.", + }, + qualification: "INSTALL_VERIFIED", + tier: "Tier 1: Dynamic DLL", + verificationLevel: "L0-L4 PASS, L6 PASS (L5 GAMEPLAY_NOT_TESTED)", + notes: { + ru: "Сборка и установка подтверждены. Содержит миграции базы данных characters.", + en: "Build and install verified. Contains characters DB migrations.", + }, + sqlRequired: true, + canInstall: true, + }, + { + id: "mod-transmog", + name: "Transmogrification", + repo: "https://github.com/azerothcore/mod-transmog", + category: "utility", + description: { + ru: "Трансмогрификация экипировки персонажей в стиле современных дополнений WoW.", + en: "Modern retail-style equipment transmogrification system.", + }, + qualification: "BUILT", + tier: "Tier 1: Dynamic DLL", + verificationLevel: "L0-L2 PASS", + notes: { + ru: "Сборка C++20 с адаптером успешна. Требуется проверка на живом клиенте.", + en: "C++20 compilation with adapter succeeds. Client testing required.", + }, + sqlRequired: true, + canInstall: true, + }, + { + id: "mod-solocraft", + name: "Solocraft", + repo: "https://github.com/azerothcore/mod-solocraft", + category: "scaling", + description: { + ru: "Масштабирование характеристик персонажа при одиночном прохождении группового контента.", + en: "Dynamically boosts player stats in group dungeons and raids for solo play.", + }, + qualification: "POTENTIAL_CONFLICT", + tier: "Tier 2: Config Conflict Protection", + verificationLevel: "L0-L2 PASS (Конфликт со встроенным скалированием)", + notes: { + ru: "Может конфликтовать по балансу со встроенным Content Scaling. Требуется калибровка параметров.", + en: "Potential balance stacking with Content Scaling. Requires parameter calibration.", + }, + sqlRequired: true, + canInstall: true, + }, + { + id: "mod-autobalance", + name: "AutoBalance", + repo: "https://github.com/azerothcore/mod-autobalance", + category: "scaling", + description: { + ru: "Динамическое изменение характеристик монстров в зависимости от состава группы.", + en: "Dynamic mob health and damage scaling based on player group size.", + }, + qualification: "CONFLICT_DETECTED", + tier: "Tier 2: Mutual Exclusion Required", + verificationLevel: "L0 PASS (Прямой конфликт полномочий)", + notes: { + ru: "Прямой конфликт с CoAContentScaling: оба модуля переопределяют SetCreateHealth. Запрещено включать одновременно.", + en: "Direct budget collision with CoAContentScaling. Concurrent execution prohibited.", + }, + sqlRequired: true, + canInstall: false, + }, + { + id: "mod-guildhouse", + name: "Guildhouse", + repo: "https://github.com/azerothcore/mod-guildhouse", + category: "housing", + description: { + ru: "Гильдейские дома с телепортацией, дворецкими и динамическим созданием объектов.", + en: "Guild housing system with portals, butlers, and dynamic object spawning.", + }, + qualification: "CORE_INTEGRATED_REQUIRED", + tier: "Tier 3: Core-Integrated Required", + verificationLevel: "L0 PASS, L1/L2 BLOCKED (Требуется сборка ядра)", + notes: { + ru: "Прямое управление жизненным циклом GameObject/Creature в памяти и БД (SaveToDB, DeleteFromDB, AddObjectToRemoveList). Не может быть загружен как автономная DLL.", + en: "Direct entity lifecycle calls require host core compilation. Cannot be loaded as standalone dynamic DLL.", + }, + sqlRequired: true, + canInstall: false, + }, + { + id: "mod-ale", + name: "Azeroth Lua Engine (ALE)", + repo: "https://github.com/azerothcore/mod-ale", + category: "scripting", + description: { + ru: "Встраиваемая среда выполнения Lua-скриптов для расширения игровой логики сервера.", + en: "Embedded Lua runtime environment for writing server-side game logic scripts.", + }, + qualification: "DEPENDENCY_MISSING", + tier: "Tier 4: Runtime Dependency Missing", + verificationLevel: "L0 PASS (Отсутствует runtime LuaJIT)", + notes: { + ru: "Требует отдельной сборки и связывания с внешней библиотекой LuaJIT в среде /MD.", + en: "Requires external LuaJIT /MD build target and C++20 adapter.", + }, + sqlRequired: false, + canInstall: false, + }, +]; export function ModulesPage({ serverId, onChanged, - onRegisterGuard: _onRegisterGuard, + onRegisterGuard, }: { serverId: string; onChanged?: () => void; onRegisterGuard?: (guard: UnsavedChangesGuard | null) => void; }) { - const { locale } = useI18n(); + const { t, locale } = useI18n(); + const human = useHuman(); // Navigation tab - const [activeTab, setActiveTab] = useState("github"); + const [activeTab, setActiveTab] = useState("official"); + + // Official modules state + const [modules, setModules] = useState(null); + const [openSettings, setOpenSettings] = 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 [guard, setGuard] = useState(null); // Installed dynamic plugins const [installedPlugins, setInstalledPlugins] = useState([]); const [error, setError] = useState(null); const [notification, setNotification] = useState(null); + // Catalog search & filter + const [catalogQuery, setCatalogQuery] = useState(""); + const [catalogFilter, setCatalogFilter] = useState("all"); + const [selectedCatalogModule, setSelectedCatalogModule] = useState(null); + // GitHub Intake & Analysis state const [githubUrl, setGithubUrl] = useState(""); const [analyzing, setAnalyzing] = useState(false); @@ -72,6 +387,11 @@ export function ModulesPage({ // Action busy indicators const [actionInProgress, setActionInProgress] = useState(null); + useEffect(() => { + onRegisterGuard?.(guard); + return () => onRegisterGuard?.(null); + }, [guard, onRegisterGuard]); + const loadToolchain = useCallback(async () => { try { const tc = await api.previewToolchainStatus(); @@ -90,19 +410,106 @@ export function ModulesPage({ } }, [serverId]); + const loadRacesStatus = useCallback(async () => { + try { + const st = await api.customRacesStatus(serverId); + setRacesPatchStatus(st); + } catch { + // ignore + } + }, [serverId]); + const load = useCallback(async () => { try { + const mods = await api.modulesList(serverId); + setModules(mods.filter((m) => !m.hidden)); + await loadRacesStatus(); await loadInstalledPlugins(); await loadToolchain(); } catch (e) { setError(asUiError(e)); } - }, [loadInstalledPlugins, loadToolchain]); + }, [serverId, loadRacesStatus, loadInstalledPlugins, loadToolchain]); useEffect(() => { void load(); }, [load]); + useEffect(() => { + let unlisten: (() => void) | undefined; + void listen("custom-races-progress", (e) => { + setRacesProgress(e.payload); + }).then((un) => { + unlisten = un; + }); + return () => { + unlisten?.(); + }; + }, []); + + async function installClientPatch() { + setRacesInstalling(true); + setError(null); + try { + await api.customRacesInstall(serverId); + await loadRacesStatus(); + onChanged?.(); + } catch (e) { + setError(asUiError(e)); + } finally { + setRacesInstalling(false); + setRacesProgress(null); + } + } + + async function uninstallClientPatch() { + setRacesInstalling(true); + setError(null); + try { + await api.customRacesUninstall(serverId); + await loadRacesStatus(); + onChanged?.(); + } catch (e) { + setError(asUiError(e)); + } finally { + setRacesInstalling(false); + } + } + + async function toggleOfficialModule(m: ModuleView) { + if (toggleLock.current || racesInstalling) return; + toggleLock.current = true; + setToggling(m.id); + setError(null); + try { + // Mutual exclusion check between companions and squid + if (m.id === "companions" && !m.enabled) { + const squidMod = modules?.find((x) => x.id === "squid"); + if (squidMod?.enabled) { + await api.moduleSetEnabled(serverId, "squid", false); + } + } else if (m.id === "squid" && !m.enabled) { + const compMod = modules?.find((x) => x.id === "companions"); + if (compMod?.enabled) { + await api.moduleSetEnabled(serverId, "companions", false); + } + } + await api.moduleSetEnabled(serverId, m.id, !m.enabled); + setChanged(true); + await load(); + if (m.id === "custom-races") { + await loadRacesStatus(); + } + onChanged?.(); + } catch (e) { + setError(asUiError(e)); + await load(); + } finally { + toggleLock.current = false; + setToggling(null); + } + } + async function registerTestRealm() { setActionInProgress("register-realm"); setError(null); @@ -127,9 +534,7 @@ export function ModulesPage({ try { const p = await api.previewExportDiagnostics(serverId); setNotification( - locale === "ru" - ? `Диагностический отчёт сохранён: ${p}` - : `Diagnostic report saved: ${p}` + locale === "ru" ? `Диагностический отчёт сохранён: ${p}` : `Diagnostic report saved: ${p}` ); } catch (e) { setError(asUiError(e)); @@ -138,14 +543,17 @@ export function ModulesPage({ } } - async function runAnalysis() { - if (!githubUrl.trim()) return; + async function runAnalysis(urlToAnalyze?: string) { + const targetUrl = (urlToAnalyze || githubUrl).trim(); + if (!targetUrl) return; + setGithubUrl(targetUrl); setAnalyzing(true); setAnalysisError(null); setReport(null); setBuildResult(null); + setActiveTab("github"); try { - const rep = await api.analyzeGithubModule(githubUrl.trim(), serverId); + const rep = await api.analyzeGithubModule(targetUrl, serverId); setReport(rep); } catch (e: unknown) { setAnalysisError(e instanceof Error ? e.message : String(e)); @@ -172,8 +580,8 @@ export function ModulesPage({ if (res.success) { setNotification( locale === "ru" - ? `Сборка успешно завершена! DLL квалифицирована: ${res.dll_sha256?.substring(0, 16)}...` - : `Build succeeded! Qualified DLL: ${res.dll_sha256?.substring(0, 16)}...` + ? `Сборка успешно завершена! DLL '${res.display_name || res.module_id}' квалифицирована: ${res.dll_sha256?.substring(0, 16)}...` + : `Build succeeded! DLL '${res.display_name || res.module_id}' qualified: ${res.dll_sha256?.substring(0, 16)}...` ); } else { setAnalysisError( @@ -261,6 +669,34 @@ export function ModulesPage({ } } + 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); + } + + const selectedOfficial = modules?.find((m) => m.id === openSettings) ?? null; + const selectedOfficialIndex = modules?.findIndex((m) => m.id === openSettings) ?? -1; + + const filteredCatalog = VERIFIED_CATALOG.filter((item) => { + if (catalogFilter === "verified" && !["INSTALL_VERIFIED", "LINK_VERIFIED"].includes(item.qualification)) return false; + if (catalogFilter === "conflict" && !["POTENTIAL_CONFLICT", "CONFLICT_DETECTED"].includes(item.qualification)) return false; + if (catalogFilter === "intree" && item.qualification !== "CORE_INTEGRATED_REQUIRED") return false; + if (!catalogQuery.trim()) return true; + const q = catalogQuery.toLowerCase(); + return ( + item.name.toLowerCase().includes(q) || + item.id.toLowerCase().includes(q) || + item.description.ru.toLowerCase().includes(q) || + item.description.en.toLowerCase().includes(q) + ); + }); + return (
{/* Header & Sub-navigation */} @@ -275,8 +711,8 @@ export function ModulesPage({

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

@@ -319,7 +755,7 @@ export function ModulesPage({ {/* Error Banner */} {error && (
- ⚠ {error.technical || error.human.message} + ⚠ {error.technical || (error.human ? human(error.human).message : "Unknown error")} @@ -373,11 +809,37 @@ export function ModulesPage({ )} {/* Tabs Header */} -
+
+ + + +
- {/* TAB 1: GITHUB INSTALLATION & COMPATIBILITY WORKFLOW */} + {/* TAB 0: OFFICIAL MODULES (FROM STABLE CSM DESIGN LANGUAGE) */} + {activeTab === "official" && ( +
+
+
+

+ {locale === "ru" + ? "Встроенные модули сервера. Включайте, выключайте и настраивайте параметры каждого модуля." + : "Built-in server modules. Enable, disable and configure runtime module parameters."} +

+
+ {changed && ( + + {t("mod.restart")} + + )} +
+ +
+ {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.id === "companions" && ( +

+ {locale === "ru" + ? "Взаимоисключение: не работает одновременно со SQUID's Playerbots." + : "Mutual exclusion: cannot run concurrently with SQUID's Playerbots."} +

+ )} + {m.id === "squid" && ( +

+ {locale === "ru" + ? "Взаимоисключение: отключает CoA Companions при активации." + : "Mutual exclusion: disables CoA Companions upon activation."} +

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

+ + {t("mod.switching")} +

+ )} + + {/* Custom Races Client Patch status & actions */} + {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 && 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" && ( + + )} +
+ + + {/* Inline settings drawer */} + {selectedOfficial?.has_settings && + !selectedOfficial.page && + selectedOfficialIndex >= 0 && + Math.floor(selectedOfficialIndex / 2) === Math.floor(i / 2) && + (i % 2 === 1 || i === modules.length - 1) && ( + +
+

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

+ +
+ setChanged(true)} + onRegisterGuard={setGuard} + /> +
+ )} + + ))} +
+
+ )} + + {/* TAB 1: VERIFIED MODULES CATALOG */} + {activeTab === "catalog" && ( +
+
+
+

+ {locale === "ru" ? "Каталог проверенных модулей" : "Verified Modules Catalog"} +

+

+ {locale === "ru" + ? "Модули AzerothCore, протестированные против CoA Plugin SDK с честными уровнями квалификации." + : "Curated AzerothCore modules evaluated against CoA Plugin SDK with honest qualification levels."} +

+
+ + {/* Category filter pills */} +
+ + + + +
+
+ + {/* Search box */} +
+ + setCatalogQuery(e.target.value)} + placeholder={ + locale === "ru" + ? "Поиск по названию или описанию (например, buffer, enchanter, guildhouse)..." + : "Search verified catalog..." + } + className="w-full rounded-md border border-line bg-bg pl-9 pr-4 py-2 text-xs text-ink placeholder:text-muted/60 focus:border-gold focus:outline-none" + /> +
+ + {/* Catalog Grid */} +
+ {filteredCatalog.map((item) => ( + +
+
+
+

+ {item.name} + ({item.id}) +

+

{locale === "ru" ? item.description.ru : item.description.en}

+
+
+ + {/* Qualification Badges */} +
+ {item.qualification === "INSTALL_VERIFIED" && ( + + ✓ {item.qualification} + + )} + {item.qualification === "LINK_VERIFIED" && ( + + ✓ {item.qualification} + + )} + {item.qualification === "BUILT" && ( + + ● {item.qualification} + + )} + {item.qualification === "POTENTIAL_CONFLICT" && ( + + ⚠ {item.qualification} + + )} + {item.qualification === "CONFLICT_DETECTED" && ( + + ✕ {item.qualification} + + )} + {item.qualification === "CORE_INTEGRATED_REQUIRED" && ( + + ⚙ {item.qualification} + + )} + {item.qualification === "DEPENDENCY_MISSING" && ( + + ⚙ {item.qualification} + + )} + + {item.tier} + {item.sqlRequired && ( + SQL + )} +
+ +

+ {locale === "ru" ? item.notes.ru : item.notes.en} +

+
+ +
+ + +
+ + + {item.canInstall ? ( + + ) : ( + + )} +
+
+
+ ))} +
+ + {/* Details Modal */} + {selectedCatalogModule && ( +
+ +
+

+ {selectedCatalogModule.name} + ({selectedCatalogModule.id}) +

+ +
+ +
+
+ {locale === "ru" ? "Описание:" : "Description:"} +

+ {locale === "ru" ? selectedCatalogModule.description.ru : selectedCatalogModule.description.en} +

+
+ +
+
+ {locale === "ru" ? "Уровень верификации:" : "Verification Level:"} + {selectedCatalogModule.verificationLevel} +
+
+ {locale === "ru" ? "Уровень архитектуры:" : "Architecture Tier:"} + {selectedCatalogModule.tier} +
+
+ +
+ + {locale === "ru" ? "Инженерные примечания и статус:" : "Engineering Notes & Status:"} + +

+ {locale === "ru" ? selectedCatalogModule.notes.ru : selectedCatalogModule.notes.en} +

+
+
+ +
+ + {selectedCatalogModule.canInstall && ( + + )} +
+
+
+ )} +
+ )} + + {/* TAB 2: GITHUB INSTALLATION & COMPATIBILITY WORKFLOW */} {activeTab === "github" && (
@@ -437,8 +1419,8 @@ export function ModulesPage({

{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)."} + ? "Укажите ссылку на GitHub-репозиторий совместимого модуля AzerothCore (например, mod-npc-buffer, mod-ah-bot, mod-congrats-on-level, mod-npc-enchanter)." + : "Paste GitHub repository URL for an AzerothCore module (e.g., mod-npc-buffer, mod-ah-bot, mod-congrats-on-level, mod-npc-enchanter)."}

@@ -449,34 +1431,65 @@ export function ModulesPage({ 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" /> -
- {analysisError && ( -
- {analysisError} -
- )} + {/* Quick module sample chips */} +
+ {locale === "ru" ? "Быстрый выбор:" : "Quick select:"} + + + + +
- {/* Analysis Report Card */} + {analysisError && ( +
+ {locale === "ru" ? "Ошибка анализа:" : "Analysis Error:"} {analysisError} +
+ )} + + {/* Analysis Report View */} {report && ( - -
+ +

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

@@ -494,6 +1507,10 @@ export function ModulesPage({ {/* Build and Install Buttons */}
+ +
+ {report.classification === "CorePatchRequired" && ( +
+ +
+ + {locale === "ru" + ? "Tier 3: Требуется интеграция с ядром (In-Tree Core Build)" + : "Tier 3: Core-Integrated Compatibility Required"} + +

+ {locale === "ru" + ? "Модуль обращается к внутренним структурам управления памятью GameObject/Creature или базам данных (SaveToDB, DeleteFromDB, AddObjectToRemoveList). Сборка в виде автономной DLL отключена во избежание падения сервера." + : "Module calls engine-internal GameObject/Creature memory or database lifecycle methods. Standalone dynamic DLL build is blocked to prevent host crashes."} +

+
+
+ )} + {/* Multi-Dimensional Status */} {report.multi_dimensional_status && (
@@ -537,7 +1574,11 @@ export function ModulesPage({
{report.multi_dimensional_status.build_status} @@ -548,7 +1589,11 @@ export function ModulesPage({
{report.multi_dimensional_status.runtime_status} @@ -634,7 +1679,7 @@ export function ModulesPage({
)} - {/* TAB 2: INSTALLED PLUGINS */} + {/* TAB 3: INSTALLED PLUGINS */} {activeTab === "installed" && (
@@ -655,8 +1700,8 @@ export function ModulesPage({ ? "В этом реалме ещё нет установленных динамических плагинов." : "No dynamic plugins installed in this realm yet."}

- ) : ( @@ -669,7 +1714,12 @@ export function ModulesPage({ {p.name} v{p.version} -

+ {p.source_commit && ( +

+ Commit: {p.source_commit.substring(0, 8)} +

+ )} +

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

@@ -727,7 +1777,7 @@ export function ModulesPage({
)} - {/* TAB 3: BUILDS & MSVC LOGS */} + {/* TAB 4: BUILDS & MSVC LOGS */} {activeTab === "builds" && (
{/* Build Result Card */} @@ -744,7 +1794,7 @@ export function ModulesPage({ )}

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

{buildResult.success @@ -765,10 +1815,17 @@ export function ModulesPage({ {buildResult.errors.length > 0 && (

MSVC Compiler / Linker Errors:
-
    +
      {buildResult.errors.map((err, i) => (
    • - [{err.error_code}] {err.file}:{err.line} - {err.message} +
      + [{err.error_code}] {err.file}:{err.line} - {err.message} +
      + {err.actionable_resolution && ( +
      + ➜ {err.actionable_resolution} +
      + )}
    • ))}
    @@ -795,7 +1852,7 @@ export function ModulesPage({
)} - {/* TAB 4: TOOLCHAIN & ENVIRONMENT */} + {/* TAB 5: TOOLCHAIN & ENVIRONMENT */} {activeTab === "toolchain" && toolchain && (

@@ -856,7 +1913,9 @@ export function ModulesPage({
    {report.sql_files.map((s, idx) => ( -
  • • {s.file_path} ({s.statement_count} statements)
  • +
  • + • {s.file_path} ({s.statement_count} statements) +
  • ))}

@@ -886,3 +1945,366 @@ export function ModulesPage({
); } + +/** Settings sub-component for official modules */ +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 ? human(error.human).message : error.technical} +

+ )} + {dirty && ( +
+ {tn("set.unsaved", Object.keys(edits).length)} +
+ + +
+
+ )} +
+ ); +}