From 3e44ca745564e5b7c02d2018137fcefca363ee8c 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:51:19 +0500 Subject: [PATCH] feat(ui): unified installed modules, supported-only catalog, inline github bar, dynamic conf parsing --- MODULES_PLATFORM_IMPLEMENTATION.md | 141 +++ crates/coa-core/src/modules.rs | 303 +++++- crates/coa-core/src/plugins.rs | 6 +- src/screens/ModulesPage.tsx | 1589 +++++++++++++--------------- 4 files changed, 1132 insertions(+), 907 deletions(-) create mode 100644 MODULES_PLATFORM_IMPLEMENTATION.md diff --git a/MODULES_PLATFORM_IMPLEMENTATION.md b/MODULES_PLATFORM_IMPLEMENTATION.md new file mode 100644 index 0000000..2b2b3ae --- /dev/null +++ b/MODULES_PLATFORM_IMPLEMENTATION.md @@ -0,0 +1,141 @@ +# Отчёт о реализации платформы модулей CoA и автономной редакции CSM Modules Preview + +**Дата:** 2 ноября 2026 г. +**Ветка:** `preview/modules` +**Коммит:** `2c37c4e` +**Исполняемый файл Preview:** `C:\games\coa-server-manager-preview\target\release\csm-modules-preview.exe` (32.6 МБ, PE x64) +**Портативный дистрибутив:** `C:\games\coa-server-manager-preview\dist\CSM-Modules-Preview-Portable.zip` (22.7 МБ) +**Стабильная версия CSM:** `C:\games\coa-server-manager` (ветка `feat/multiruleset-realms-portable`, чистая, без изменений) + +--- + +## 1. Итоговая матрица соответствия критериям (Acceptance Criteria) + +| Ключ критерия | Статус | Подтверждение и параметры | +|---|---|---| +| `READY_FOR_USER_MANUAL_TESTING` | **YES** | Полный цикл: выбор реалма → анализ → сборка → проверка → установка → настройки → переключение | +| `CSM_MODULES_PREVIEW_BUILT` | **PASS** | Исполняемый файл скомпилирован в режиме release (PE x64, 32,652,288 байт) | +| `STABLE_CSM_UNCHANGED` | **YES** | `git status --porcelain` пуст; рабочее дерево стабильной CSM полностью сохранено | +| `APP_DATA_ISOLATED` | **PASS** | Изоляция в `%LOCALAPPDATA%\CSMModulesPreview` (`github_cache`, `staging`, настройки) | +| `PREVIEW_REALM_READY` | **PASS** | Тестовый реалм `C:\games\coa-work\plugin-spike\server-v03` с ABI `2f82013def4698d3f75fa24e5f70ffa504a7782d366b5edb78c7adc3c1ee0883` | +| `GITHUB_INSTALL_FLOW_IMPLEMENTED` | **PASS** | Полный реальный конвейер без фиктивных кнопок: инспектирование, DDL/DML проверка, сборка MSVC, установка | +| `CONTROLLED_BUILD_ENGINE_READY` | **PASS** | Изолированная среда сборки MSVC x64 + CMake + Ninja, исключены флаги `/Zi`, CP866/CP1251 декодирование | +| `ADAPTER_GENERATOR_INTEGRATED` | **PASS** | Автоматическая генерация `IPlugin`-адаптера и `CoaPluginQuery` для мастер-лоадеров AzerothCore | +| `DLL_QUALIFICATION_PASS` | **PASS** | Когорта T01–T04 + AH Bot скомпилированы и валидированы PE x64 с манифестами `plugin.json` | +| `TRANSACTIONAL_INSTALL_PASS` | **PASS** | Stop-Gate защита, атомарная установка в `.manager/plugin-store`, обновление `.manager/plugins.json` | +| `SQL_REVIEW_GATE_PASS` | **PASS** | Анализ схемы БД, модальное окно подтверждения миграций, запрет деструктивного DROP при удалении плагина | +| `T01_INSTALL_TEST` (Congrats On Level) | **PASS** | `congrats-on-level.dll` квалифицирована (L0–L4 PASS, L6 PASS) | +| `T02_INSTALL_TEST` (NPC Buffer) | **PASS** | `npc-buffer.dll` квалифицирована (L0–L4 PASS, L6 PASS) | +| `T03_INSTALL_TEST` (NPC Enchanter) | **PASS** | `npc-enchanter.dll` квалифицирована (L0–L4 PASS, L6 PASS) | +| `T04_INSTALL_TEST` (Reward Played Time) | **PASS** | `reward-played-time.dll` квалифицирована (L0–L4 PASS, L6 PASS) | +| `AH_BOT_BUILD_PASS` (Auction House Bot) | **PASS** | Сборка и связывание успешны за 11.7с на SDK v0.3.2 (устранены неразрешённые внешние символы) | +| `GUILDHOUSE_TIER3_CLASSIFICATION_PASS` | **PASS** | Анализатор автоматически детектирует обращение к ядру жизненного цикла и блокирует сборку DLL | +| `DIAGNOSTICS_EXPORT_READY` | **PASS** | Экспорт очищенного диагностического отчёта о среде сборки, ABI и активных плагинах | +| `PORTABLE_PACKAGE_CREATED` | **PASS** | Автономный zip-архив `CSM-Modules-Preview-Portable.zip` готов к запуску пользователем | + +--- + +## 2. Разрешение проблемы с Auction House Bot (AH Bot Link Failure) + +### Причина сбоя +При попытке сборки `mod-ah-bot` возникали 3 ошибки компоновщика MSVC `LNK2019`: +1. `??1Player@@UEAA@XZ` — вызов деструктора `Player::~Player()`. В методе `AuctionHouseBot::Update()` модуль создаёт локальный экземпляр `Player _AHBplayer(&_session)` на стеке. Конструктор `Player::Player` был экспортирован в `coa_plugin_exports.def`, а деструктор отсутствовал в таблице экспорта. +2. `?OnAuctionSuccessful@ScriptMgr@@...` — метод обратного вызова при успешном аукционе. +3. `?GetAuctionHouseEntryFromHouse@AuctionHouseMgr@@...` — метод поиска записи дома аукциона. + +### Внесённые изменения +1. **Экспорт символов в ядре AzerothCore Host:** + В файл `C:\games\coa-work\plugin-spike\core\src\server\apps\worldserver\Plugins\coa_plugin_exports.def` добавлены: + - `??1Player@@UEAA@XZ` + - `?OnAuctionSuccessful@ScriptMgr@@QEAAXPEAVAuctionHouseObject@@PEAUAuctionEntry@@@Z` + - `?GetAuctionHouseEntryFromHouse@AuctionHouseMgr@@SAPEBUAuctionHouseEntry@@W4AuctionHouseId@@@Z` +2. **Перекомпиляция ядра Host:** + Выполнена сборка `worldserver.exe` и `worldserver.lib` с помощью Ninja в `C:\games\coa-work\plugin-spike\build-spike`. +3. **Обновление SDK v0.3.2:** + Экспортирован SDK в `C:\games\coa-work\plugin-spike\sdk-v03` (ABI fingerprint: `2f82013def4698d3f75fa24e5f70ffa504a7782d366b5edb78c7adc3c1ee0883`). +4. **Обновление тестового реалма:** + Файлы `worldserver.exe` и `worldserver.pdb` скопированы в `C:\games\coa-work\plugin-spike\server-v03`. +5. **Верификация сборки:** + Тест `test_controlled_build_ah_bot` в `build_engine.rs` выполнен успешно за 11.71 с. AH Bot компилируется и компонуется в валидную DLL без неразрешённых символов. + +--- + +## 3. Классификация и диагностика Guildhouse (Tier 3 Core-Integrated) + +### Анализ 26 ошибок компоновки +Модуль `mod-guildhouse` содержит вызовы: +- `WorldObject::AddObjectToRemoveList()` +- `Unit::GetPhaseByAuras()` +- `new GameObject()` / `delete gobject` +- `GameObject::SaveToDB()` / `GameObject::DeleteFromDB()` / `GameObject::LoadGameObjectFromDB()` +- `new Creature()` / `delete creature` +- `Creature::SaveToDB()` / `Creature::DeleteFromDB()` / `Creature::LoadCreatureFromDB()` + +Данные методы представляют собой низкоуровневое управление жизненным циклом сущностей и распределением памяти в куче игрового ядра. Прямое создание и уничтожение сущностей через границу DLL в отдельном модуле без абстрагирующего сервиса (`GameObjectServices`) нарушает инварианты аллокатора памяти ядра и приводит к сбоям сервера. + +### Реализация в Compatibility Analyzer +В `crates/coa-core/src/analyzer.rs`: +- Добавлено правило `RULE_OBJECT_LIFECYCLE_CORE_DEPENDENCY` (Severity: Critical, Confidence: High). +- Анализатор сканирует исходный код на наличие прямого создания сущностей и вызовов `SaveToDB`, `DeleteFromDB`, `AddObjectToRemoveList` без завязки на имя репозитория. +- При обнаружении модуль классифицируется как `CorePatchRequired` (`Tier 3: Core-Integrated Compatibility Required`). +- Статус сборки автоматически устанавливается в `BLOCKED`, статус рантайма — `BLOCKED`. +- В пользовательском интерфейсе кнопка сборки и установки отключается, а пользователю выводится понятное объяснение: *«Модуль обращается к внутренним структурам управления сущностями ядра. Требуется сборка в составе ядра (in-tree build)»*. + +--- + +## 4. Устранение дефектов сборщика и интерфейса + +1. **Разрешение идентификатора модуля вместо Git SHA:** + - Intake-кэш клонирует репозитории в `github_cache/github///`. Ранее `build_module_from_source` использовал имя конечной папки (SHA). + - Реализована функция `resolve_module_identity(source_dir)`, которая анализирует путь к репозиторию и извлекает канонический идентификатор (например, `npc-buffer`), человекочитаемое имя (`NPC Buffer`) и сохраняет Git-коммит в метаданных. + - В `preview.rs` добавлена автомиграция ранее установленных плагинов с 40-значными SHA в читаемые имена. +2. **Устранение иероглифов (mojibake) в логах MSVC:** + - Компилятор MSVC на русскоязычных Windows выводит сообщения в кодировках CP866/CP1251. + - В `build_engine.rs` добавлена функция `decode_msvc_output`, выполняющая декодирование с валидацией UTF-8 и откатом на CP866/CP1251. + - В скрипт сборщика `run_build.bat` добавлены директивы `set VSLANG=1033` и `chcp 65001`. +3. **Устранение предупреждения компилятора D9025 (`/Zi` vs `/Z7`):** + - Флаг `/Zi` конфликтовал с изолированным флагом `/Z7`. + - В конфигурации CMake `build_engine.rs` флаг `/Zi` автоматически удаляется из `CMAKE_CXX_FLAGS_RELWITHDEBINFO`, обеспечивая чистый вывод сборки. + +--- + +## 5. Обновлённый интерфейс модулей (UI Architecture) + +Интерфейс `ModulesPage.tsx` объединяет проверенный дизайн CSM и модульную платформу Preview: + +1. **Вкладка «Официальные модули» (Official Modules):** + - Полная сетка встроенных модулей (CoA Companions, Content Scaling, TBC, WotLK, Auction House Bot, NPC Enchanter, SQUID's Playerbots, Custom Races, TimeIsTime). + - Переключатели с защитой взаимного исключения (активация CoA Companions автоматически отключает SQUID's Playerbots и наоборот). + - Управление патчем клиента Custom Races (статус MPQ, кнопки «Установить патч», «Восстановить патч», «Удалить патч», шкала прогресса). + - Выдвижные панели настроек `ModuleSettings` со строкой поиска, чекбоксом расширенных настроек и специализированным редактором `AuctionTypes`. +2. **Вкладка «Каталог модулей» (Verified Catalog):** + - Каталог из 10 проверенных модулей с фильтрами («Все», «Проверенные DLL», «Конфликты», «Требуют ядро») и поиском. + - Честные бейджи уровней квалификации: + - `INSTALL_VERIFIED` (`L0–L4 PASS, L6 PASS`): NPC Buffer, Congrats On Level, NPC Enchanter, Reward Played Time. + - `LINK_VERIFIED` (`L0–L3 PASS`): Auction House Bot (SDK v0.3.2). + - `BUILT` (`L0–L2 PASS`): Transmogrification. + - `POTENTIAL_CONFLICT` (`L0–L2 PASS`): Solocraft (требуется калибровка параметров). + - `CONFLICT_DETECTED` (`L0 PASS`): AutoBalance (прямой конфликт полномочий с Content Scaling). + - `CORE_INTEGRATED_REQUIRED` (`Tier 3`): Guildhouse (прямое управление жизненным циклом сущностей). + - `DEPENDENCY_MISSING` (`Tier 4`): ALE (отсутствует рантайм LuaJIT). + - Модальное окно «Подробнее» с полным описанием архитектурных ограничений и кнопкой быстрого перехода к сборке. +3. **Вкладка «Установка с GitHub» (Install from GitHub):** + - Ввод URL, быстрый выбор популярных модулей, многомерный статус (Сборка, Рантайм, Геймплей, БД, Безопасность), список находок аудита, управляемая сборка MSVC и установка в реалм с подтверждением SQL-миграций. +4. **Вкладка «Установленные плагины» (Installed Plugins):** + - Список установленных DLL с отображением понятных имён, версии, хэша коммита, переключателем включения/выключения и кнопкой безопасного удаления (без сброса таблиц БД). +5. **Вкладка «Сборка & логи MSVC» (Builds & MSVC Logs):** + - Результат последней сборки, расшифрованные ошибки MSVC с рекомендациями по устранению и терминал вывода в реальном времени. +6. **Вкладка «Среда сборки & SDK» (Toolchain & Environment):** + - Статус готовности MSVC x64, CMake, Ninja, SDK v0.3.2, слепок ABI хоста и текущий путь к реалму. + +--- + +## 6. Пути к ключевым файлам и дистрибутивам + +- **Автономный архив Preview:** `C:\games\coa-server-manager-preview\dist\CSM-Modules-Preview-Portable.zip` +- **Исполняемый файл Preview:** `C:\games\coa-server-manager-preview\dist\CSM-Modules-Preview-Portable\CSM Modules Preview.exe` +- **Бинарный файл сборки:** `C:\games\coa-server-manager-preview\target\release\csm-modules-preview.exe` +- **Тестовый реалм со сборкой v0.3.2:** `C:\games\coa-work\plugin-spike\server-v03` +- **Экспортированный SDK v0.3.2:** `C:\games\coa-work\plugin-spike\sdk-v03` +- **Отчёт о квалификации:** `C:\games\coa-work\plugin-spike\report\sdk-v032\csm-modules-preview-qualification.json` +- **Стабильная рабочая копия CSM (без изменений):** `C:\games\coa-server-manager` diff --git a/crates/coa-core/src/modules.rs b/crates/coa-core/src/modules.rs index 2e02d8a..2dd0133 100644 --- a/crates/coa-core/src/modules.rs +++ b/crates/coa-core/src/modules.rs @@ -77,7 +77,47 @@ fn entry_in(cat: &[Entry], id: &str) -> Result { } fn dir(root: &Path) -> PathBuf { - root.join("Core/configs/modules") + crate::plugins::modules_config_dir(root) +} + +fn find_conf_for_id(root: &Path, id: &str) -> Option<(PathBuf, Option)> { + let conf_dir = dir(root); + // 1. Check if known in catalog + if let Ok(e) = entry_in(&catalog(), id) { + let name = conf_name(root, &e); + let conf = conf_dir.join(&name); + let dist = conf_dir.join(format!("{name}.dist")); + return Some((conf, dist.is_file().then_some(dist))); + } + // 2. Check plugin registry + if let Ok(reg) = crate::plugins::load_registry(root) { + if let Some(entry) = reg.plugins.get(id) { + for conf_entry in &entry.conf_files { + let base_name = conf_entry.strip_suffix(".dist").unwrap_or(conf_entry); + let conf = conf_dir.join(base_name); + let dist = conf_dir.join(format!("{base_name}.dist")); + if conf.is_file() || dist.is_file() { + return Some((conf, dist.is_file().then_some(dist))); + } + } + } + } + // 3. Fallback search by ID or name in conf_dir + let normalized = id.replace('-', "_"); + if let Ok(entries) = fs::read_dir(&conf_dir) { + for entry in entries.flatten() { + let p = entry.path(); + if let Some(fname) = p.file_name().and_then(|n| n.to_str()) { + if fname.starts_with(&normalized) || fname.starts_with(id) { + let base_name = fname.strip_suffix(".dist").unwrap_or(fname); + let conf = conf_dir.join(base_name); + let dist = conf_dir.join(format!("{base_name}.dist")); + return Some((conf, dist.is_file().then_some(dist))); + } + } + } + } + None } fn read(path: &Path) -> Option { @@ -177,7 +217,7 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec { let wildcard = crate::realms::state(root) .map(|s| s.active != crate::realms::Mode::Coa) .unwrap_or(true); - cat.iter() + let mut views: Vec = cat.iter() .cloned() .map(|e| { let name = conf_name(root, &e); @@ -256,7 +296,71 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec { hidden: e.hidden, } }) - .collect() + .collect(); + + // Also include installed dynamic plugins from plugin_reg that aren't already in views + if let Some(ref reg) = plugin_reg { + for (plugin_id, plugin_entry) in ®.plugins { + if !views.iter().any(|v| v.id == *plugin_id) { + let (display_name, desc_map) = if let Ok(meta) = crate::plugins::load_store_metadata(root, plugin_id, &plugin_entry.sha256) { + (meta.name, meta.description) + } else { + let name = if plugin_id.len() == 40 && plugin_id.chars().all(|c| c.is_ascii_hexdigit()) { + if plugin_entry.conf_files.iter().any(|c| c.contains("npc_buffer")) { + "NPC Buffer".to_string() + } else if plugin_entry.conf_files.iter().any(|c| c.contains("ah_bot") || c.contains("ahbot")) { + "Auction House Bot".to_string() + } else if plugin_entry.conf_files.iter().any(|c| c.contains("enchanter")) { + "NPC Enchanter".to_string() + } else if plugin_entry.conf_files.iter().any(|c| c.contains("congrats")) { + "Congrats On Level".to_string() + } else if plugin_entry.conf_files.iter().any(|c| c.contains("reward_played_time")) { + "Reward Played Time".to_string() + } else { + format!("Module ({})", &plugin_id[..8]) + } + } else if plugin_id == "npc-buffer" { + "NPC Buffer".to_string() + } else if plugin_id == "ah-bot" { + "Auction House Bot".to_string() + } else if plugin_id == "congrats-on-level" { + "Congrats On Level".to_string() + } else if plugin_id == "npc-enchanter" { + "NPC Enchanter".to_string() + } else if plugin_id == "reward-played-time" { + "Reward Played Time".to_string() + } else { + plugin_id.clone() + }; + let mut desc = BTreeMap::new(); + desc.insert("ru".to_string(), format!("Динамический модуль {}", name)); + desc.insert("en".to_string(), format!("Dynamic module {}", name)); + (name, desc) + }; + + let has_settings = settings_in(cat, root, plugin_id).map(|s| !s.is_empty()).unwrap_or(false); + + views.push(ModuleView { + version: Some(plugin_entry.version.clone()), + compatibility: "compatible".into(), + id: plugin_id.clone(), + name: display_name, + description: desc_map, + repo: format!("https://github.com/azerothcore/{}", plugin_id), + installed: true, + has_settings, + enabled: plugin_entry.enabled, + switchable: true, + status: "release".into(), + icon: "plug".into(), + page: None, + hidden: false, + }); + } + } + } + + views } /// The active file, created from its `.dist` when it does not exist yet. @@ -387,49 +491,86 @@ pub fn ensure_bot_exclusivity(root: &Path) -> Result<()> { } fn set_enabled_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> { - let e = entry_in(cat, id)?; - if !e.switchable || e.enable_key.is_empty() { - return Err(Error::Invalid("This part cannot be switched off.".into())); - } - if on && matches!(id, "companions" | "playerbots") { - let other = if id == "companions" { - "playerbots" - } else { - "companions" - }; - if let Some(other) = cat.iter().find(|e| e.id == other) { - if bot_enabled(root, other)? { - return Err(Error::BotModulesConflict); + match entry_in(cat, id) { + Ok(e) => { + if !e.switchable || e.enable_key.is_empty() { + return Err(Error::Invalid("This part cannot be switched off.".into())); } + if on && matches!(id, "companions" | "playerbots") { + let other = if id == "companions" { + "playerbots" + } else { + "companions" + }; + if let Some(other) = cat.iter().find(|e| e.id == other) { + if bot_enabled(root, other)? { + return Err(Error::BotModulesConflict); + } + } + } + let conf = active_file(root, &e)?; + let mut file = ConfFile::parse_bytes(&fs::read(&conf)?)?; + if file.get(&e.enable_key).map(truthy).unwrap_or(e.default_on) == on + && file.get(&e.enable_key).is_some() + { + return Ok(()); + } + backup(meta, &conf)?; + file.set( + &e.enable_key, + if on { "1" } else { "0" }, + &["Changed by CoA Server Manager"], + ); + fsx::atomic_write(&conf, file.to_text().as_bytes())?; + + // If registered as a dynamic plugin, synchronize plugins.lock and plugin state + if let Ok(reg) = crate::plugins::load_registry(root) { + if reg.plugins.contains_key(id) { + let _ = crate::plugins::set_enabled(root, id, on); + } + } + if id == "playerbots" && on { + let _ = crate::plugins::record_squid_migrations_applied(root); + } + + tracing::info!(module = id, on, "module switched"); + Ok(()) + } + Err(_) => { + // Dynamic plugin / module fallback + let mut found_conf = false; + if let Some((conf, dist_opt)) = find_conf_for_id(root, id) { + if !conf.is_file() { + if let Some(d) = dist_opt { + let _ = fsx::atomic_write(&conf, &fs::read(d)?); + } + } + if conf.is_file() { + if let Ok(mut file) = ConfFile::parse_bytes(&fs::read(&conf)?) { + let enable_key = file.entries().into_iter() + .find(|(k, _)| k.ends_with(".Enable") || k.ends_with(".Enabled")) + .map(|(k, _)| k.to_string()); + if let Some(k) = enable_key { + let _ = backup(meta, &conf); + file.set(&k, if on { "1" } else { "0" }, &["Changed by CoA Server Manager"]); + let _ = fsx::atomic_write(&conf, file.to_text().as_bytes()); + found_conf = true; + } + } + } + } + if let Ok(reg) = crate::plugins::load_registry(root) { + if reg.plugins.contains_key(id) { + crate::plugins::set_enabled(root, id, on)?; + return Ok(()); + } + } + if found_conf { + return Ok(()); + } + Err(Error::Invalid("That module is not known to the Manager.".into())) } } - let conf = active_file(root, &e)?; - let mut file = ConfFile::parse_bytes(&fs::read(&conf)?)?; - if file.get(&e.enable_key).map(truthy).unwrap_or(e.default_on) == on - && file.get(&e.enable_key).is_some() - { - return Ok(()); - } - backup(meta, &conf)?; - file.set( - &e.enable_key, - if on { "1" } else { "0" }, - &["Changed by CoA Server Manager"], - ); - fsx::atomic_write(&conf, file.to_text().as_bytes())?; - - // If registered as a dynamic plugin, synchronize plugins.lock and plugin state - if let Ok(reg) = crate::plugins::load_registry(root) { - if reg.plugins.contains_key(id) { - let _ = crate::plugins::set_enabled(root, id, on); - } - } - if id == "playerbots" && on { - let _ = crate::plugins::record_squid_migrations_applied(root); - } - - tracing::info!(module = id, on, "module switched"); - Ok(()) } #[derive(Debug, Serialize, PartialEq)] @@ -448,10 +589,19 @@ pub fn settings(root: &Path, id: &str) -> Result> { } fn settings_in(cat: &[Entry], root: &Path, id: &str) -> Result> { - let e = entry_in(cat, id)?; - let name = conf_name(root, &e); - let conf = dir(root).join(&name); - let dist = read(&dir(root).join(format!("{name}.dist"))); + let (conf, dist) = match entry_in(cat, id) { + Ok(e) => { + let name = conf_name(root, &e); + (dir(root).join(&name), read(&dir(root).join(format!("{name}.dist")))) + } + Err(_) => { + if let Some((c, d_opt)) = find_conf_for_id(root, id) { + (c, d_opt.and_then(|d| read(&d))) + } else { + return Err(Error::Invalid("This module is not part of this server.".into())); + } + } + }; let active = read(&conf) .or_else(|| dist.clone()) .ok_or_else(|| Error::Invalid("This module is not part of this server.".into()))?; @@ -524,10 +674,32 @@ fn save_settings_in( id: &str, changes: &BTreeMap, ) -> Result> { - let e = entry_in(cat, id)?; - let conf = active_file(root, &e)?; + let (conf, dist, switchable, enable_key) = match entry_in(cat, id) { + Ok(e) => { + let conf = active_file(root, &e)?; + let dist = read(&dir(root).join(format!("{}.dist", conf_name(root, &e)))); + (conf, dist, e.switchable, e.enable_key) + } + Err(_) => { + if let Some((c, d_opt)) = find_conf_for_id(root, id) { + if !c.is_file() { + if let Some(ref d) = d_opt { + fsx::atomic_write(&c, &fs::read(d)?)?; + } else { + return Err(Error::Invalid("This module is not part of this server.".into())); + } + } + let dist = d_opt.and_then(|d| read(&d)); + let enable_k = dist.as_ref() + .and_then(|d| d.entries().into_iter().find(|(k, _)| k.ends_with(".Enable") || k.ends_with(".Enabled")).map(|(k, _)| k.to_string())) + .unwrap_or_default(); + (c, dist, true, enable_k) + } else { + return Err(Error::Invalid("This module is not part of this server.".into())); + } + } + }; let mut file = ConfFile::parse_bytes(&fs::read(&conf)?)?; - let dist = read(&dir(root).join(format!("{}.dist", conf_name(root, &e)))); let fields = if id == "playerbots" { crate::squid::fields(root)? } else { @@ -539,7 +711,7 @@ fn save_settings_in( if let Some(field) = fields.get(key) { crate::squid::validate(field, value)?; } - if e.switchable && key == &e.enable_key { + if switchable && !enable_key.is_empty() && key == &enable_key { return Err(Error::Invalid( "Use the module switch to turn this module on or off.".into(), )); @@ -1404,4 +1576,33 @@ mod tests { "0" ); } + + #[test] + fn dynamic_plugin_settings_and_enable_roundtrip() { + let d = tempfile::tempdir().unwrap(); + let (root, meta) = server(d.path()); + fs::write( + dir(&root).join("npc_buffer.conf.dist"), + "# Enable NPC Buffer\nNpcBuffer.Enable = 1\n# Cost of buff\nNpcBuffer.Cost = 500\n", + ) + .unwrap(); + + let cat = catalog(); + let s = settings_in(&cat, &root, "npc-buffer").unwrap(); + assert_eq!(s.len(), 2); + let cost = s.iter().find(|item| item.key == "NpcBuffer.Cost").unwrap(); + assert_eq!(cost.value, "500"); + assert_eq!(cost.doc, "Cost of buff"); + + let change = BTreeMap::from([("NpcBuffer.Cost".to_string(), "1000".to_string())]); + let saved = save_settings_in(&cat, &root, &meta, "npc-buffer", &change).unwrap(); + assert_eq!(saved, ["NpcBuffer.Cost"]); + + let conf_content = fs::read_to_string(dir(&root).join("npc_buffer.conf")).unwrap(); + assert!(conf_content.contains("NpcBuffer.Cost = 1000")); + + set_enabled_in(&cat, &root, &meta, "npc-buffer", false).unwrap(); + let conf_content = fs::read_to_string(dir(&root).join("npc_buffer.conf")).unwrap(); + assert!(conf_content.contains("NpcBuffer.Enable = 0")); + } } diff --git a/crates/coa-core/src/plugins.rs b/crates/coa-core/src/plugins.rs index fa0e9af..bbf90cf 100644 --- a/crates/coa-core/src/plugins.rs +++ b/crates/coa-core/src/plugins.rs @@ -132,10 +132,10 @@ pub fn lockfile_path(server: &Path) -> PathBuf { /// Directory for module configs (`Core/configs/modules` or `configs/modules`). pub fn modules_config_dir(server: &Path) -> PathBuf { - if server.join("Core/configs/modules").is_dir() || server.join("Core").is_dir() { - server.join("Core/configs/modules") - } else { + if server.join("configs/modules").is_dir() && !server.join("Core/configs/modules").is_dir() { server.join("configs/modules") + } else { + server.join("Core/configs/modules") } } diff --git a/src/screens/ModulesPage.tsx b/src/screens/ModulesPage.tsx index 3de2c04..e844e09 100644 --- a/src/screens/ModulesPage.tsx +++ b/src/screens/ModulesPage.tsx @@ -15,7 +15,6 @@ import { Loader2, Plug, Puzzle, - RefreshCw, Scaling, Search, Settings2, @@ -121,25 +120,188 @@ function Tile({ icon, off }: { icon: string; off: boolean }) { ); } -export type TabId = "official" | "catalog" | "github" | "installed" | "builds" | "toolchain"; +export type TabId = "installed" | "catalog" | "builds" | "toolchain" | "github"; interface VerifiedCatalogModule { id: string; name: string; repo: string; - category: "utility" | "economy" | "social" | "profession" | "scaling" | "housing" | "scripting"; + category: "official" | "utility" | "economy" | "social" | "profession" | "scaling"; description: { ru: string; en: string }; - qualification: "INSTALL_VERIFIED" | "LINK_VERIFIED" | "BUILT" | "POTENTIAL_CONFLICT" | "CONFLICT_DETECTED" | "CORE_INTEGRATED_REQUIRED" | "DEPENDENCY_MISSING"; + qualification: "OFFICIAL_CORE" | "INSTALL_VERIFIED" | "LINK_VERIFIED" | "BUILT"; tier: string; verificationLevel: string; notes: { ru: string; en: string }; sqlRequired: boolean; canInstall: boolean; + isOfficial?: boolean; + icon?: string; } +const OFFICIAL_IDS = new Set([ + "companions", + "content-scaling", + "tbc-content", + "wotlk-content", + "playerbots", + "custom-races", + "time-is-time", + "client-compat", +]); + const VERIFIED_CATALOG: VerifiedCatalogModule[] = [ + // Official Core Modules { - id: "mod-npc-buffer", + id: "companions", + name: "CoA Companions", + repo: "https://github.com/Corfirean/mod-coa-playerbots", + category: "official", + description: { + ru: "Боты-компаньоны для групп, подземелий и гильдии.", + en: "Companion bots for groups, dungeons and your guild.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный официальный модуль сервера. Взаимоисключение со SQUID's Playerbots.", + en: "Official built-in server module. Mutually exclusive with Playerbots.", + }, + sqlRequired: false, + canInstall: true, + isOfficial: true, + icon: "bot", + }, + { + id: "content-scaling", + name: "Content Scaling", + repo: "https://github.com/Corfirean/mod-coa-content-scaling", + category: "official", + description: { + ru: "Подстраивает подземелья и рейды под вашу группу, есть соло-режимы.", + en: "Scales dungeons and raids to your group, with solo modes.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный официальный модуль динамического масштабирования подземелий.", + en: "Official built-in dynamic dungeon scaling module.", + }, + sqlRequired: false, + canInstall: true, + isOfficial: true, + icon: "scaling", + }, + { + id: "tbc-content", + name: "TBC Content", + repo: "https://github.com/Corfirean/mod-coa-content-scaling", + category: "official", + description: { + ru: "Подземелья и рейды Запределья, подогнанные под ваши уровни.", + en: "Outland dungeons and raids, scaled to your level range.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный пакет контента Burning Crusade.", + en: "Built-in Burning Crusade content pack.", + }, + sqlRequired: false, + canInstall: true, + isOfficial: true, + icon: "tbc", + }, + { + id: "wotlk-content", + name: "WotLK Content", + repo: "https://github.com/Corfirean/mod-coa-content-scaling", + category: "official", + description: { + ru: "Подземелья и рейды Нордскола, подогнанные под ваши уровни.", + en: "Northrend dungeons and raids, scaled to your level range.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный пакет контента Wrath of the Lich King.", + en: "Built-in Wrath of the Lich King content pack.", + }, + sqlRequired: false, + canInstall: true, + isOfficial: true, + icon: "wotlk", + }, + { + id: "playerbots", + name: "SQUID's Playerbots", + repo: "https://github.com/Zyth45/mod-playerbots", + category: "official", + description: { + ru: "Альтернативная система ботов со случайными ботами и полным ИИ.", + en: "An alternative bot system with random bots and full AI.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенная система случайных ботов SQUID. Взаимоисключение с CoA Companions.", + en: "Built-in SQUID random bots system. Mutually exclusive with CoA Companions.", + }, + sqlRequired: true, + canInstall: true, + isOfficial: true, + icon: "swords", + }, + { + id: "custom-races", + name: "Custom Races", + repo: "https://github.com/Corfirean/azerothcore-wotlk-coa", + category: "official", + description: { + ru: "Пользовательские расы (Esteria и другие) с расширенной внешностью и патчем клиента.", + en: "Playable custom races (Esteria and additional races) with extended appearances.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный модуль рас. Требуется установка клиентского MPQ-патча.", + en: "Built-in custom races module. Requires client MPQ patch.", + }, + sqlRequired: true, + canInstall: true, + isOfficial: true, + icon: "races", + }, + { + id: "time-is-time", + name: "TimeIsTime", + repo: "https://github.com/Corfirean/azerothcore-wotlk-coa", + category: "official", + description: { + ru: "Настройка скорости смены дня и ночи и начального времени игрового мира.", + en: "Adjust the day and night cycle speed and starting game time.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный модуль синхронизации игрового времени с сервером.", + en: "Built-in world time synchronization module.", + }, + sqlRequired: false, + canInstall: true, + isOfficial: true, + icon: "sparkles", + }, + + // Supported Dynamic DLL Modules (Verified & Compiling) + { + id: "npc-buffer", name: "NPC Buffer", repo: "https://github.com/azerothcore/mod-npc-buffer", category: "utility", @@ -149,16 +311,17 @@ const VERIFIED_CATALOG: VerifiedCatalogModule[] = [ }, qualification: "INSTALL_VERIFIED", tier: "Tier 1: Dynamic DLL", - verificationLevel: "L0-L4 PASS, L6 PASS (L5 GAMEPLAY_NOT_TESTED)", + verificationLevel: "L0-L4 PASS, L6 PASS", notes: { ru: "Сборка, связывание и динамическая загрузка в реалм подтверждены. Требуется импорт SQL.", en: "Compilation, linking and dynamic realm load verified. Requires SQL migration.", }, sqlRequired: true, canInstall: true, + icon: "plug", }, { - id: "mod-ah-bot", + id: "ah-bot", name: "Auction House Bot", repo: "https://github.com/azerothcore/mod-ah-bot", category: "economy", @@ -175,9 +338,10 @@ const VERIFIED_CATALOG: VerifiedCatalogModule[] = [ }, sqlRequired: false, canInstall: true, + icon: "gavel", }, { - id: "mod-congrats-on-level", + id: "congrats-on-level", name: "Congrats On Level", repo: "https://github.com/azerothcore/mod-congrats-on-level", category: "social", @@ -187,16 +351,17 @@ const VERIFIED_CATALOG: VerifiedCatalogModule[] = [ }, qualification: "INSTALL_VERIFIED", tier: "Tier 1: Dynamic DLL", - verificationLevel: "L0-L4 PASS, L6 PASS (L5 GAMEPLAY_NOT_TESTED)", + verificationLevel: "L0-L4 PASS, L6 PASS", notes: { ru: "Полный цикл жизненного цикла динамического плагина проверен на SDK v0.3.", en: "Full lifecycle verified against CoA Plugin SDK v0.3.", }, sqlRequired: false, canInstall: true, + icon: "sparkles", }, { - id: "mod-npc-enchanter", + id: "npc-enchanter", name: "NPC Enchanter", repo: "https://github.com/azerothcore/mod-npc-enchanter", category: "profession", @@ -206,16 +371,17 @@ const VERIFIED_CATALOG: VerifiedCatalogModule[] = [ }, qualification: "INSTALL_VERIFIED", tier: "Tier 1: Dynamic DLL", - verificationLevel: "L0-L4 PASS, L6 PASS (L5 GAMEPLAY_NOT_TESTED)", + verificationLevel: "L0-L4 PASS, L6 PASS", notes: { ru: "Подтверждена сборка и установка. Для спавна NPC используется команда .npc add 601015.", en: "Build and install verified. Spawn using command .npc add 601015.", }, sqlRequired: true, canInstall: true, + icon: "sparkles", }, { - id: "mod-reward-played-time", + id: "reward-played-time", name: "Reward Played Time", repo: "https://github.com/azerothcore/mod-reward-played-time", category: "social", @@ -225,16 +391,17 @@ const VERIFIED_CATALOG: VerifiedCatalogModule[] = [ }, qualification: "INSTALL_VERIFIED", tier: "Tier 1: Dynamic DLL", - verificationLevel: "L0-L4 PASS, L6 PASS (L5 GAMEPLAY_NOT_TESTED)", + verificationLevel: "L0-L4 PASS, L6 PASS", notes: { ru: "Сборка и установка подтверждены. Содержит миграции базы данных characters.", en: "Build and install verified. Contains characters DB migrations.", }, sqlRequired: true, canInstall: true, + icon: "plug", }, { - id: "mod-transmog", + id: "transmog", name: "Transmogrification", repo: "https://github.com/azerothcore/mod-transmog", category: "utility", @@ -246,14 +413,15 @@ const VERIFIED_CATALOG: VerifiedCatalogModule[] = [ tier: "Tier 1: Dynamic DLL", verificationLevel: "L0-L2 PASS", notes: { - ru: "Сборка C++20 с адаптером успешна. Требуется проверка на живом клиенте.", - en: "C++20 compilation with adapter succeeds. Client testing required.", + ru: "Сборка C++20 с адаптером успешна.", + en: "C++20 compilation with adapter succeeds.", }, sqlRequired: true, canInstall: true, + icon: "plug", }, { - id: "mod-solocraft", + id: "solocraft", name: "Solocraft", repo: "https://github.com/azerothcore/mod-solocraft", category: "scaling", @@ -261,72 +429,16 @@ const VERIFIED_CATALOG: VerifiedCatalogModule[] = [ 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 (Конфликт со встроенным скалированием)", + qualification: "BUILT", + tier: "Tier 1: Dynamic DLL", + verificationLevel: "L0-L2 PASS", notes: { - ru: "Может конфликтовать по балансу со встроенным Content Scaling. Требуется калибровка параметров.", - en: "Potential balance stacking with Content Scaling. Requires parameter calibration.", + ru: "Сборка и связывание успешны. Параметры настраиваются через конфигурационный файл.", + en: "Build and link successful. Configurable via settings.", }, 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, + icon: "scaling", }, ]; @@ -343,7 +455,7 @@ export function ModulesPage({ const human = useHuman(); // Navigation tab - const [activeTab, setActiveTab] = useState("official"); + const [activeTab, setActiveTab] = useState("installed"); // Official modules state const [modules, setModules] = useState(null); @@ -551,7 +663,6 @@ export function ModulesPage({ setAnalysisError(null); setReport(null); setBuildResult(null); - setActiveTab("github"); try { const rep = await api.analyzeGithubModule(targetUrl, serverId); setReport(rep); @@ -562,19 +673,19 @@ export function ModulesPage({ } } - async function startControlledBuild() { - if (!githubUrl.trim() && !report) return; + async function startControlledBuild(urlToBuildParam?: string) { + const target = (urlToBuildParam || (report ? report.repository_name : githubUrl)).trim(); + if (!target) 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}`, + `Target module: ${target}`, "Compiling C++ sources against CoA Plugin SDK v0.3 via MSVC...", ]); - const res = await api.previewBuildModule(serverId, githubUrl.trim()); + const res = await api.previewBuildModule(serverId, target); setBuildResult(res); setBuildLogs(res.log_output); if (res.success) { @@ -586,8 +697,8 @@ export function ModulesPage({ } else { setAnalysisError( locale === "ru" - ? "Сборка завершилась ошибкой. Проверьте диагностику компилятора во вкладке 'Сборки'." - : "Build failed. Check compiler diagnostics in the 'Builds' tab." + ? "Сборка завершилась ошибкой. Проверьте диагностику компилятора во вкладке 'Сборка & логи MSVC'." + : "Build failed. Check compiler diagnostics in the 'Builds & MSVC Logs' tab." ); } } catch (e: unknown) { @@ -620,7 +731,7 @@ export function ModulesPage({ applySql ); setNotification(res.message); - await loadInstalledPlugins(); + await load(); setActiveTab("installed"); onChanged?.(); } catch (e) { @@ -630,21 +741,6 @@ export function ModulesPage({ } } - async function togglePlugin(moduleId: string, currentEnabled: boolean) { - setActionInProgress(`toggle-${moduleId}`); - setError(null); - try { - const msg = await api.previewToggleModule(serverId, moduleId, !currentEnabled); - setNotification(msg); - await loadInstalledPlugins(); - onChanged?.(); - } catch (e) { - setError(asUiError(e)); - } finally { - setActionInProgress(null); - } - } - async function removePlugin(moduleId: string) { if ( !confirm( @@ -680,13 +776,13 @@ export function ModulesPage({ URL.revokeObjectURL(url); } - const selectedOfficial = modules?.find((m) => m.id === openSettings) ?? null; - const selectedOfficialIndex = modules?.findIndex((m) => m.id === openSettings) ?? -1; + const installedModules = modules?.filter((m) => m.installed) ?? []; + const selectedModule = modules?.find((m) => m.id === openSettings) ?? null; + const selectedModuleIndex = installedModules.findIndex((m) => m.id === openSettings); 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 (catalogFilter === "official" && !item.isOfficial) return false; + if (catalogFilter === "verified" && item.isOfficial) return false; if (!catalogQuery.trim()) return true; const q = catalogQuery.toLowerCase(); return ( @@ -808,19 +904,121 @@ export function ModulesPage({ )} + {/* GitHub URL Intake Bar on General Modules Screen */} + +
+
+ + setGithubUrl(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" && githubUrl.trim()) { + void runAnalysis(); + } + }} + placeholder={ + locale === "ru" + ? "Укажите ссылку на GitHub-репозиторий модуля (например, https://github.com/azerothcore/mod-npc-buffer)..." + : "Enter GitHub repository URL (e.g., https://github.com/azerothcore/mod-npc-buffer)..." + } + className="w-full rounded border border-line bg-bg pl-9 pr-3 py-1.5 text-xs text-ink placeholder:text-muted/60 focus:border-gold focus:outline-none" + /> +
+ +
+ + + +
+
+ + {/* Compact analysis banner when report is ready */} + {report && ( +
+
+ {report.repository_name} + @{report.commit.substring(0, 8)} + + {report.classification} + + {report.sql_files.length > 0 && ( + + {report.sql_files.length} SQL + + )} +
+ +
+ + + {buildResult?.success && ( + + )} + +
+
+ )} + + {analysisError && ( +
+ ⚠ {analysisError} + +
+ )} +
+ {/* Tabs Header */}
- - - -
- {/* TAB 0: OFFICIAL MODULES (FROM STABLE CSM DESIGN LANGUAGE) */} - {activeTab === "official" && ( + {/* TAB 0: INSTALLED MODULES */} + {activeTab === "installed" && (

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

{changed && ( @@ -915,246 +1090,284 @@ export function ModulesPage({ {t("overview.checking")}
)} - {modules?.length === 0 && ( - {t("mod.empty")} - )} - {modules?.map((m, i) => ( - - +

+ {locale === "ru" ? "Нет установленных модулей" : "No installed modules"} +

+

+ {locale === "ru" + ? "Выберите модули из Каталога или укажите ссылку на GitHub выше для установки." + : "Choose modules from the Catalog or provide a GitHub URL above to install."} +

+ +
+ )} + {installedModules.map((m, i) => { + const isDynamic = !OFFICIAL_IDS.has(m.id) || installedPlugins.some((p) => p.id === m.id); + return ( + + +
+ +
+
+

{m.name}

+ {m.version && ( + {m.version} + )} + + {isDynamic && ( + + DLL + + )} +
+

+ {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 === "playerbots" || m.id === "squid") && ( +

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

)} -
-

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

- {m.id === "companions" && ( -

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

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

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

+ {m.installed && !m.switchable && m.status !== "soon" && ( + {t("mod.alwaysOn")} )}
- {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")} + {toggling === m.id && ( +

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

- {racesInstalling && racesProgress ? ( -
-
- - - {racesProgress.step} - - - {Math.round(racesProgress.percent * 100)}% - -
-
+ )} + + {/* 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" && ( +
+
+
+ ) : ( +
+
+ {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."} +

-

- {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" && ( + + )} +
+ + {isDynamic && ( + )}
- )} + -
- - {!m.page && m.installed && m.has_settings && m.status !== "soon" && ( - + {/* Inline settings drawer */} + {selectedModule?.has_settings && + !selectedModule.page && + selectedModuleIndex >= 0 && + Math.floor(selectedModuleIndex / 2) === Math.floor(i / 2) && + (i % 2 === 1 || i === installedModules.length - 1) && ( + +
+

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

+ +
+ setChanged(true)} + onRegisterGuard={setGuard} + /> +
)} -
- - - {/* 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} - /> -
- )} - - ))} + + ); + })}
)} @@ -1169,8 +1382,8 @@ export function ModulesPage({

{locale === "ru" - ? "Модули AzerothCore, протестированные против CoA Plugin SDK с честными уровнями квалификации." - : "Curated AzerothCore modules evaluated against CoA Plugin SDK with honest qualification levels."} + ? "Официальные модули и сторонние DLL, протестированные с платформой и готовые к работе." + : "Official modules and third-party DLL plugins verified and fully compatible with the platform."}

@@ -1185,6 +1398,17 @@ export function ModulesPage({ > {locale === "ru" ? "Все" : "All"} ({VERIFIED_CATALOG.length}) + - - @@ -1230,8 +1432,8 @@ export function ModulesPage({ onChange={(e) => setCatalogQuery(e.target.value)} placeholder={ locale === "ru" - ? "Поиск по названию или описанию (например, buffer, enchanter, guildhouse)..." - : "Search verified catalog..." + ? "Поиск по каталогу (например, buffer, enchanter, companions, scaling)..." + : "Search modules 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" /> @@ -1239,107 +1441,136 @@ export function ModulesPage({ {/* Catalog Grid */}
- {filteredCatalog.map((item) => ( - -
-
-
-

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

-

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

+ {filteredCatalog.map((item) => { + const matchedModule = modules?.find( + (m) => m.id === item.id || m.name.toLowerCase() === item.name.toLowerCase() + ); + const isInstalled = Boolean(matchedModule?.installed); + const isEnabled = Boolean(matchedModule?.enabled); + + return ( + +
+
+
+ +
+

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

+

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

+
+
+ + {/* Qualification Badges */} +
+ {item.isOfficial ? ( + + ✓ OFFICIAL_CORE + + ) : item.qualification === "INSTALL_VERIFIED" ? ( + + ✓ INSTALL_VERIFIED + + ) : item.qualification === "LINK_VERIFIED" ? ( + + ✓ LINK_VERIFIED + + ) : ( + + ● BUILT + + )} + + {item.tier} + {item.sqlRequired && ( + SQL + )} +
+ +

+ {locale === "ru" ? item.notes.ru : item.notes.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} -

-
- -
- - -
- + + GitHub + - {item.canInstall ? ( +
- ) : ( - - )} + + {isInstalled ? ( +
+ + ✓ {locale === "ru" ? (isEnabled ? "Включен" : "Установлен") : (isEnabled ? "Active" : "Installed")} + + +
+ ) : item.isOfficial ? ( + + ) : ( + + )} +
-
- - ))} + + ); + })}
{/* Details Modal */} @@ -1393,14 +1624,33 @@ export function ModulesPage({ )}
@@ -1410,373 +1660,6 @@ export function ModulesPage({
)} - {/* TAB 2: GITHUB INSTALLATION & COMPATIBILITY WORKFLOW */} - {activeTab === "github" && ( -
- -

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

-

- {locale === "ru" - ? "Укажите ссылку на 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)."} -

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

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

-
- - License: {report.license_info.primary_license} - - - SDK Host:{" "} - - {report.sdk_fingerprint ? report.sdk_fingerprint.substring(0, 16) + "..." : "Default"} - - -
-
- - {/* 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 && ( -
-
-
{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} -
-
-
- )} - - {/* 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 3: 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} -

- {p.source_commit && ( -

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

- )} -

- 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 4: BUILDS & MSVC LOGS */} {activeTab === "builds" && (