feat(mods): merge additive mod system, official map selector, and mod-dev-docs

# Conflicts:
#	apps/launcher/src/main/workers/build-worker.ts
#	apps/launcher/src/renderer/src/i18n/locales/en.json
#	apps/launcher/src/renderer/src/i18n/locales/zh-CN.json
This commit is contained in:
N0VAN0M4LY committed 2026-12-03 03:43:56 +08:00
commit d94c8fe687
103 files changed
+10829 -1621

No files matched your search

+3
View File
@@ -1,5 +1,8 @@
# Never commit game files (copyright, size). The build reads them from a game folder.
*.vromfs.bin
# Allow additive patch directories named after target packs inside mod templates (never binary archives).
!mod-dev-docs/templates/**/client/packs/*.vromfs.bin/
!mod-dev-docs/templates/**/client/packs/ui/*.vromfs.bin/
*.vromfs.bin.orig
aces.exe
aces*.exe
+1
View File
@@ -14,6 +14,7 @@
},
"dependencies": {
"@fontsource/roboto-condensed": "^5.3.0",
"@wto/mods": "*",
"@wto/patcher": "*",
"@wto/server": "*",
"fflate": "^0.8.2",
+57
View File
@@ -17,6 +17,20 @@ import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesSta
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
import {
applyModPreset,
autoSortMods,
deleteModPreset,
exportModPreset,
getModsState,
importModPreset,
openModDocs,
openModsFolder,
saveModPreset,
setModEnabled,
setModsFolder,
setModsOrder,
} from '../services/mods/mods-service.ts';
import { resourcePaths } from '../services/resources/resource-paths.ts';
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
import { broadcast, handle } from './register.ts';
@@ -175,6 +189,49 @@ export function registerIpcHandlers(): void {
handle('tuning:get', ({ copyId }) => getCopyTuning(copyId));
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
const requireModsWritable = (): void => {
if (launchInProgress() || maintenanceInProgress()) throw new AppError('mods_read_only');
};
handle('mods:getState', ({ copyId }) => getModsState(copyId));
handle('mods:setEnabled', ({ copyId, modId, enabled }) => {
requireModsWritable();
return setModEnabled(copyId, modId, enabled);
});
handle('mods:setOrder', ({ copyId, order }) => {
requireModsWritable();
return setModsOrder(copyId, order);
});
handle('mods:autoSort', ({ copyId }) => {
requireModsWritable();
return autoSortMods(copyId);
});
handle('mods:savePreset', ({ copyId, name, overwriteId }) => {
requireModsWritable();
return saveModPreset(copyId, name, overwriteId);
});
handle('mods:applyPreset', ({ copyId, presetId }) => {
requireModsWritable();
return applyModPreset(copyId, presetId);
});
handle('mods:deletePreset', ({ copyId, presetId }) => {
requireModsWritable();
return deleteModPreset(copyId, presetId);
});
handle('mods:exportPreset', ({ copyId, presetId }, sender) =>
exportModPreset(copyId, presetId, BrowserWindow.fromWebContents(sender)));
handle('mods:importPreset', ({ copyId }, sender) => {
requireModsWritable();
return importModPreset(copyId, BrowserWindow.fromWebContents(sender));
});
handle('mods:openFolder', () => openModsFolder());
handle('mods:openDocs', (input) => openModDocs(input?.language));
handle('mods:setFolder', async ({ copyId, path }) => {
requireModsWritable();
const state = await setModsFolder(copyId, path);
broadcast('event:settings-changed', await getSettings());
return state;
});
handle('launch:getState', () => getLaunchState());
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
handle('launch:start', () => {
@@ -11,6 +11,7 @@ import type { Settings } from '@shared/schemas/settings.ts';
import { getSettings } from '../config/settings-store.ts';
import { decalCachePath } from '../install/decals.ts';
import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts';
import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
import { saveBackup } from '../saves/save-archive.ts';
import { buildCopy } from './build-copy.ts';
@@ -108,7 +109,7 @@ async function launch(job: LaunchJob): Promise<void> {
job.copyId = record.id;
const plan = await planLaunch(job, record, settings);
if (plan === null) return;
const { lab, copyPath, stockPath, dataPath, port } = plan;
const { lab, copyPath, stockPath, dataPath, port, modsDir, enabledModIds } = plan;
await buildForLaunch(job, record, plan, settings);
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
@@ -123,7 +124,15 @@ async function launch(job: LaunchJob): Promise<void> {
update(job, { phase: 'ready' });
return;
}
const gameExit = await runOrdinaryLaunch(copyPath, dataPath, port, settings, signal, publish);
const gameExit = await runOrdinaryLaunch(
copyPath,
dataPath,
port,
settings,
signal,
publish,
{ modsDir, enabledModIds },
);
update(job, { phase: 'game-exited', gameExit });
}
@@ -134,6 +143,8 @@ interface LaunchPlan {
readonly dataPath: string;
readonly steamLibraryConfirmed: boolean;
readonly port: number;
readonly modsDir: string;
readonly enabledModIds: readonly string[];
}
async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> {
@@ -183,13 +194,15 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
}
if (games) throw new AppError('launch_game_running');
const { modsDir, enabledMods } = await resolveEnabledModsForLaunch(dataPath, copyVersion);
const enabledModIds = enabledMods.map((mod) => mod.manifest.id);
const port = await selectPort(requestedPort);
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port };
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port, modsDir, enabledModIds };
}
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> {
const signal = job.stop.signal;
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan;
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed, modsDir, enabledModIds } = plan;
if (settings.autoSaveBackups) {
for (const { userId } of new AccountStore(dataPath).all()) {
signal.throwIfAborted();
@@ -211,6 +224,8 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
hookLogging: settings.loggingEnabled,
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
modsDir,
enabledModIds,
}, signal, (filesWritten, filesTotal, file) => {
writtenFiles = filesWritten;
if (!signal.aborted) update(job, {
@@ -33,13 +33,22 @@ export async function localServerReady(port: number, pid?: number, signal?: Abor
}
}
export interface StartLocalServerOptions extends Omit<ServerOptions, 'report' | 'mods'> {
readonly modsDir?: string;
readonly enabledModIds?: readonly string[];
}
export async function startLocalServer(
{ gameFolder, dataFolder, port, loggingEnabled = true }: Omit<ServerOptions, 'report'>, signal: AbortSignal,
{ gameFolder, dataFolder, port, loggingEnabled = true, modsDir, enabledModIds }: StartLocalServerOptions, signal: AbortSignal,
): Promise<LocalServer> {
signal.throwIfAborted();
const workerArgs = [gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'];
if (modsDir && enabledModIds && enabledModIds.length > 0) {
workerArgs.push(modsDir, JSON.stringify(enabledModIds));
}
const worker = utilityProcess.fork(
join(import.meta.dirname, 'server-worker.js'),
[gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'],
workerArgs,
{
serviceName: 'WTOffline local server',
stdio: 'pipe',
@@ -45,12 +45,19 @@ type OrdinaryPhase = 'starting-server' | 'starting-game' | 'running' | 'server-r
export async function runOrdinaryLaunch(
copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal,
publish: (phase: OrdinaryPhase, gameExit?: GameExit) => void,
mods?: { readonly modsDir: string; readonly enabledModIds: readonly string[] },
): Promise<GameExit> {
const args = parseLaunchArguments(settings.launchArguments);
if (!args) throw new AppError('launch_game_failed');
publish('starting-server');
const server = await startLocalServer(
{ gameFolder: copyPath, dataFolder: dataPath, port, loggingEnabled: settings.loggingEnabled },
{
gameFolder: copyPath,
dataFolder: dataPath,
port,
loggingEnabled: settings.loggingEnabled,
...(mods && mods.enabledModIds.length > 0 ? { modsDir: mods.modsDir, enabledModIds: mods.enabledModIds } : {}),
},
signal,
);
const stop = new AbortController();
@@ -0,0 +1,442 @@
import { randomUUID } from 'node:crypto';
import { access, cp, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
import { isAbsolute, join } from 'node:path';
import { app, BrowserWindow, dialog, shell } from 'electron';
import {
computeAutoSortOrder,
discoverMods,
emptyClientModsConfig,
MOD_API_VERSION,
normalizeClientModsConfig,
resolveModLoadOrder,
type ClientModsConfig,
type DiscoveredMod,
type ModPreset,
} from '@wto/mods';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
import { getSettings, updateSettings } from '../config/settings-store.ts';
import { listCopies } from '../install/install-record.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
const CLIENT_MODS_CONFIG_FILE = 'mods-config.json';
const EXAMPLES_SEEDED_MARKER = '.wto-examples-seeded';
const inFlightSeeds = new Map<string, Promise<void>>();
export function defaultModsFolder(): string {
return join(app.getPath('userData'), 'mods');
}
export async function resolveModsFolder(): Promise<{ readonly modsDir: string; readonly defaultModsDir: string; readonly isCustomModsDir: boolean }> {
const settings = await getSettings();
const defaultModsDir = defaultModsFolder();
const isCustomModsDir = settings.modsFolder !== null;
const modsDir = settings.modsFolder ?? defaultModsDir;
await mkdir(modsDir, { recursive: true });
await seedBundledExampleModsOnce(modsDir);
return { modsDir, defaultModsDir, isCustomModsDir };
}
/**
* Copy newly shipped bundled template mods into the mods folder once each (disabled by default).
* Tracks which template folder names have already been seeded in `.wto-examples-seeded` so
* deleting a bundled template never restores it, while newly added official templates still
* appear for existing users. Serialized per directory to prevent concurrent seeding races.
*/
async function seedBundledExampleModsOnce(modsDir: string): Promise<void> {
const key = modsDir.toLowerCase();
const pending = inFlightSeeds.get(key);
if (pending) {
await pending;
return;
}
const task = (async () => {
const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER);
try {
const templatesRoot = resourcePaths().modTemplates;
if (!(await pathExists(templatesRoot))) return;
const seeded = await readSeededTemplateNames(markerPath, modsDir);
const templates = await readdir(templatesRoot, { withFileTypes: true });
let changed = false;
for (const entry of templates) {
if (!entry.isDirectory()) continue;
if (seeded.has(entry.name)) continue;
const dest = join(modsDir, entry.name);
if (!(await pathExists(dest))) {
await cp(join(templatesRoot, entry.name), dest, { recursive: true });
}
seeded.add(entry.name);
changed = true;
}
if (changed || !(await pathExists(markerPath))) {
await writeFile(markerPath, JSON.stringify({ seeded: [...seeded].sort() }, null, 2) + '\n', 'utf8');
}
} catch (error) {
console.warn('[mods] seeding bundled example mods skipped:', error);
}
})().finally(() => {
inFlightSeeds.delete(key);
});
inFlightSeeds.set(key, task);
await task;
}
async function readSeededTemplateNames(markerPath: string, modsDir: string): Promise<Set<string>> {
if (!(await pathExists(markerPath))) return new Set();
try {
const raw = (await readFile(markerPath, 'utf8')).trim();
if (raw === '1') {
// Legacy marker from initial 2-template version: mark existing folders as already seeded
// so newly added official templates (e.g. official-map-selector) are still delivered once.
const existing = await readdir(modsDir);
const set = new Set(['example-vehicle-tweak', 'example-server-script']);
for (const name of existing) set.add(name);
return set;
}
const parsed = JSON.parse(raw) as { seeded?: unknown };
if (Array.isArray(parsed.seeded)) {
return new Set(parsed.seeded.filter((item): item is string => typeof item === 'string'));
}
} catch { /* ignore */ }
return new Set();
}
async function pathExists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch {
return false;
}
}
export async function openModsFolder(): Promise<void> {
const { modsDir } = await resolveModsFolder();
const failure = await shell.openPath(modsDir);
if (failure) console.warn('[mods] opening the mods folder failed:', modsDir, failure);
}
export async function openModDocs(language?: string): Promise<void> {
const docsRoot = resourcePaths().modDocs;
const preferred = language && language.toLowerCase().startsWith('zh') ? 'zh-CN.html' : 'en.html';
const fallback = preferred === 'zh-CN.html' ? 'en.html' : 'zh-CN.html';
const target = (await pathExists(join(docsRoot, preferred)))
? join(docsRoot, preferred)
: join(docsRoot, fallback);
if (!(await pathExists(target))) {
throw new AppError('folder_unreadable', { path: docsRoot });
}
const failure = await shell.openPath(target);
if (failure) console.warn('[mods] opening the mod docs failed:', target, failure);
}
export async function getModsState(copyId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
return buildModsStateView(copy);
}
export async function setModEnabled(copyId: string, modId: string, enabled: boolean): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const next: ClientModsConfig = {
...current,
activePresetId: null,
enabled: { ...current.enabled, [modId]: enabled },
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function setModsOrder(copyId: string, order: readonly string[]): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const next = normalizeClientModsConfig({ ...current, activePresetId: null, order }, discovered.mods);
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function autoSortMods(copyId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const sortedOrder = computeAutoSortOrder(discovered.mods, current.order);
const next: ClientModsConfig = {
...current,
activePresetId: null,
order: sortedOrder,
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function saveModPreset(copyId: string, name: string, overwriteId?: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const now = new Date().toISOString();
let presets: ModPreset[];
let presetId: string;
if (overwriteId && current.presets.some((preset) => preset.id === overwriteId)) {
presetId = overwriteId;
presets = current.presets.map((preset) => (
preset.id === overwriteId
? { id: preset.id, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now }
: preset
));
} else {
presetId = randomUUID();
presets = [
...current.presets,
{ id: presetId, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now },
];
}
const next: ClientModsConfig = {
...current,
activePresetId: presetId,
presets,
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function applyModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const preset = current.presets.find((item) => item.id === presetId);
if (!preset) throw new AppError('mods_preset_invalid');
const next = normalizeClientModsConfig({
...current,
order: preset.order,
enabled: preset.enabled,
activePresetId: preset.id,
}, discovered.mods);
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function deleteModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const current = await readClientModsConfig(copy.dataPath);
const next: ClientModsConfig = {
...current,
activePresetId: current.activePresetId === presetId ? null : current.activePresetId,
presets: current.presets.filter((preset) => preset.id !== presetId),
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function exportModPreset(
copyId: string,
presetId: string,
window: BrowserWindow | null,
): Promise<{ readonly path: string | null }> {
const copy = await requireCopy(copyId);
const current = await readClientModsConfig(copy.dataPath);
const preset = current.presets.find((item) => item.id === presetId);
if (!preset) throw new AppError('mods_preset_invalid');
const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset';
const dialogOptions = {
defaultPath: `${safeName}.wto-mods-preset.json`,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
};
const choice = window
? await dialog.showSaveDialog(window, dialogOptions)
: await dialog.showSaveDialog(dialogOptions);
if (choice.canceled || !choice.filePath) return { path: null };
const payload = {
format: 1 as const,
name: preset.name,
order: [...preset.order],
enabled: { ...preset.enabled },
};
await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
return { path: choice.filePath };
}
export async function importModPreset(
copyId: string,
window: BrowserWindow | null,
): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> {
const copy = await requireCopy(copyId);
const dialogOptions = {
properties: ['openFile'] as Array<'openFile'>,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
};
const choice = window
? await dialog.showOpenDialog(window, dialogOptions)
: await dialog.showOpenDialog(dialogOptions);
if (choice.canceled || !choice.filePaths[0]) {
return { imported: false, state: await buildModsStateView(copy) };
}
let parsedRaw: unknown;
try {
parsedRaw = JSON.parse(await readFile(choice.filePaths[0], 'utf8')) as unknown;
} catch {
throw new AppError('mods_preset_invalid');
}
const validated = ModPresetTransferSchema.safeParse(parsedRaw);
if (!validated.success) throw new AppError('mods_preset_invalid');
const current = await readClientModsConfig(copy.dataPath);
const newPreset: ModPreset = {
id: randomUUID(),
name: validated.data.name,
order: validated.data.order,
enabled: validated.data.enabled,
updatedAt: new Date().toISOString(),
};
const next: ClientModsConfig = {
...current,
presets: [...current.presets, newPreset],
};
await writeClientModsConfig(copy.dataPath, next);
return { imported: true, state: await buildModsStateView(copy, next) };
}
export async function setModsFolder(copyId: string, folderPath: string | null): Promise<ModsStateView> {
if (folderPath !== null) {
if (!isAbsolute(folderPath)) throw new AppError('mods_folder_invalid');
try {
await mkdir(folderPath, { recursive: true });
const info = await stat(folderPath);
if (!info.isDirectory()) throw new AppError('mods_folder_invalid');
} catch (error) {
if (error instanceof AppError) throw error;
throw new AppError('mods_folder_invalid');
}
}
await updateSettings({ modsFolder: folderPath });
const copy = await requireCopy(copyId);
return buildModsStateView(copy);
}
/** Resolve ordered enabled mods for a launch; rejects when blocking dependency/conflict errors exist. */
export async function resolveEnabledModsForLaunch(
dataPath: string,
gameVersion: string | null,
): Promise<{ readonly modsDir: string; readonly enabledMods: readonly DiscoveredMod[] }> {
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const config = normalizeClientModsConfig(await readClientModsConfig(dataPath), discovered.mods);
const resolved = resolveModLoadOrder(discovered.mods, config, gameVersion);
if (resolved.hasBlockingErrors) {
console.error('[mods] blocking mod issues prevented launch:', resolved.issues.filter((i) => i.severity === 'error'));
throw new AppError('mods_blocking_issues');
}
return { modsDir, enabledMods: resolved.enabledMods };
}
async function buildModsStateView(copy: InstallRecord, preloadedConfig?: ClientModsConfig): Promise<ModsStateView> {
const { modsDir, defaultModsDir, isCustomModsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const rawConfig = preloadedConfig ?? await readClientModsConfig(copy.dataPath);
const config = normalizeClientModsConfig(rawConfig, discovered.mods);
const resolved = resolveModLoadOrder(discovered.mods, config, copy.gameVersion);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const orderedMods: ModListItem[] = config.order
.map((id) => byId.get(id))
.filter((mod): mod is DiscoveredMod => mod !== undefined)
.map(toModListItem);
return {
modsDir,
defaultModsDir,
isCustomModsDir,
apiVersion: MOD_API_VERSION,
mods: orderedMods,
discoveryErrors: [...discovered.errors],
order: [...config.order],
enabled: { ...config.enabled },
activePresetId: config.activePresetId,
presets: config.presets.map((preset) => ({
id: preset.id,
name: preset.name,
order: [...preset.order],
enabled: { ...preset.enabled },
updatedAt: preset.updatedAt,
})),
issues: [...resolved.issues],
hasBlockingErrors: resolved.hasBlockingErrors,
};
}
function toModListItem(mod: DiscoveredMod): ModListItem {
return {
id: mod.manifest.id,
folderName: mod.folderName,
rootDir: mod.rootDir,
name: mod.manifest.name,
...(mod.manifest.description !== undefined ? { description: mod.manifest.description } : {}),
version: mod.manifest.version,
author: mod.manifest.author,
apiVersion: mod.manifest.apiVersion,
gameVersions: [...mod.manifest.gameVersions],
requires: [...mod.manifest.requires],
conflicts: [...mod.manifest.conflicts],
loadAfter: [...mod.manifest.loadAfter],
loadBefore: [...mod.manifest.loadBefore],
badges: [...mod.content.badges],
hasServerScript: mod.content.serverEntry !== undefined,
serverTuningFiles: [...mod.content.serverTuningFiles],
packOperations: [...mod.content.packOperations],
guiPatchCount: mod.content.guiPatchDirs.length,
exePatchCount: mod.content.exePatchDirs.length,
hasClientAddon: mod.content.hasClientAddon,
addonFileCount: mod.content.addonRelativeFiles.length,
clientFileCount: mod.content.clientFiles.length,
hasConfigBlkPatch: mod.content.configBlkPatch !== undefined,
};
}
async function requireCopy(copyId: string): Promise<InstallRecord> {
const copies = await listCopies();
const copy = copies.copies.find((entry) => entry.id === copyId);
if (!copy) throw new AppError('copy_not_found');
return copy;
}
async function readClientModsConfig(dataPath: string): Promise<ClientModsConfig> {
const path = join(dataPath, CLIENT_MODS_CONFIG_FILE);
try {
const raw = await readJsonOr(path, null);
if (!raw || typeof raw !== 'object') return emptyClientModsConfig();
const obj = raw as Partial<ClientModsConfig>;
return {
format: 1,
order: Array.isArray(obj.order) ? obj.order.filter((item): item is string => typeof item === 'string') : [],
enabled: obj.enabled && typeof obj.enabled === 'object' ? { ...obj.enabled } : {},
activePresetId: typeof obj.activePresetId === 'string' ? obj.activePresetId : null,
presets: Array.isArray(obj.presets) ? obj.presets : [],
};
} catch (error) {
console.warn('[mods] unreadable client mods config, using defaults:', path, error);
return emptyClientModsConfig();
}
}
async function writeClientModsConfig(dataPath: string, config: ClientModsConfig): Promise<void> {
try {
await writeJsonAtomic(join(dataPath, CLIENT_MODS_CONFIG_FILE), config);
} catch (error) {
console.error('[mods] writing client mods config failed:', error);
throw new AppError('mods_write_failed');
}
}
@@ -17,6 +17,10 @@ export interface ResourcePaths {
readonly networkHookLibrary: string;
/** Multi-resolution Windows icon for the window and system tray. */
readonly appIcon: string;
/** Bundled example mod templates seeded into an empty mods folder on first use. */
readonly modTemplates: string;
/** Offline HTML mod development handbook (zh-CN.html and en.html). */
readonly modDocs: string;
}
export function resourcePaths(): ResourcePaths {
@@ -32,6 +36,8 @@ export function bundledResourcePaths(): ResourcePaths {
patches: join(process.resourcesPath, 'patches'),
networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'),
appIcon: join(process.resourcesPath, 'icon.ico'),
modTemplates: join(process.resourcesPath, 'mod-templates'),
modDocs: join(process.resourcesPath, 'mod-dev-docs'),
};
}
// The app path is apps/launcher; the repository is two levels up.
@@ -40,6 +46,8 @@ export function bundledResourcePaths(): ResourcePaths {
patches: join(repository, 'patches'),
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
modTemplates: join(repository, 'mod-dev-docs', 'templates'),
modDocs: join(repository, 'build', 'mod-dev-docs'),
};
}
@@ -12,6 +12,8 @@ export interface BuildRequest {
readonly decalCache?: string;
readonly hookLogging: boolean;
readonly acceptedUnavailable: readonly string[];
readonly modsDir?: string;
readonly enabledModIds?: readonly string[];
}
export type BuildCommand = BuildRequest | { readonly kind: 'write' };
+63 -5
View File
@@ -1,7 +1,21 @@
import { readFileSync, realpathSync } from 'node:fs';
import { relative } from 'node:path';
import type { MessageEvent } from 'electron';
import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCacheProblem, readPlayerDecalIndexFiles, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher';
import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods';
import {
assertWritableCopy,
buildGameCopy,
computeModsBuildFingerprint,
copyPlayerDecalCache,
CORE_BUILD_PACKS,
playerDecalCacheProblem,
prepareOptionalStockPacks,
readPlayerDecalIndexFiles,
readStockGameFiles,
syncExternalModFiles,
writeGameCopy,
type GameCopyFile,
} from '@wto/patcher';
import { multiVehiclePackIds } from '@wto/server';
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
@@ -9,6 +23,9 @@ let prepared: {
readonly request: BuildRequest;
readonly files: readonly GameCopyFile[];
readonly decalCache: string | undefined;
readonly enabledMods: readonly DiscoveredMod[];
readonly optionalPacksInBuild: readonly ModdableClientPack[];
readonly fingerprint: string;
} | null = null;
function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void {
@@ -31,19 +48,41 @@ function importedDecals(path: string | undefined): string | undefined {
return undefined;
}
function resolveOrderedMods(modsDir: string | undefined, enabledModIds: readonly string[] | undefined): DiscoveredMod[] {
if (!modsDir || !enabledModIds || enabledModIds.length === 0) return [];
const discovered = discoverMods(modsDir);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const ordered: DiscoveredMod[] = [];
for (const id of enabledModIds) {
const mod = byId.get(id);
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
ordered.push(mod);
}
return ordered;
}
function build(request: BuildRequest): void {
checkBuildLocation(request);
const decalCache = importedDecals(request.decalCache);
const decalIndexFiles = decalCache ? readPlayerDecalIndexFiles(decalCache) : undefined;
const enabledMods = resolveOrderedMods(request.modsDir, request.enabledModIds);
const touchedPacks = touchedClientPacks(enabledMods);
const optionalPacksInBuild = touchedPacks.filter((pack) => !CORE_BUILD_PACKS.has(pack));
const extraStockPacks = optionalPacksInBuild.length > 0
? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild)
: undefined;
const result = buildGameCopy({
stock: readStockGameFiles(request.stockPath),
patches: request.patches,
networkHookLibrary: readFileSync(request.networkHookLibrary),
port: request.port,
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info),
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info, enabledMods),
placeholderDecals: decalCache === undefined,
...(decalIndexFiles ? { decalIndexFiles } : {}),
hookLogging: request.hookLogging,
...(enabledMods.length > 0 ? { mods: enabledMods } : {}),
...(extraStockPacks ? { extraStockPacks } : {}),
});
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
const accepted = new Set(request.acceptedUnavailable);
@@ -52,7 +91,19 @@ function build(request: BuildRequest): void {
send({ kind: 'failed', error: 'launch_build_unavailable' });
return;
}
prepared = { request, files: result.files, decalCache };
if (result.mods.enabledModIds.length > 0) {
console.info(
`[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` +
`(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` +
`gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` +
`exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`,
);
for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) {
console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`);
}
}
const fingerprint = computeModsBuildFingerprint(enabledMods, request.port, request.patches);
prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint };
send({ kind: 'prepared', total: prepared.files.length });
}
@@ -64,15 +115,22 @@ process.parentPort.on('message', (event: MessageEvent) => {
return;
}
if (!prepared) throw new Error('No build is ready to write.');
const { request, files, decalCache } = prepared;
const { request, files, decalCache, enabledMods, optionalPacksInBuild, fingerprint } = prepared;
prepared = null;
checkBuildLocation(request);
const { copyPath } = request;
const { copyPath, stockPath } = request;
if (decalCache) copyPlayerDecalCache(decalCache, copyPath);
for (const [index, file] of files.entries()) {
writeGameCopy(copyPath, [file]);
send({ kind: 'progress', written: index + 1, total: files.length, file: file.path });
}
const deployResult = syncExternalModFiles(copyPath, stockPath, enabledMods, optionalPacksInBuild, fingerprint);
for (const warning of deployResult.warnings) {
console.warn(`[mods] skipped "${warning.targetRelPath}" from "${warning.modId}": ${warning.reason}`);
}
if (deployResult.restoredOptionalPacks.length > 0) {
console.info(`[mods] restored stock pack(s): ${deployResult.restoredOptionalPacks.join(', ')}`);
}
send({ kind: 'written' });
} catch (error) {
console.error('[build] preparing the game copy failed:', error);
@@ -1,16 +1,42 @@
import { discoverMods, type DiscoveredMod } from '@wto/mods';
import { startServer } from '@wto/server';
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
function loadOrderedMods(modsDir: string | undefined, enabledJson: string | undefined): DiscoveredMod[] {
if (!modsDir || !enabledJson) return [];
const ids = JSON.parse(enabledJson) as unknown;
if (!Array.isArray(ids) || ids.length === 0) return [];
const discovered = discoverMods(modsDir);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const mods: DiscoveredMod[] = [];
for (const id of ids) {
if (typeof id !== 'string') continue;
const mod = byId.get(id);
if (!mod) throw new Error(`Enabled mod "${id}" not found in ${modsDir}`);
mods.push(mod);
}
return mods;
}
async function serve(): Promise<void> {
const [gameFolder, dataFolder, portText, loggingFlag] = process.argv.slice(2);
const [gameFolder, dataFolder, portText, loggingFlag, modsDir, enabledModIdsJson] = process.argv.slice(2);
const port = Number(portText);
if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('Invalid local server arguments.');
}
const loggingEnabled = loggingFlag !== '0';
const server = await startServer({ gameFolder, dataFolder, port, loggingEnabled, report: console.info });
const mods = loadOrderedMods(modsDir, enabledModIdsJson);
const server = await startServer({
gameFolder,
dataFolder,
port,
loggingEnabled,
...(mods.length > 0 ? { mods } : {}),
report: console.info,
});
if (server.logFolder) console.info('Traffic log:', server.logFolder);
if (server.loadedModIds.length > 0) console.info('Loaded server script mods:', server.loadedModIds.join(', '));
process.parentPort.once('message', () => {
void server.close().then(() => process.exit(0)).catch((error: unknown) => {
console.error('Could not close the local server:', error);
+10 -1
View File
@@ -22,6 +22,7 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts';
import { WizardMain } from './pages/install/WizardMain.tsx';
import { WizardSide } from './pages/install/WizardSide.tsx';
import { wizardBar } from './pages/install/wizard-bar.ts';
import { ModsPage } from './pages/mods/ModsPage.tsx';
import { TuningPage } from './pages/tuning/TuningPage.tsx';
import { SavesPage } from './pages/saves/SavesPage.tsx';
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
@@ -32,7 +33,7 @@ import { Background } from './shell/Background.tsx';
import { BottomBar } from './shell/BottomBar.tsx';
import type { BarModel } from './shell/bar-model.ts';
import { Footer } from './shell/Footer.tsx';
import { COPY_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
import { COPY_SECTIONS, MODS_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
import { SubNav } from './shell/SubNav.tsx';
import { TitleBar } from './shell/TitleBar.tsx';
import { useBackgrounds } from './shell/useBackgrounds.ts';
@@ -195,6 +196,14 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
: <Sheet title={t(`tuning.sections.${route.tuning}`)}><p className="lead">{t('tuning.noCopy')}</p></Sheet>,
bar: home,
};
case 'mods':
return {
side: <SubNav sections={MODS_SECTIONS} active={route.mods} label={(section) => t(`mods.sections.${section}`)} onSelect={(section) => go({ page: 'mods', section })} />,
main: record
? <ModsPage key={record.id} copy={record} section={route.mods} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'server-running', 'stopping'].includes(launch.phase)} onError={report} />
: <Sheet title={t(`mods.sections.${route.mods}`)}><p className="lead">{t('mods.noCopy')}</p></Sheet>,
bar: home,
};
case 'copies': {
const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />;
if (route.copies === 'list') {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,589 @@
import { useCallback, useEffect, useMemo, useState, type DragEvent, type FormEvent } from 'react';
import { useTranslation } from 'react-i18next';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { ModIssueView, ModListItem, ModsStateView } from '@shared/schemas/mods.ts';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
import type { ModsSection } from '../../shell/navigation.ts';
interface Props {
readonly copy: InstallRecord;
readonly section: ModsSection;
readonly readOnly: boolean;
readonly onError: (error: unknown) => void;
}
function localized(value: string | Readonly<Record<string, string>> | undefined, language: string): string {
if (!value) return '';
if (typeof value === 'string') return value;
const exact = value[language];
if (exact) return exact;
const prefix = language.split('-')[0];
if (prefix) {
const match = Object.entries(value).find(([key]) => key === prefix || key.startsWith(`${prefix}-`));
if (match?.[1]) return match[1];
}
return value.en ?? value['en-US'] ?? Object.values(value)[0] ?? '';
}
export function ModsPage({ copy, section, readOnly, onError }: Props) {
const { t, i18n } = useTranslation();
const [state, setState] = useState<ModsStateView | null>(null);
const [busy, setBusy] = useState(false);
const [query, setQuery] = useState('');
const [expandedId, setExpandedId] = useState<string | null>(null);
const [draggedId, setDraggedId] = useState<string | null>(null);
const [presetName, setPresetName] = useState('');
const [notice, setNotice] = useState<string | null>(null);
const load = useCallback(() => {
setBusy(true);
ipcInvoke('mods:getState', { copyId: copy.id })
.then(setState)
.catch(onError)
.finally(() => setBusy(false));
}, [copy.id, onError]);
useEffect(() => {
let mounted = true;
const sync = (): void => {
ipcInvoke('mods:getState', { copyId: copy.id })
.then((result) => { if (mounted) setState(result); })
.catch(onError);
};
sync();
window.addEventListener('focus', sync);
return () => {
mounted = false;
window.removeEventListener('focus', sync);
};
}, [copy.id, onError]);
const runAction = (action: Promise<ModsStateView>, successNotice?: string): void => {
setBusy(true);
setNotice(null);
action
.then((next) => {
setState(next);
if (successNotice) setNotice(successNotice);
})
.catch(onError)
.finally(() => setBusy(false));
};
const issuesByMod = useMemo(() => {
const map = new Map<string, ModIssueView[]>();
for (const issue of state?.issues ?? []) {
const list = map.get(issue.modId) ?? [];
list.push(issue);
map.set(issue.modId, list);
}
return map;
}, [state]);
const title = t(`mods.sections.${section}`);
if (!state) {
return <Sheet title={title} aside={copy.name}><p className="lead">{t('mods.loading')}</p></Sheet>;
}
const disabled = readOnly || busy;
const enabledCount = state.mods.filter((mod) => state.enabled[mod.id] === true).length;
const toggleMod = (modId: string, nextEnabled: boolean): void => {
runAction(ipcInvoke('mods:setEnabled', { copyId: copy.id, modId, enabled: nextEnabled }));
};
const reorder = (nextOrder: string[]): void => {
runAction(ipcInvoke('mods:setOrder', { copyId: copy.id, order: nextOrder }));
};
const moveMod = (modId: string, delta: -1 | 1): void => {
const idx = state.order.indexOf(modId);
const target = idx + delta;
if (idx < 0 || target < 0 || target >= state.order.length) return;
const next = [...state.order];
const [item] = next.splice(idx, 1);
next.splice(target, 0, item!);
reorder(next);
};
const handleDrop = (targetId: string, event: DragEvent<HTMLDivElement>): void => {
event.preventDefault();
const sourceId = draggedId;
setDraggedId(null);
if (!sourceId || sourceId === targetId || disabled) return;
const from = state.order.indexOf(sourceId);
const to = state.order.indexOf(targetId);
if (from < 0 || to < 0) return;
const next = [...state.order];
const [moved] = next.splice(from, 1);
next.splice(to, 0, moved!);
reorder(next);
};
const savePreset = (event: FormEvent<HTMLFormElement>): void => {
event.preventDefault();
const trimmed = presetName.trim();
if (!trimmed) return;
runAction(
ipcInvoke('mods:savePreset', { copyId: copy.id, name: trimmed }),
t('mods.presets.saved', { name: trimmed }),
);
setPresetName('');
};
const pickCustomFolder = (): void => {
ipcInvoke('dialog:pickFolder', { title: t('mods.repo.pickTitle') })
.then(({ path }) => {
if (!path) return;
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path }), t('mods.repo.updated'));
})
.catch(onError);
};
const resetFolder = (): void => {
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path: null }), t('mods.repo.resetDone'));
};
const exportPreset = (presetId: string): void => {
setBusy(true);
setNotice(null);
ipcInvoke('mods:exportPreset', { copyId: copy.id, presetId })
.then(({ path }) => {
if (path) setNotice(t('mods.presets.exported', { path }));
})
.catch(onError)
.finally(() => setBusy(false));
};
const importPreset = (): void => {
setBusy(true);
setNotice(null);
ipcInvoke('mods:importPreset', { copyId: copy.id })
.then(({ imported, state: next }) => {
setState(next);
if (imported) setNotice(t('mods.presets.imported'));
})
.catch(onError)
.finally(() => setBusy(false));
};
const normalizedQuery = query.trim().toLowerCase();
const visibleMods = normalizedQuery
? state.mods.filter((mod) => {
const displayName = localized(mod.name, i18n.language).toLowerCase();
return displayName.includes(normalizedQuery)
|| mod.id.toLowerCase().includes(normalizedQuery)
|| mod.author.toLowerCase().includes(normalizedQuery);
})
: state.mods;
const canDrag = !disabled && normalizedQuery.length === 0;
return (
<Sheet
title={title}
aside={(
<span className="mods-aside">
<span>{copy.name} · {t('mods.enabledSummary', { enabled: enabledCount, total: state.mods.length })}</span>
<span
className="mods-exp-chip"
tabIndex={0}
aria-label={t('mods.experimentalBody', { api: state.apiVersion })}
>
<span>{t('mods.experimentalChip')}</span>
<span className="mods-exp-icon" aria-hidden="true">i</span>
<span className="mods-exp-popover" role="tooltip">
<strong>{t('mods.experimentalTitle')}</strong>
<span>{t('mods.experimentalBody', { api: state.apiVersion })}</span>
</span>
</span>
</span>
)}
>
{readOnly && (
<div className="mods-banner mods-banner-warn" role="status">
{t('mods.readOnlyNotice')}
</div>
)}
{notice && (
<div className="mods-banner mods-banner-ok" role="status">
{notice}
</div>
)}
{section === 'list' ? (
<>
<div className="mods-toolbar">
<input
type="search"
className="input mods-search"
placeholder={t('mods.searchPlaceholder')}
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
{state.presets.length > 0 && (
<select
className="select mods-preset-select"
aria-label={t('mods.presets.quickSwitch')}
disabled={disabled}
value={state.activePresetId ?? ''}
onChange={(event) => {
const id = event.target.value;
if (id) runAction(ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: id }));
}}
>
<option value="">{t('mods.presets.customOption')}</option>
{state.presets.map((preset) => (
<option key={preset.id} value={preset.id}>{preset.name}</option>
))}
</select>
)}
<button
type="button"
className="button"
disabled={disabled || state.mods.length < 2}
onClick={() => runAction(ipcInvoke('mods:autoSort', { copyId: copy.id }), t('mods.autoSorted'))}
>
{t('mods.autoSort')}
</button>
<button type="button" className="button" disabled={busy} onClick={load}>
{t('mods.refresh')}
</button>
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
{t('mods.openFolder')}
</button>
<button type="button" className="button" onClick={() => ipcInvoke('mods:openDocs', { language: i18n.language }).catch(onError)}>
{t('mods.openDocs')}
</button>
</div>
{state.discoveryErrors.length > 0 && (
<div className="mods-issues-box mods-issues-error">
<div className="mods-issues-title">{t('mods.discoveryErrorsTitle', { count: state.discoveryErrors.length })}</div>
<ul>
{state.discoveryErrors.map((err) => (
<li key={err.folderName}>
<code>{err.folderName}</code>: {err.reason}
</li>
))}
</ul>
</div>
)}
{state.issues.length > 0 && (
<div className={state.hasBlockingErrors ? 'mods-issues-box mods-issues-error' : 'mods-issues-box mods-issues-warn'}>
<div className="mods-issues-title">
{state.hasBlockingErrors
? t('mods.blockingIssuesTitle', { count: state.issues.filter((i) => i.severity === 'error').length })
: t('mods.issuesTitle', { count: state.issues.length })}
</div>
<ul>
{state.issues.map((issue, idx) => (
<li key={`${issue.modId}-${issue.kind}-${idx}`} className={`mods-issue-${issue.severity}`}>
<span className="mods-issue-tag">{t(`mods.severity.${issue.severity}`)}</span>
<strong>{issue.modId}</strong>: {issue.detail}
</li>
))}
</ul>
</div>
)}
{visibleMods.length === 0 ? (
<div className="mods-empty">
<p className="lead">{state.mods.length === 0 ? t('mods.emptyTitle') : t('mods.noSearchMatch')}</p>
{state.mods.length === 0 && (
<>
<p className="mods-hint">{t('mods.emptyHint', { path: state.modsDir })}</p>
<button type="button" className="button button-primary" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
{t('mods.openFolder')}
</button>
</>
)}
</div>
) : (
<div className="mods-list">
{visibleMods.map((mod) => {
const index = state.order.indexOf(mod.id);
const isEnabled = state.enabled[mod.id] === true;
const isExpanded = expandedId === mod.id;
const modIssues = issuesByMod.get(mod.id) ?? [];
return (
<ModCard
key={mod.id}
mod={mod}
index={index}
total={state.order.length}
enabled={isEnabled}
expanded={isExpanded}
disabled={disabled}
canDrag={canDrag}
language={i18n.language}
issues={modIssues}
onToggle={(next) => toggleMod(mod.id, next)}
onMove={(delta) => moveMod(mod.id, delta)}
onToggleExpand={() => setExpandedId(isExpanded ? null : mod.id)}
onDragStart={() => setDraggedId(mod.id)}
onDrop={(event) => handleDrop(mod.id, event)}
/>
);
})}
</div>
)}
</>
) : (
<>
<section className="mods-section">
<h3 className="mods-subheading">{t('mods.presets.heading')}</h3>
<p className="mods-hint">{t('mods.presets.description')}</p>
<form className="mods-preset-form" onSubmit={savePreset}>
<input
type="text"
className="input"
maxLength={80}
disabled={disabled}
placeholder={t('mods.presets.namePlaceholder')}
value={presetName}
onChange={(event) => setPresetName(event.target.value)}
/>
<button type="submit" className="button button-primary" disabled={disabled || !presetName.trim()}>
{t('mods.presets.saveCurrent')}
</button>
<button type="button" className="button" disabled={disabled} onClick={importPreset}>
{t('mods.presets.import')}
</button>
</form>
{state.presets.length === 0 ? (
<p className="mods-hint">{t('mods.presets.empty')}</p>
) : (
<div className="mods-preset-list">
{state.presets.map((preset) => {
const active = state.activePresetId === preset.id;
const count = Object.values(preset.enabled).filter(Boolean).length;
return (
<div key={preset.id} className={active ? 'mods-preset-item mods-preset-active' : 'mods-preset-item'}>
<div className="mods-preset-meta">
<div className="mods-preset-name">
{preset.name}
{active && <span className="mods-badge mods-badge-data">{t('mods.presets.activeTag')}</span>}
</div>
<div className="mods-preset-sub">
{t('mods.presets.summary', { count, total: preset.order.length })}
</div>
</div>
<div className="copy-list-actions">
<button
type="button"
className="button button-primary"
disabled={disabled}
onClick={() => runAction(
ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: preset.id }),
t('mods.presets.applied', { name: preset.name }),
)}
>
{t('mods.presets.apply')}
</button>
<button
type="button"
className="button"
disabled={disabled}
onClick={() => runAction(
ipcInvoke('mods:savePreset', { copyId: copy.id, name: preset.name, overwriteId: preset.id }),
t('mods.presets.updated', { name: preset.name }),
)}
>
{t('mods.presets.overwrite')}
</button>
<button type="button" className="button" disabled={busy} onClick={() => exportPreset(preset.id)}>
{t('mods.presets.export')}
</button>
<button
type="button"
className="button"
disabled={disabled}
onClick={() => runAction(ipcInvoke('mods:deletePreset', { copyId: copy.id, presetId: preset.id }))}
>
{t('mods.presets.delete')}
</button>
</div>
</div>
);
})}
</div>
)}
</section>
<section className="mods-section">
<h3 className="mods-subheading">{t('mods.repo.heading')}</h3>
<p className="mods-hint">{t('mods.repo.description')}</p>
<Row
label={t('mods.repo.pathLabel')}
hint={state.isCustomModsDir ? t('mods.repo.customNote') : t('mods.repo.defaultNote')}
>
<code className="mods-path">{state.modsDir}</code>
</Row>
<div className="copy-list-actions" style={{ marginTop: 12 }}>
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
{t('mods.openFolder')}
</button>
<button type="button" className="button" disabled={disabled} onClick={pickCustomFolder}>
{t('mods.repo.changeFolder')}
</button>
{state.isCustomModsDir && (
<button type="button" className="button" disabled={disabled} onClick={resetFolder}>
{t('mods.repo.resetDefault')}
</button>
)}
</div>
</section>
</>
)}
</Sheet>
);
}
interface ModCardProps {
readonly mod: ModListItem;
readonly index: number;
readonly total: number;
readonly enabled: boolean;
readonly expanded: boolean;
readonly disabled: boolean;
readonly canDrag: boolean;
readonly language: string;
readonly issues: readonly ModIssueView[];
readonly onToggle: (next: boolean) => void;
readonly onMove: (delta: -1 | 1) => void;
readonly onToggleExpand: () => void;
readonly onDragStart: () => void;
readonly onDrop: (event: DragEvent<HTMLDivElement>) => void;
}
function ModCard({
mod,
index,
total,
enabled,
expanded,
disabled,
canDrag,
language,
issues,
onToggle,
onMove,
onToggleExpand,
onDragStart,
onDrop,
}: ModCardProps) {
const { t } = useTranslation();
const displayName = localized(mod.name, language) || mod.id;
const description = localized(mod.description, language);
const errorCount = issues.filter((i) => i.severity === 'error').length;
const warnCount = issues.filter((i) => i.severity === 'warning').length;
return (
<div
className={`mods-card${enabled ? ' mods-card-enabled' : ''}`}
draggable={canDrag}
onDragStart={onDragStart}
onDragOver={(event) => { if (canDrag) event.preventDefault(); }}
onDrop={onDrop}
>
<div className="mods-card-row">
<span className="mods-order-num" title={t('mods.loadOrderHint')}>#{index + 1}</span>
<input
type="checkbox"
className="mods-checkbox"
checked={enabled}
disabled={disabled}
aria-label={displayName}
onChange={(event) => onToggle(event.target.checked)}
/>
<div className="mods-card-main" onClick={onToggleExpand}>
<div className="mods-card-title">
<span className="mods-name">{displayName}</span>
<span className="mods-version">v{mod.version}</span>
<span className="mods-author">· {mod.author}</span>
<div className="mods-badges">
{mod.badges.map((badge) => (
<span key={badge} className={`mods-badge mods-badge-${badge}`}>
{t(`mods.badges.${badge}`)}
</span>
))}
{errorCount > 0 && <span className="mods-badge mods-badge-error">{t('mods.errorCount', { count: errorCount })}</span>}
{warnCount > 0 && <span className="mods-badge mods-badge-warn">{t('mods.warnCount', { count: warnCount })}</span>}
</div>
</div>
{description && <div className="mods-card-desc">{description}</div>}
</div>
<div className="mods-card-actions">
<button
type="button"
className="button mods-move-btn"
disabled={disabled || index <= 0}
title={t('mods.moveUp')}
onClick={() => onMove(-1)}
>
↑
</button>
<button
type="button"
className="button mods-move-btn"
disabled={disabled || index < 0 || index >= total - 1}
title={t('mods.moveDown')}
onClick={() => onMove(1)}
>
↓
</button>
<button type="button" className="button" onClick={onToggleExpand}>
{expanded ? t('mods.hideDetails') : t('mods.showDetails')}
</button>
</div>
</div>
{expanded && (
<div className="mods-card-details">
<div className="mods-detail-grid">
<div><span>ID:</span> <code>{mod.id}</code></div>
<div><span>API:</span> <code>{mod.apiVersion}</code></div>
<div><span>{t('mods.details.folder')}:</span> <code>{mod.folderName}</code></div>
{mod.gameVersions.length > 0 && (
<div><span>{t('mods.details.gameVersions')}:</span> <code>{mod.gameVersions.join(', ')}</code></div>
)}
{mod.requires.length > 0 && (
<div><span>{t('mods.details.requires')}:</span> <code>{mod.requires.join(', ')}</code></div>
)}
{mod.conflicts.length > 0 && (
<div><span>{t('mods.details.conflicts')}:</span> <code>{mod.conflicts.join(', ')}</code></div>
)}
</div>
<div className="mods-detail-summary">
{mod.serverTuningFiles.length > 0 && (
<span>{t('mods.details.tuning', { count: mod.serverTuningFiles.length })}</span>
)}
{mod.hasServerScript && <span>{t('mods.details.serverScript')}</span>}
{mod.packOperations.length > 0 && (
<span>{t('mods.details.packOps', { count: mod.packOperations.length })}</span>
)}
{mod.hasClientAddon && (
<span>{t('mods.details.addon', { count: mod.addonFileCount })}</span>
)}
{mod.guiPatchCount > 0 && (
<span>{t('mods.details.guiPatches', { count: mod.guiPatchCount })}</span>
)}
{mod.exePatchCount > 0 && (
<span>{t('mods.details.exePatches', { count: mod.exePatchCount })}</span>
)}
{mod.clientFileCount > 0 && (
<span>{t('mods.details.companionFiles', { count: mod.clientFileCount })}</span>
)}
{mod.hasConfigBlkPatch && <span>{t('mods.details.configBlk')}</span>}
</div>
</div>
)}
</div>
);
}
@@ -1,9 +1,8 @@
/**
* The window's pages and the sections of those that have a section list in the side panel.
* Pages for later features (saves, tuning) join this list when they are built.
*/
export const PAGES = ['home', 'saves', 'tuning', 'copies', 'settings', 'about'] as const;
export const PAGES = ['home', 'saves', 'tuning', 'mods', 'copies', 'settings', 'about'] as const;
export type PageId = (typeof PAGES)[number];
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'official', 'backup'] as const;
@@ -12,6 +11,9 @@ export type SaveSection = (typeof SAVE_SECTIONS)[number];
export const TUNING_SECTIONS = ['rewards', 'battle', 'newProfile', 'research'] as const;
export type TuningSection = (typeof TUNING_SECTIONS)[number];
export const MODS_SECTIONS = ['list', 'presets'] as const;
export type ModsSection = (typeof MODS_SECTIONS)[number];
export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const;
export type CopySection = (typeof COPY_SECTIONS)[number];
@@ -23,16 +25,25 @@ export interface Route {
readonly copies: CopySection;
readonly saves: SaveSection;
readonly tuning: TuningSection;
readonly mods: ModsSection;
readonly settings: SettingsSection;
}
export const START_ROUTE: Route = { page: 'home', saves: 'list', tuning: 'rewards', copies: 'list', settings: 'general' };
export const START_ROUTE: Route = {
page: 'home',
saves: 'list',
tuning: 'rewards',
mods: 'list',
copies: 'list',
settings: 'general',
};
/** Where a link points: a page, and for pages with sections, which one. */
export type Destination =
| { readonly page: 'home' | 'about' }
| { readonly page: 'saves'; readonly section?: SaveSection }
| { readonly page: 'tuning'; readonly section?: TuningSection }
| { readonly page: 'mods'; readonly section?: ModsSection }
| { readonly page: 'copies'; readonly section?: CopySection }
| { readonly page: 'settings'; readonly section?: SettingsSection };
@@ -42,6 +53,8 @@ export function navigate(route: Route, to: Destination): Route {
return { ...route, page: 'saves', saves: to.section ?? route.saves };
case 'tuning':
return { ...route, page: 'tuning', tuning: to.section ?? route.tuning };
case 'mods':
return { ...route, page: 'mods', mods: to.section ?? route.mods };
case 'copies':
return { ...route, page: 'copies', copies: to.section ?? route.copies };
case 'settings':
@@ -435,3 +435,397 @@
.about-card .notice .button {
margin-top: 8px;
}
/* ===== Mods ===== */
.mods-aside {
display: inline-flex;
align-items: center;
gap: 10px;
}
.mods-exp-chip {
position: relative;
display: inline-flex;
align-items: center;
gap: 5px;
padding: 2px 7px;
font-size: 11.5px;
line-height: 1.3;
color: rgba(255, 227, 163, 0.9);
background: rgba(214, 158, 46, 0.14);
border: 1px solid rgba(214, 158, 46, 0.38);
border-radius: var(--radius);
cursor: help;
user-select: none;
}
.mods-exp-chip:hover,
.mods-exp-chip:focus-visible {
background: rgba(214, 158, 46, 0.22);
border-color: rgba(214, 158, 46, 0.6);
outline: none;
}
.mods-exp-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
font-size: 10px;
font-weight: 700;
font-style: normal;
border-radius: 50%;
border: 1px solid rgba(255, 227, 163, 0.55);
}
.mods-exp-popover {
position: absolute;
top: calc(100% + 8px);
right: 0;
z-index: 40;
width: 340px;
max-width: min(340px, 70vw);
display: flex;
flex-direction: column;
gap: 4px;
padding: 10px 12px;
font-size: 12px;
line-height: 1.5;
text-align: left;
white-space: normal;
color: rgba(255, 244, 218, 0.94);
background: rgba(16, 20, 24, 0.97);
border: 1px solid rgba(214, 158, 46, 0.5);
border-radius: var(--radius);
box-shadow: 0 10px 26px rgba(0, 0, 0, 0.55);
opacity: 0;
visibility: hidden;
pointer-events: none;
transform: translateY(-2px);
transition: opacity 140ms ease, transform 140ms ease, visibility 140ms ease;
}
.mods-exp-chip:hover .mods-exp-popover,
.mods-exp-chip:focus-visible .mods-exp-popover {
opacity: 1;
visibility: visible;
transform: translateY(0);
}
.mods-banner {
display: flex;
flex-direction: column;
gap: 3px;
padding: 10px 12px;
margin-bottom: 12px;
font-size: 12.5px;
line-height: 1.5;
border: 1px solid var(--line);
border-radius: var(--radius);
}
.mods-banner-warn {
background: rgba(206, 65, 55, 0.16);
border-color: rgba(206, 65, 55, 0.5);
color: #ffd7d4;
}
.mods-banner-ok {
background: rgba(68, 170, 102, 0.16);
border-color: rgba(68, 170, 102, 0.5);
color: #d7ffe4;
}
.mods-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 12px;
}
.mods-search {
flex: 1 1 180px;
min-width: 140px;
}
.mods-preset-select {
max-width: 210px;
}
.mods-issues-box {
padding: 10px 12px;
margin-bottom: 12px;
font-size: 12.5px;
border-radius: var(--radius);
border: 1px solid var(--line);
}
.mods-issues-error {
background: rgba(206, 65, 55, 0.15);
border-color: rgba(206, 65, 55, 0.55);
}
.mods-issues-warn {
background: rgba(214, 158, 46, 0.13);
border-color: rgba(214, 158, 46, 0.45);
}
.mods-issues-title {
font-weight: 600;
margin-bottom: 6px;
}
.mods-issues-box ul {
margin: 0;
padding-left: 18px;
display: flex;
flex-direction: column;
gap: 4px;
}
.mods-issue-tag {
display: inline-block;
margin-right: 6px;
padding: 1px 5px;
font-size: 11px;
border-radius: 2px;
background: rgba(255, 255, 255, 0.12);
}
.mods-empty {
padding: 20px 14px;
text-align: center;
border: 1px dashed var(--line);
border-radius: var(--radius);
}
.mods-hint {
font-size: 12.5px;
color: var(--text-dim);
line-height: 1.5;
margin: 6px 0 12px;
}
.mods-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.mods-card {
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(12, 16, 19, 0.62);
transition: border-color 120ms ease;
}
.mods-card-enabled {
border-left: 3px solid var(--red);
background: rgba(18, 24, 29, 0.78);
}
.mods-card-row {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 12px;
}
.mods-order-num {
min-width: 26px;
font-size: 12px;
color: var(--text-dim);
text-align: right;
cursor: grab;
}
.mods-checkbox {
width: 16px;
height: 16px;
flex: none;
cursor: pointer;
}
.mods-card-main {
flex: 1;
min-width: 0;
cursor: pointer;
}
.mods-card-title {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.mods-name {
font-weight: 600;
color: var(--white);
}
.mods-version,
.mods-author {
font-size: 12px;
color: var(--text-dim);
}
.mods-card-desc {
margin-top: 3px;
font-size: 12px;
color: var(--text-dim);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.mods-badges {
display: inline-flex;
flex-wrap: wrap;
gap: 4px;
}
.mods-badge {
padding: 1px 6px;
font-size: 11px;
border-radius: 2px;
border: 1px solid rgba(255, 255, 255, 0.16);
}
.mods-badge-data {
background: rgba(88, 166, 255, 0.16);
color: #b7d7ff;
}
.mods-badge-gui {
background: rgba(163, 113, 247, 0.18);
color: #dec8ff;
}
.mods-badge-script {
background: rgba(214, 158, 46, 0.22);
color: #ffe3a3;
}
.mods-badge-exe {
background: rgba(206, 65, 55, 0.28);
color: #ffc2be;
border-color: rgba(206, 65, 55, 0.55);
}
.mods-badge-error {
background: rgba(206, 65, 55, 0.35);
color: #ffd5d2;
}
.mods-badge-warn {
background: rgba(214, 158, 46, 0.25);
color: #ffe8b3;
}
.mods-card-actions {
display: flex;
align-items: center;
gap: 4px;
flex: none;
}
.mods-move-btn {
min-width: 28px;
padding: 4px 6px;
}
.mods-card-details {
padding: 10px 12px 12px 48px;
border-top: 1px solid var(--line);
font-size: 12px;
color: var(--text-dim);
}
.mods-detail-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 4px 12px;
margin-bottom: 8px;
}
.mods-detail-summary {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.mods-detail-summary span {
padding: 2px 7px;
border-radius: 2px;
background: rgba(255, 255, 255, 0.08);
color: rgba(255, 255, 255, 0.85);
}
.mods-section {
margin-bottom: 22px;
}
.mods-subheading {
margin: 0 0 4px;
font: 600 15px var(--font-display);
color: var(--white);
}
.mods-preset-form {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 10px 0 14px;
}
.mods-preset-form .input {
flex: 1 1 200px;
}
.mods-preset-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.mods-preset-item {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(12, 16, 19, 0.62);
}
.mods-preset-active {
border-left: 3px solid var(--red);
}
.mods-preset-meta {
min-width: 0;
}
.mods-preset-name {
display: flex;
align-items: center;
gap: 8px;
font-weight: 600;
color: var(--white);
}
.mods-preset-sub {
font-size: 12px;
color: var(--text-dim);
margin-top: 2px;
}
.mods-path {
font-size: 12px;
word-break: break-all;
}
+5
View File
@@ -24,6 +24,11 @@ export const APP_ERROR_CODES = [
'diagnostics_export_failed',
'copy_not_found',
'tuning_invalid',
'mods_read_only',
'mods_write_failed',
'mods_preset_invalid',
'mods_blocking_issues',
'mods_folder_invalid',
'save_not_found',
'save_archive_invalid',
'save_official_invalid',
+2
View File
@@ -16,6 +16,8 @@ export const IPC_CHANNEL_PREFIXES = [
'copies:',
/** Settings shared by the saves of a game copy. */
'tuning:',
/** Additive mods repository, per-copy ordering/toggles, and presets. */
'mods:',
/** Local account and save management. */
'saves:',
/** Starting and stopping the active copy. */
+49
View File
@@ -17,6 +17,7 @@ import {
} from '../schemas/install.ts';
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
import { ModsStateViewSchema } from '../schemas/mods.ts';
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts';
import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
@@ -262,6 +263,54 @@ export const ipcContract = {
input: z.object({ copyId: CopyIdSchema, patch: TuningPatchSchema }),
output: TuningViewSchema,
},
'mods:getState': {
input: z.object({ copyId: CopyIdSchema }),
output: ModsStateViewSchema,
},
'mods:setEnabled': {
input: z.object({ copyId: CopyIdSchema, modId: z.string().min(1), enabled: z.boolean() }),
output: ModsStateViewSchema,
},
'mods:setOrder': {
input: z.object({ copyId: CopyIdSchema, order: z.array(z.string()) }),
output: ModsStateViewSchema,
},
'mods:autoSort': {
input: z.object({ copyId: CopyIdSchema }),
output: ModsStateViewSchema,
},
'mods:savePreset': {
input: z.object({ copyId: CopyIdSchema, name: z.string().trim().min(1).max(80), overwriteId: z.string().min(1).optional() }),
output: ModsStateViewSchema,
},
'mods:applyPreset': {
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
output: ModsStateViewSchema,
},
'mods:deletePreset': {
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
output: ModsStateViewSchema,
},
'mods:exportPreset': {
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
output: z.object({ path: z.string().nullable() }),
},
'mods:importPreset': {
input: z.object({ copyId: CopyIdSchema }),
output: z.object({ imported: z.boolean(), state: ModsStateViewSchema }),
},
'mods:openFolder': {
input: z.void(),
output: z.void(),
},
'mods:openDocs': {
input: z.object({ language: z.string().optional() }).optional(),
output: z.void(),
},
'mods:setFolder': {
input: z.object({ copyId: CopyIdSchema, path: z.string().min(1).nullable() }),
output: ModsStateViewSchema,
},
'launch:getState': {
input: z.void(),
output: LaunchStateSchema,
+87
View File
@@ -0,0 +1,87 @@
import { z } from 'zod';
export const ModRiskBadgeSchema = z.enum(['data', 'gui', 'script', 'exe']);
export const ModIssueSeveritySchema = z.enum(['error', 'warning', 'info']);
export const LocalizedTextSchema = z.union([z.string(), z.record(z.string(), z.string())]);
export const ModPackOperationSchema = z.object({
pack: z.string(),
targetPath: z.string(),
action: z.enum(['blk-patch', 'csv-patch', 'file']),
sourceRelativePath: z.string(),
});
export const ModListItemSchema = z.object({
id: z.string(),
folderName: z.string(),
rootDir: z.string(),
name: LocalizedTextSchema,
description: LocalizedTextSchema.optional(),
version: z.string(),
author: z.string(),
apiVersion: z.string(),
gameVersions: z.array(z.string()),
requires: z.array(z.string()),
conflicts: z.array(z.string()),
loadAfter: z.array(z.string()),
loadBefore: z.array(z.string()),
badges: z.array(ModRiskBadgeSchema),
hasServerScript: z.boolean(),
serverTuningFiles: z.array(z.string()),
packOperations: z.array(ModPackOperationSchema),
guiPatchCount: z.number().int().nonnegative(),
exePatchCount: z.number().int().nonnegative(),
hasClientAddon: z.boolean(),
addonFileCount: z.number().int().nonnegative(),
clientFileCount: z.number().int().nonnegative(),
hasConfigBlkPatch: z.boolean(),
});
export const ModDiscoveryErrorSchema = z.object({
folderName: z.string(),
rootDir: z.string(),
reason: z.string(),
});
export const ModIssueSchema = z.object({
severity: ModIssueSeveritySchema,
kind: z.string(),
modId: z.string(),
otherModId: z.string().optional(),
detail: z.string(),
});
export const ModPresetSchema = z.object({
id: z.string().min(1),
name: z.string().min(1).max(80),
order: z.array(z.string()),
enabled: z.record(z.string(), z.boolean()),
updatedAt: z.string(),
});
export const ModsStateViewSchema = z.object({
modsDir: z.string(),
defaultModsDir: z.string(),
isCustomModsDir: z.boolean(),
apiVersion: z.string(),
mods: z.array(ModListItemSchema),
discoveryErrors: z.array(ModDiscoveryErrorSchema),
order: z.array(z.string()),
enabled: z.record(z.string(), z.boolean()),
activePresetId: z.string().nullable(),
presets: z.array(ModPresetSchema),
issues: z.array(ModIssueSchema),
hasBlockingErrors: z.boolean(),
});
export const ModPresetTransferSchema = z.object({
format: z.literal(1),
name: z.string().min(1).max(80),
order: z.array(z.string()),
enabled: z.record(z.string(), z.boolean()),
});
export type ModListItem = z.output<typeof ModListItemSchema>;
export type ModPresetView = z.output<typeof ModPresetSchema>;
export type ModIssueView = z.output<typeof ModIssueSchema>;
export type ModsStateView = z.output<typeof ModsStateViewSchema>;
@@ -37,6 +37,8 @@ export const SettingsSchema = z.object({
developerMode: z.boolean().default(true),
labStockPath: LabPathSchema.default(null),
labDataPath: LabPathSchema.default(null),
/** Custom global mods repository directory; null uses `<userData>/mods`. */
modsFolder: LabPathSchema.default(null),
});
export type Settings = z.output<typeof SettingsSchema>;
@@ -60,6 +62,7 @@ export const SettingsPatchSchema = z.object({
developerMode: z.boolean().optional(),
labStockPath: LabPathSchema.optional(),
labDataPath: LabPathSchema.optional(),
modsFolder: LabPathSchema.optional(),
});
export type SettingsPatch = z.output<typeof SettingsPatchSchema>;
+1
View File
@@ -9,6 +9,7 @@
"dependencies": {
"@wto/blk": "*",
"@wto/jsonc": "*",
"@wto/mods": "*",
"@wto/vromfs": "*"
}
}
+27 -2
View File
@@ -86,6 +86,16 @@ export type MatchmakeOutcome =
| { readonly ok: true; readonly launch: BattleLaunchPlan }
| { readonly ok: false; readonly error: string };
export type MissionPoolFilter = (ctx: {
readonly userId: string;
readonly modeId: number;
readonly modeName: string;
readonly economicName: string;
readonly minMrank: number;
readonly maxMrank: number;
readonly missions: readonly MissionHeader[];
}) => readonly MissionHeader[];
export class BattleMatchmaker {
readonly #gameModes: GameModes;
readonly #vehicles: readonly CatalogueVehicle[];
@@ -94,6 +104,7 @@ export class BattleMatchmaker {
readonly #tuning: BattleTuning;
readonly #spawnRules: BattleSpawnRulesData;
readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>;
readonly #filterMissions: MissionPoolFilter | undefined;
constructor(
gameModes: GameModes,
@@ -102,6 +113,7 @@ export class BattleMatchmaker {
tuning: BattleTuning,
spawnRules: BattleSpawnRulesData,
aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
filterMissions?: MissionPoolFilter,
) {
this.#gameModes = gameModes;
this.#vehicles = vehicles;
@@ -110,6 +122,7 @@ export class BattleMatchmaker {
this.#tuning = tuning;
this.#spawnRules = spawnRules;
this.#aircraftLoadouts = aircraftLoadouts;
this.#filterMissions = filterMissions;
}
enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
@@ -133,8 +146,20 @@ export class BattleMatchmaker {
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity;
const maxMrank = Math.max(minMrank, playerMrank, Math.min(roomCeiling, playerMrank + this.#tuning.brSpreadMrank));
const missions = twoSidedMissionsOf(chosenMode, maxMrank);
if (missions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
const rawMissions = twoSidedMissionsOf(chosenMode, maxMrank);
if (rawMissions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
const filteredMissions = this.#filterMissions
? this.#filterMissions({
userId: input.userId,
modeId: declaration.gameModeId,
modeName: declaration.name,
economicName: declaration.economicName,
minMrank,
maxMrank,
missions: rawMissions,
})
: rawMissions;
const missions = filteredMissions.length > 0 ? filteredMissions : rawMissions;
const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions);
const coalitions = selectBattleCoalitions({
vehicles: this.#vehicles,
@@ -3,6 +3,7 @@
* settles them into the player's save (battle-settlement.ts) and answers the updated profile,
* whose new `EULT_SESSION_RESULT` log carries the debriefing table.
*/
import type { BattleSettlementContext } from '@wto/mods';
import type { AccountStore } from '../../accounts/account-store.ts';
import { parseBattleReport } from '../../battle/battle-report.ts';
import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
@@ -28,6 +29,7 @@ export interface BattleActionDependencies {
readonly streaks: BattleStreaks;
/** Units whose lives and events are not settled (battle-support-planes.ts). */
readonly supportPlanes: ReadonlySet<string>;
readonly onAfterSettle?: (ctx: BattleSettlementContext) => void;
}
export interface FinishBattleContext {
@@ -62,6 +64,11 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio
}
const updated = ctx.profiles.update(account.userId, (profile) => {
settleBattle(profile, report, session, settlementDeps);
battle.onAfterSettle?.({
userId: account.userId,
roomId: session.sessionId,
summary: { profile, report, session },
});
});
battle.sessions.markSettled(session.sessionId);
return { kind: 'data', blk: clientProfile(updated, account) };
+53 -2
View File
@@ -13,6 +13,8 @@
* default lets the client continue and reveal what it asks for next.
*/
import { emptyBlock } from '@wto/blk';
import type { ModCharRequest, ModCharResponse } from '@wto/mods';
import type { ServerModRuntime } from '../mods/server-mod-runtime.ts';
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
import type { CharActionHandler } from './char-action.ts';
import { toResponse, type CharAnswer } from './char-answers.ts';
@@ -23,17 +25,26 @@ const CHAR_HOST = /^char-[a-z0-9-]+\.warthunder\.com$/;
export class CharService implements Service {
readonly name = 'char';
readonly #actions: ReadonlyMap<string, CharActionHandler>;
readonly #modRuntime: ServerModRuntime | undefined;
constructor(actions: ReadonlyMap<string, CharActionHandler>) {
constructor(actions: ReadonlyMap<string, CharActionHandler>, modRuntime?: ServerModRuntime) {
this.#actions = actions;
this.#modRuntime = modRuntime;
}
accepts(request: ServiceRequest): boolean {
return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost);
}
handle(request: ServiceRequest): ServiceResponse {
handle(request: ServiceRequest): ServiceResponse | Promise<ServiceResponse> {
const action = header(request, 'action') ?? '(no action header)';
if (this.#modRuntime?.hasCharOverride(action)) {
return this.#handleWithModOverride(action, request);
}
return this.#handleCore(action, request);
}
#handleCore(action: string, request: ServiceRequest): ServiceResponse {
const payload = decodeRequestPayload(request.body);
const handler = this.#actions.get(action);
const answer: CharAnswer = handler
@@ -56,6 +67,46 @@ export class CharService implements Service {
},
};
}
async #handleWithModOverride(action: string, request: ServiceRequest): Promise<ServiceResponse> {
const headers: Record<string, string | undefined> = {};
for (const [key, value] of Object.entries(request.headers)) {
headers[key] = Array.isArray(value) ? value[0] : value;
}
const query: Record<string, string> = {};
for (const [key, value] of request.query.entries()) query[key] = value;
const modReq: ModCharRequest = {
action,
userId: header(request, 'uidhint') ?? '',
headers,
body: request.body,
query,
};
const result = await this.#modRuntime!.dispatchCharOverride(action, modReq, async (nextReq): Promise<ModCharResponse> => {
const forwarded: ServiceRequest = { ...request, body: nextReq.body };
const coreResp = this.#handleCore(nextReq.action, forwarded);
return {
status: coreResp.status,
...(coreResp.headers ? { headers: coreResp.headers } : {}),
body: coreResp.body ?? '',
};
});
const responseHeaders: Record<string, string> = { ...(result.headers ?? {}) };
if (result.contentType && !responseHeaders['content-type'] && !responseHeaders['Content-Type']) {
responseHeaders['content-type'] = result.contentType;
}
return {
status: result.status ?? 200,
headers: responseHeaders,
body: result.body,
logNotes: {
summary: `${action} [mod handler] -> ${result.status ?? 200}`,
},
};
}
}
function header(request: ServiceRequest, name: string): string | undefined {
@@ -11,6 +11,7 @@
* "strike": time:f the local player's nuclear bomb exploded
* answer: { streaks: [{ id:s stage:i (-1 = single-stage) stageParam:i wp:i exp:i }] }
*/
import type { BattleLiveFactContext } from '@wto/mods';
import type { BattleLiveLogs } from '../battle/battle-live-log.ts';
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
import type { BattleStreaks } from '../battle/battle-streaks.ts';
@@ -23,6 +24,7 @@ export interface BattleLiveDependencies {
readonly streaks: BattleStreaks;
/** Units whose lives and events earn no awards (battle-support-planes.ts). */
readonly supportPlanes: ReadonlySet<string>;
readonly onLiveFact?: (ctx: BattleLiveFactContext) => void;
}
export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string, MatchingRequestHandler]> {
@@ -34,6 +36,11 @@ export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string,
if (!session || session.settled) return { streaks: [] };
const log = deps.liveLogs.of(session.sessionId);
if (!recordFact(log, p)) return { streaks: [] };
deps.onLiveFact?.({
userId: userId!,
roomId: session.sessionId,
fact: p as Record<string, unknown>,
});
const awarded = deps.streaks.evaluate({
...withoutSupportPlanes({ events: log.events, lives: log.lives }, deps.supportPlanes),
feed: log.feed,
@@ -5,6 +5,7 @@
* - `match.leave_queue` (scripts/queue/queuestate.nut:28)
* - `match.check_reconnect`
*/
import type { BattleMatchmakeContext } from '@wto/mods';
import { MAX_BATTLE_CREW_SLOTS } from '../battle/battle-extra-slots.ts';
import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.ts';
import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts';
@@ -24,6 +25,7 @@ export interface BattleQueueDependencies {
readonly sessions: BattleSessionStore;
readonly economy: BattleEconomy;
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void;
readonly onBeforeMatchmake?: (ctx: BattleMatchmakeContext) => void;
}
export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> {
@@ -85,6 +87,11 @@ function handleEnqueue(
const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country);
const idInCountry = playerEntry.selectedSlot;
const selectedSlotVehicle = idInCountry === undefined ? undefined : crewSlotVehicleOfCountry(profile, playerEntry.country, idInCountry);
deps.onBeforeMatchmake?.({
userId,
eventName: modes[0]!.declaration.name,
request: params as Record<string, unknown>,
});
const outcome = deps.matchmaker.enqueue({
userId,
mode: modes[0]!,
+82
View File
@@ -0,0 +1,82 @@
/**
* HTTP router service that exposes mod-registered routes under `/mods/<modId>/...`
* so mods can provide custom APIs or embedded-browser pages without touching core routes.
*/
import type { ModHttpHandler, ModHttpRequest } from '@wto/mods';
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
export interface RegisteredModHttpRoute {
readonly modId: string;
/** Full normalized path prefix or exact path under `/mods/<modId>/...`. */
readonly pattern: string;
readonly isWildcard: boolean;
readonly prefix: string;
readonly handler: ModHttpHandler;
}
export class ModHttpService implements Service {
readonly name = 'mods-http';
readonly #routes: readonly RegisteredModHttpRoute[];
constructor(routes: readonly RegisteredModHttpRoute[]) {
this.#routes = routes;
}
accepts(request: ServiceRequest): boolean {
if (request.originalHost !== undefined) return false;
return this.#match(request.path) !== undefined;
}
async handle(request: ServiceRequest): Promise<ServiceResponse> {
const matched = this.#match(request.path);
if (!matched) {
return { status: 404, body: 'mod route not found' };
}
const headers: Record<string, string | undefined> = {};
for (const [key, value] of Object.entries(request.headers)) {
headers[key] = Array.isArray(value) ? value[0] : value;
}
const query: Record<string, string> = {};
for (const [key, value] of request.query.entries()) query[key] = value;
const modReq: ModHttpRequest = {
method: request.method,
path: request.path,
query,
headers,
body: request.body,
};
const answer = await matched.handler(modReq);
const responseHeaders: Record<string, string> = { ...(answer.headers ?? {}) };
if (answer.contentType && !responseHeaders['content-type'] && !responseHeaders['Content-Type']) {
responseHeaders['content-type'] = answer.contentType;
}
return {
status: answer.status ?? 200,
headers: responseHeaders,
body: answer.body,
logNotes: { summary: `mod:${matched.modId} ${request.method} ${request.path}` },
};
}
#match(path: string): RegisteredModHttpRoute | undefined {
for (const route of this.#routes) {
if (route.isWildcard) {
if (path.startsWith(route.prefix)) return route;
} else if (path === route.pattern) {
return route;
}
}
return undefined;
}
}
export function buildModHttpRoute(modId: string, subPath: string, handler: ModHttpHandler): RegisteredModHttpRoute {
const cleaned = subPath.startsWith('/') ? subPath : `/${subPath}`;
const full = `/mods/${modId}${cleaned === '/' ? '' : cleaned}`;
if (full.endsWith('/*')) {
const prefix = full.slice(0, -1); // keeps trailing '/'
return { modId, pattern: full, isWildcard: true, prefix, handler };
}
return { modId, pattern: full, isWildcard: false, prefix: full, handler };
}
+55
View File
@@ -0,0 +1,55 @@
/**
* Isolated JSON storage for server mods:
* - per-player files under `<dataFolder>/saves/<userId>/mods/<safeModId>.json`
* - shared mod state under `<dataFolder>/mods-data/<safeModId>.json`
*
* Keeping mod state outside `profile.blk` guarantees uninstalling a mod never corrupts stock saves.
*/
import { existsSync, readFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import type { ModPlayerStorage, ModStorageApi } from '@wto/mods';
import { writeFileAtomic } from '../storage/atomic-file.ts';
export function createModStorage(dataFolder: string, modId: string): ModStorageApi {
const safeMod = sanitizeSegment(modId);
return {
forPlayer(userId: string): ModPlayerStorage {
const safeUser = sanitizeSegment(userId);
const filePath = join(dataFolder, 'saves', safeUser, 'mods', `${safeMod}.json`);
return createJsonFileStorage(filePath);
},
shared(): ModPlayerStorage {
const filePath = join(dataFolder, 'mods-data', `${safeMod}.json`);
return createJsonFileStorage(filePath);
},
};
}
function createJsonFileStorage(filePath: string): ModPlayerStorage {
return {
read<T = unknown>(): T | undefined {
if (!existsSync(filePath)) return undefined;
try {
return JSON.parse(readFileSync(filePath, 'utf8')) as T;
} catch {
return undefined;
}
},
write(value: unknown): void {
writeFileAtomic(filePath, JSON.stringify(value, null, 2));
},
remove(): void {
try {
rmSync(filePath, { force: true });
} catch { /* ignore */ }
},
};
}
function sanitizeSegment(raw: string): string {
const cleaned = raw.replace(/[^A-Za-z0-9._-]/g, '_');
if (!cleaned || cleaned === '.' || cleaned === '..') {
throw new Error(`invalid storage path segment "${raw}"`);
}
return cleaned;
}
+362
View File
@@ -0,0 +1,362 @@
/**
* Experimental server-side JS/TS mod runtime.
*
* Loads each enabled mod's server script entry (`.ts`, `.mjs`, or `.js` via Node 24's built-in
* TypeScript stripping and ESM dynamic import), injects an isolated `WtoServerModContext`, and
* coordinates lifecycle hooks, profile/battle hooks, char/matching wrappers, and `/mods/<id>/*`
* HTTP routes.
*/
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import type { BlkBlock } from '@wto/blk';
import {
MOD_API_VERSION,
type BattleFilterMissionsContext,
type BattleLiveFactContext,
type BattleMatchmakeContext,
type BattleMissionCandidate,
type BattleSettlementContext,
type DiscoveredMod,
type ModCharHandler,
type ModCharRequest,
type ModCharResponse,
type ModCharWrapper,
type ModHttpHandler,
type ModMatchingHandler,
type ModMatchingRequest,
type ModMatchingWrapper,
type ServerModCataloguesView,
type ServerModDatasetsView,
type WtoServerMod,
type WtoServerModContext,
} from '@wto/mods';
import type { MatchingRequestHandler, MatchingRequestTable } from '../matching/matching-requests.ts';
import { buildModHttpRoute, ModHttpService, type RegisteredModHttpRoute } from './mod-http-service.ts';
import { createModStorage } from './mod-storage.ts';
interface RuntimeInitOptions {
readonly mods: readonly DiscoveredMod[];
readonly gameFolder: string;
readonly dataFolder: string;
readonly port: number;
readonly report: (line: string) => void;
}
interface ScopedHandler<T> {
readonly modId: string;
readonly fn: T;
}
export class ServerModRuntime {
readonly #report: (line: string) => void;
readonly #loadedModIds: string[] = [];
readonly #onDatasetsLoaded: ScopedHandler<(datasets: ServerModDatasetsView) => void | Promise<void>>[] = [];
readonly #onCataloguesReady: ScopedHandler<(catalogues: ServerModCataloguesView) => void | Promise<void>>[] = [];
readonly #onServerListening: ScopedHandler<(info: { readonly port: number }) => void | Promise<void>>[] = [];
readonly #onServerClosing: ScopedHandler<() => void | Promise<void>>[] = [];
readonly #onProfileRefresh: ScopedHandler<(profile: BlkBlock, userId: string) => void>[] = [];
readonly #onBeforeMatchmake: ScopedHandler<(ctx: BattleMatchmakeContext) => void>[] = [];
readonly #onFilterMissions: ScopedHandler<(ctx: BattleFilterMissionsContext) => readonly BattleMissionCandidate[] | void>[] = [];
readonly #onLiveFact: ScopedHandler<(ctx: BattleLiveFactContext) => void>[] = [];
readonly #onAfterSettle: ScopedHandler<(ctx: BattleSettlementContext) => void>[] = [];
readonly #charHandlers = new Map<string, ScopedHandler<ModCharHandler>>();
readonly #charWrappers = new Map<string, ScopedHandler<ModCharWrapper>[]>();
readonly #matchingHandlers = new Map<string, ScopedHandler<ModMatchingHandler>>();
readonly #matchingWrappers = new Map<string, ScopedHandler<ModMatchingWrapper>[]>();
readonly #httpRoutes: RegisteredModHttpRoute[] = [];
private constructor(report: (line: string) => void) {
this.#report = report;
}
static async load(options: RuntimeInitOptions): Promise<ServerModRuntime> {
const runtime = new ServerModRuntime(options.report);
const scriptMods = options.mods.filter((mod) => mod.content.serverEntry !== undefined);
if (scriptMods.length === 0) return runtime;
const cacheBust = Date.now();
for (const mod of scriptMods) {
const entryRel = mod.content.serverEntry!;
const entryAbs = join(mod.rootDir, ...entryRel.split('/'));
const modId = mod.manifest.id;
const url = `${pathToFileURL(entryAbs).href}?wto_mod=${cacheBust}`;
let loadedModule: Record<string, unknown>;
try {
loadedModule = (await import(url)) as Record<string, unknown>;
} catch (error) {
throw new Error(
`Failed to load server mod "${modId}" (${entryRel}): ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
);
}
const modExport = resolveModExport(loadedModule);
if (!modExport) {
throw new Error(
`Server mod "${modId}" (${entryRel}) must export default { setup(ctx) { ... } } or named setup(ctx)`,
);
}
const ctx = runtime.#createContext(mod, options);
try {
await modExport.setup(ctx);
} catch (error) {
throw new Error(
`Server mod "${modId}" setup() failed: ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
);
}
runtime.#loadedModIds.push(modId);
options.report(`mod ${modId}: server script loaded (${entryRel})`);
}
return runtime;
}
get loadedModIds(): readonly string[] {
return this.#loadedModIds;
}
async runDatasetsLoaded(view: ServerModDatasetsView): Promise<void> {
for (const { modId, fn } of this.#onDatasetsLoaded) {
try {
await fn(view);
} catch (error) {
throw new Error(`Server mod "${modId}" onDatasetsLoaded failed: ${formatError(error)}`);
}
}
}
async runCataloguesReady(view: ServerModCataloguesView): Promise<void> {
for (const { modId, fn } of this.#onCataloguesReady) {
try {
await fn(view);
} catch (error) {
throw new Error(`Server mod "${modId}" onCataloguesReady failed: ${formatError(error)}`);
}
}
}
async runServerListening(port: number): Promise<void> {
for (const { modId, fn } of this.#onServerListening) {
try {
await fn({ port });
} catch (error) {
this.#report(`[mod:${modId}] onServerListening error: ${formatError(error)}`);
}
}
}
async runServerClosing(): Promise<void> {
for (const { modId, fn } of [...this.#onServerClosing].reverse()) {
try {
await fn();
} catch (error) {
this.#report(`[mod:${modId}] onServerClosing error: ${formatError(error)}`);
}
}
}
runProfileRefresh(profile: BlkBlock, userId: string): void {
for (const { modId, fn } of this.#onProfileRefresh) {
try {
fn(profile, userId);
} catch (error) {
this.#report(`[mod:${modId}] profile.onRefresh error: ${formatError(error)}`);
}
}
}
runBattleBeforeMatchmake(ctx: BattleMatchmakeContext): void {
for (const { modId, fn } of this.#onBeforeMatchmake) {
try {
fn(ctx);
} catch (error) {
this.#report(`[mod:${modId}] battle.onBeforeMatchmake error: ${formatError(error)}`);
}
}
}
runBattleFilterMissions<T extends BattleMissionCandidate>(
ctx: Omit<BattleFilterMissionsContext, 'missions'> & { readonly missions: readonly T[] },
): readonly T[] {
if (this.#onFilterMissions.length === 0) return ctx.missions;
let current: readonly T[] = ctx.missions;
for (const { modId, fn } of this.#onFilterMissions) {
try {
const next = fn({ ...ctx, missions: current });
if (Array.isArray(next)) {
const allowed = new Set(next.map((item) => item.name));
const filtered = current.filter((item) => allowed.has(item.name));
if (filtered.length > 0) {
current = filtered;
} else {
this.#report(`[mod:${modId}] battle.onFilterMissions returned 0 matching candidates for ${ctx.modeName}; keeping previous pool`);
}
}
} catch (error) {
this.#report(`[mod:${modId}] battle.onFilterMissions error: ${formatError(error)}`);
}
}
return current;
}
runBattleLiveFact(ctx: BattleLiveFactContext): void {
for (const { modId, fn } of this.#onLiveFact) {
try {
fn(ctx);
} catch (error) {
this.#report(`[mod:${modId}] battle.onLiveFact error: ${formatError(error)}`);
}
}
}
runBattleAfterSettle(ctx: BattleSettlementContext): void {
for (const { modId, fn } of this.#onAfterSettle) {
try {
fn(ctx);
} catch (error) {
this.#report(`[mod:${modId}] battle.onAfterSettle error: ${formatError(error)}`);
}
}
}
hasCharOverride(action: string): boolean {
return this.#charHandlers.has(action) || this.#charWrappers.has(action);
}
async dispatchCharOverride(
action: string,
request: ModCharRequest,
baseDispatch: (req: ModCharRequest) => Promise<ModCharResponse>,
): Promise<ModCharResponse> {
const custom = this.#charHandlers.get(action);
const terminal: (req: ModCharRequest) => Promise<ModCharResponse> = custom
? async (req) => await custom.fn(req)
: baseDispatch;
const wrappers = this.#charWrappers.get(action);
if (!wrappers || wrappers.length === 0) return terminal(request);
let chain = terminal;
for (let i = wrappers.length - 1; i >= 0; i -= 1) {
const wrapper = wrappers[i]!.fn;
const next = chain;
chain = async (req) => await wrapper(req, next);
}
return chain(request);
}
applyMatchingRoutes(baseTable: MatchingRequestTable): MatchingRequestTable {
if (this.#matchingHandlers.size === 0 && this.#matchingWrappers.size === 0) {
return baseTable;
}
const merged = new Map<string, MatchingRequestHandler>(baseTable);
for (const [method, custom] of this.#matchingHandlers) {
merged.set(method, (request, session) => custom.fn({
method,
params: request.params,
userId: session.authenticatedUserId(),
}));
}
for (const [method, wrappers] of this.#matchingWrappers) {
const original = merged.get(method);
merged.set(method, (request, session) => {
const baseFn = (req: ModMatchingRequest): Record<string, unknown> => (
original ? original({ ...request, params: req.params }, session) : {}
);
let chain = baseFn;
for (let i = wrappers.length - 1; i >= 0; i -= 1) {
const wrap = wrappers[i]!.fn;
const next = chain;
chain = (req) => wrap(req, next);
}
return chain({
method,
params: request.params,
userId: session.authenticatedUserId(),
});
});
}
return merged;
}
httpService(): ModHttpService {
return new ModHttpService(this.#httpRoutes);
}
#createContext(mod: DiscoveredMod, options: RuntimeInitOptions): WtoServerModContext {
const modId = mod.manifest.id;
return {
apiVersion: MOD_API_VERSION,
manifest: mod.manifest,
modDir: mod.rootDir,
gameFolder: options.gameFolder,
dataFolder: options.dataFolder,
port: options.port,
logger: {
info: (message) => options.report(`[mod:${modId}] ${message}`),
warn: (message) => options.report(`[mod:${modId}] WARN: ${message}`),
error: (message) => options.report(`[mod:${modId}] ERROR: ${message}`),
},
storage: createModStorage(options.dataFolder, modId),
hooks: {
onDatasetsLoaded: (fn) => { this.#onDatasetsLoaded.push({ modId, fn }); },
onCataloguesReady: (fn) => { this.#onCataloguesReady.push({ modId, fn }); },
onServerListening: (fn) => { this.#onServerListening.push({ modId, fn }); },
onServerClosing: (fn) => { this.#onServerClosing.push({ modId, fn }); },
profile: {
onRefresh: (fn) => { this.#onProfileRefresh.push({ modId, fn }); },
},
battle: {
onBeforeMatchmake: (fn) => { this.#onBeforeMatchmake.push({ modId, fn }); },
onFilterMissions: (fn) => { this.#onFilterMissions.push({ modId, fn }); },
onLiveFact: (fn) => { this.#onLiveFact.push({ modId, fn }); },
onAfterSettle: (fn) => { this.#onAfterSettle.push({ modId, fn }); },
},
},
routes: {
char: {
register: (action, fn) => { this.#charHandlers.set(action, { modId, fn }); },
wrap: (action, fn) => {
const list = this.#charWrappers.get(action) ?? [];
list.push({ modId, fn });
this.#charWrappers.set(action, list);
},
},
matching: {
register: (method, fn) => { this.#matchingHandlers.set(method, { modId, fn }); },
wrap: (method, fn) => {
const list = this.#matchingWrappers.get(method) ?? [];
list.push({ modId, fn });
this.#matchingWrappers.set(method, list);
},
},
http: {
register: (subPath: string, handler: ModHttpHandler) => {
this.#httpRoutes.push(buildModHttpRoute(modId, subPath, handler));
},
},
},
};
}
}
function resolveModExport(mod: Record<string, unknown>): WtoServerMod | undefined {
const def = mod.default;
if (def && typeof def === 'object' && typeof (def as Record<string, unknown>).setup === 'function') {
return def as WtoServerMod;
}
if (typeof def === 'function') {
return { setup: def as WtoServerMod['setup'] };
}
if (typeof mod.setup === 'function') {
return { setup: mod.setup as WtoServerMod['setup'] };
}
return undefined;
}
function formatError(error: unknown): string {
return error instanceof Error ? error.stack ?? error.message : String(error);
}
+3
View File
@@ -5,6 +5,7 @@
* (with the modifications the mission support planes' presets need) and the free repair over time (repair/repair-over-time.ts) kept up to date and persisted on
* every read or write.
*/
import type { BlkBlock } from '@wto/blk';
import type { AccountStore } from './accounts/account-store.ts';
import type { ClanStore } from './clans/clan-store.ts';
import type { DatasetCache } from './game-data/datasets/dataset-cache.ts';
@@ -50,6 +51,7 @@ export function setUpProfiles(
tuning: Tuning,
sync?: ProfileSyncContext,
vehicles: readonly CatalogueVehicle[] = datasets.load(vehicleCatalogue),
onProfileRefresh?: (profile: BlkBlock, userId: string) => void,
): ProfileServices {
const startingContent: StartingContent = {
reserveVehicles: datasets.load(reserveVehicles),
@@ -70,6 +72,7 @@ export function setUpProfiles(
removeExpiredItems(profile, serverTimeNow());
repairVehiclesOverTime(profile, repair, serverTimeNow());
trimUserLogs(profile, tuning.limits.userLogsKept);
onProfileRefresh?.(profile, userId);
});
return { profiles, research, equipment, repair };
}
+158 -35
View File
@@ -1,8 +1,9 @@
/**
* Assemble the local server: data layer, save layer, rules,
* Assemble the local server: data layer, save layer, rules, experimental additive mod runtime,
* protocol-layer services, and the single loopback listening port.
*/
import type { Server } from 'node:net';
import type { DiscoveredMod, ServerModDatasetsView } from '@wto/mods';
import { AccountStore } from './accounts/account-store.ts';
import { RegistrationService } from './accounts/registration-service.ts';
import { BattleEconomy } from './battle/battle-economy.ts';
@@ -16,7 +17,7 @@ import { CloudSettingsStore } from './cloud-settings/cloud-settings-store.ts';
import { CrewSkillCatalogue } from './crew/crew-skill-rules.ts';
import { DecorShop } from './decor/decor-purchase.ts';
import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts';
import { battleEconomy } from './game-data/datasets/battle-economy.ts';
import { battleEconomy, type BattleEconomyData } from './game-data/datasets/battle-economy.ts';
import { battleSpawnRules } from './game-data/datasets/battle-spawn-rules.ts';
import { researchEfficiency } from './game-data/datasets/research-efficiency.ts';
import { ResearchEfficiency } from './research/research-efficiency.ts';
@@ -31,11 +32,11 @@ import { decorCatalogue } from './game-data/datasets/decor-catalogue.ts';
import { externalItemSources } from './game-data/datasets/external-item-sources.ts';
import { flightModelPresets } from './game-data/datasets/flight-model-presets.ts';
import { itemCatalogue } from './game-data/datasets/item-catalogue.ts';
import { multiplayerMissions } from './game-data/datasets/multiplayer-missions.ts';
import { multiplayerMissions, type MultiplayerMissions } from './game-data/datasets/multiplayer-missions.ts';
import { shopCountries } from './game-data/datasets/shop-countries.ts';
import { storeBundles } from './game-data/datasets/store-bundles.ts';
import { uiLabels, type UiLabels } from './game-data/datasets/ui-labels.ts';
import { unitNames } from './game-data/datasets/unit-names.ts';
import { unitNames, type UnitNamesMap } from './game-data/datasets/unit-names.ts';
import { unlockPrices } from './game-data/datasets/unlock-prices.ts';
import { vehicleCatalogue, type CatalogueVehicle } from './game-data/datasets/vehicle-catalogue.ts';
import { webIcons } from './game-data/datasets/web-icons.ts';
@@ -49,6 +50,7 @@ import { ItemCatalogue } from './items/item-catalogue.ts';
import { LoginService } from './login/login-service.ts';
import { matchingRequests } from './matching/matching-requests.ts';
import type { MatchingService } from './matching/matching-service.ts';
import { ServerModRuntime } from './mods/server-mod-runtime.ts';
import { setUpProfiles } from './profiles-setup.ts';
import { createPortListener } from './transport/port-listener.ts';
import { Router } from './transport/router.ts';
@@ -67,39 +69,100 @@ export interface ServerOptions {
/** Accounts, saves and logs. */
readonly dataFolder: string;
readonly port: number;
/** Start-up progress lines (static data extraction, game modes). */
/** Start-up progress lines (static data extraction, game modes, mod loading). */
readonly report?: (line: string) => void;
/** Whether to write traffic logs under `<dataFolder>/logs`; defaults to true. */
readonly loggingEnabled?: boolean;
/** Ordered list of enabled additive mods to load for this session. */
readonly mods?: readonly DiscoveredMod[];
}
export const LOOPBACK = '127.0.0.1';
export interface RunningServer {
readonly logFolder: string;
readonly loadedModIds: readonly string[];
close(): Promise<void>;
}
export async function startServer(options: ServerOptions): Promise<RunningServer> {
const report = options.report ?? (() => {});
const enabledMods = options.mods ?? [];
const modRuntime = await ServerModRuntime.load({
mods: enabledMods,
gameFolder: options.gameFolder,
dataFolder: options.dataFolder,
port: options.port,
report,
});
const gameFiles = new GameFiles(options.gameFolder);
// Static data and stores first, before the port opens.
const datasets = new DatasetCache(options.dataFolder, gameFiles, report);
const tuning = loadTuning(options.dataFolder, report);
const tuning = loadTuning(options.dataFolder, report, enabledMods);
const mutableDatasets = new Map<string, unknown>();
const vehiclesList: CatalogueVehicle[] = [...datasets.load(vehicleCatalogue)];
const rawMissions = datasets.load(multiplayerMissions);
const missionsObj: MultiplayerMissions = {
categories: [...rawMissions.categories],
missions: { ...rawMissions.missions },
};
const spawnRulesObj = datasets.load(battleSpawnRules);
const economyDataObj: BattleEconomyData = { ...datasets.load(battleEconomy), vehicles: { ...datasets.load(battleEconomy).vehicles } };
const labelsObj: UiLabels = { ...datasets.load(uiLabels) };
const localizedUnitNamesObj: UnitNamesMap = { ...datasets.load(unitNames) };
mutableDatasets.set('vehicle-catalogue', vehiclesList);
mutableDatasets.set('multiplayer-missions', missionsObj);
mutableDatasets.set('battle-spawn-rules', spawnRulesObj);
mutableDatasets.set('battle-economy', economyDataObj);
mutableDatasets.set('ui-labels', labelsObj);
mutableDatasets.set('unit-names', localizedUnitNamesObj);
const datasetsView: ServerModDatasetsView = {
vehicles: vehiclesList,
battleEconomy: economyDataObj as unknown as Record<string, unknown>,
battleSpawnRules: spawnRulesObj,
multiplayerMissions: missionsObj as unknown as Record<string, unknown>,
uiLabels: labelsObj as unknown as Record<string, unknown>,
unitNames: localizedUnitNamesObj as unknown as Record<string, unknown>,
get: <T = unknown>(id: string) => mutableDatasets.get(id) as T | undefined,
set: (id: string, value: unknown) => { mutableDatasets.set(id, value); },
};
await modRuntime.runDatasetsLoaded(datasetsView);
const vehicles = (mutableDatasets.get('vehicle-catalogue') as readonly CatalogueVehicle[]) ?? vehiclesList;
const missions = (mutableDatasets.get('multiplayer-missions') as MultiplayerMissions) ?? missionsObj;
const spawnRules = (mutableDatasets.get('battle-spawn-rules') as typeof spawnRulesObj) ?? spawnRulesObj;
const economyData = (mutableDatasets.get('battle-economy') as BattleEconomyData) ?? economyDataObj;
const labels = (mutableDatasets.get('ui-labels') as UiLabels) ?? labelsObj;
const localizedUnitNames = (mutableDatasets.get('unit-names') as UnitNamesMap) ?? localizedUnitNamesObj;
const gameModes = new GameModes(
datasets.load(multiplayerMissions), datasets.load(shopCountries), report, tuning.battle.fixedAirRealisticMaxMrank,
missions, datasets.load(shopCountries), report, tuning.battle.fixedAirRealisticMaxMrank,
);
const accounts = new AccountStore(options.dataFolder);
const clans = new ClanStore(options.dataFolder, tuning.clans);
const cloudSettings = new CloudSettingsStore(options.dataFolder);
const vehicles = datasets.load(vehicleCatalogue);
const spawnRules = datasets.load(battleSpawnRules);
const economyData = datasets.load(battleEconomy);
const efficiencyData = datasets.load(researchEfficiency);
const streakDefinitions = datasets.load(battleStreaks);
const labels = datasets.load(uiLabels);
const { profiles, research, equipment, repair } = setUpProfiles(options.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues(datasets, tuning, vehicles, labels);
const { profiles, research, equipment, repair } = setUpProfiles(
options.dataFolder,
gameFiles,
datasets,
tuning,
{ accounts, clans },
vehicles,
(profile, userId) => modRuntime.runProfileRefresh(profile, userId),
);
const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues(
datasets,
tuning,
vehicles,
labels,
localizedUnitNames,
);
const storeProducts = catalogues.store.allProducts();
const artwork = new GameArtwork(options.gameFolder, {
vehicles: storeProducts.flatMap((product) => product.vehicles?.map((vehicle) => vehicle.name) ?? []),
@@ -112,8 +175,19 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
let matching: MatchingService | undefined;
const notifyInventoryChanged = () => matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' });
const notifyUser = (userId: string, eventName: string, payload: Record<string, unknown>) => {
matching?.notifyUser(userId, eventName, payload);
};
const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept);
const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules, botAircraftLoadouts);
const battleMatchmaker = new BattleMatchmaker(
gameModes,
vehicles,
battleSessions,
tuning.battle,
spawnRules,
botAircraftLoadouts,
(ctx) => modRuntime.runBattleFilterMissions(ctx),
);
const economy = new BattleEconomy(
economyData,
tuning.battleEconomy,
@@ -124,7 +198,31 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
const streaks = new BattleStreaks(streakDefinitions, vehicles, economy);
const supportPlanes = supportPlaneUnits(spawnRules);
await modRuntime.runCataloguesReady({
tuning: tuning as unknown as Readonly<Record<string, unknown>>,
gameModes,
profiles,
accounts,
research,
equipment,
repair,
store: catalogues.store,
inventory: catalogues.inventory,
trophies: catalogues.trophies,
items: catalogues.items,
crew: catalogues.crew,
decor: catalogues.decor,
unlocks: catalogues.unlocks,
clans,
battleMatchmaker,
battleEconomy: economy,
battleStreaks: streaks,
notifyInventoryChanged,
notifyUser,
});
const router = new Router([
modRuntime.httpService(),
webUi,
new RegistrationService(accounts),
new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes, options.port),
@@ -140,44 +238,69 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
...catalogues,
clans: { store: clans, economy: squadronEconomy },
cloudSettings,
battle: { sessions: battleSessions, economy, efficiency: new ResearchEfficiency(efficiencyData, research.techTree), streaks, supportPlanes },
battle: {
sessions: battleSessions,
economy,
efficiency: new ResearchEfficiency(efficiencyData, research.techTree),
streaks,
supportPlanes,
onAfterSettle: (ctx) => modRuntime.runBattleAfterSettle(ctx),
},
notifyInventoryChanged,
})),
}), modRuntime),
new DownloadableContentService(),
]);
const log = new TrafficLog(options.dataFolder, options.loggingEnabled ?? true);
const matchingTable = modRuntime.applyMatchingRoutes(matchingRequests({
gameModes,
accounts,
battle: {
gameModes,
profiles,
matchmaker: battleMatchmaker,
sessions: battleSessions,
economy,
notifyLaunch: (userId, payload) => matching?.notifyUser(userId, 'mrpc.generic_notify', payload),
onBeforeMatchmake: (ctx) => modRuntime.runBattleBeforeMatchmake(ctx),
},
battleLive: {
sessions: battleSessions,
liveLogs: new BattleLiveLogs(tuning.limits.battleSessionsKept),
streaks,
supportPlanes,
onLiveFact: (ctx) => modRuntime.runBattleLiveFact(ctx),
},
}));
const listener = createPortListener(
router,
matchingRequests({
gameModes,
accounts,
battle: {
gameModes,
profiles,
matchmaker: battleMatchmaker,
sessions: battleSessions,
economy,
notifyLaunch: (userId, payload) => matching?.notifyUser(userId, 'mrpc.generic_notify', payload),
},
battleLive: { sessions: battleSessions, liveLogs: new BattleLiveLogs(tuning.limits.battleSessionsKept), streaks, supportPlanes },
}),
matchingTable,
log,
loadOrCreateCredentials(options.dataFolder),
);
matching = listener.matching;
await listen(listener.server, options.port);
await modRuntime.runServerListening(options.port);
return {
logFolder: log.folder,
close: () => new Promise((resolve) => {
listener.server.close(() => resolve());
listener.destroyConnections();
}),
loadedModIds: modRuntime.loadedModIds,
close: async () => {
await modRuntime.runServerClosing();
await new Promise<void>((resolve) => {
listener.server.close(() => resolve());
listener.destroyConnections();
});
},
};
}
function loadDomainCatalogues(datasets: DatasetCache, tuning: Tuning, vehicles: readonly CatalogueVehicle[], labels: UiLabels) {
function loadDomainCatalogues(
datasets: DatasetCache,
tuning: Tuning,
vehicles: readonly CatalogueVehicle[],
labels: UiLabels,
localizedUnitNames: UnitNamesMap,
) {
const classicItemDefs = datasets.load(itemCatalogue);
const localizedUnitNames = datasets.load(unitNames);
return {
crew: new CrewSkillCatalogue(datasets.load(crewSkillData)),
decor: new DecorShop(datasets.load(decorCatalogue)),
+7 -2
View File
@@ -6,9 +6,14 @@
* `bundles/guid` registers a GUID for its id, so the build must register every pack this server
* will sell from the same data folder.
*/
import type { DiscoveredMod } from '@wto/mods';
import { tuningFiles } from '../tuning/tuning-loader.ts';
import { readStoreTuning } from './store-tuning.ts';
export function multiVehiclePackIds(dataFolder: string, report: (line: string) => void): string[] {
return readStoreTuning(tuningFiles(dataFolder, report).read('store')).multiVehiclePacks.map((pack) => pack.id);
export function multiVehiclePackIds(
dataFolder: string,
report: (line: string) => void,
mods: readonly DiscoveredMod[] = [],
): string[] {
return readStoreTuning(tuningFiles(dataFolder, report, undefined, mods).read('store')).multiVehiclePacks.map((pack) => pack.id);
}
+30 -20
View File
@@ -1,16 +1,21 @@
/**
* Load one tuning file: the defaults shipped in
* apps/server/tuning/<name>.jsonc, with <data folder>/tuning/<name>.jsonc laid
* over them field by field when the player or a developer put one there. Objects merge key
* by key; any other value (numbers, texts, lists) in the override replaces the default.
* Load one tuning file with multi-layer overrides:
* shipped defaults (`apps/server/tuning/<name>.jsonc`)
* -> each enabled mod's `<server.tuning>/<name>.jsonc` in load order
* -> player overrides (`<dataFolder>/tuning/<name>.jsonc`).
*
* Objects merge key by key; plain lists replace the base list; `{ "$listOps": [...] }`
* performs additive append/prepend/upsertBy/removeBy operations across layers.
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseJsonc } from '@wto/jsonc';
import { mergeTuningLayer, type DiscoveredMod } from '@wto/mods';
import { TuningError, TuningReader } from './tuning-reader.ts';
const DEFAULTS_FOLDER = fileURLToPath(new URL('../../tuning/', import.meta.url));
const DEFAULT_MOD_TUNING_DIR = 'server/tuning';
export interface TuningFiles {
/** The merged content of <name>.jsonc, ready for typed reads. */
@@ -21,19 +26,35 @@ export function tuningFiles(
dataFolder: string | null,
report: (line: string) => void,
proposed?: ReadonlyMap<string, Record<string, unknown>>,
mods: readonly DiscoveredMod[] = [],
): TuningFiles {
const overridesFolder = dataFolder === null ? null : join(dataFolder, 'tuning');
return {
read(name: string): TuningReader {
const fileName = `${name}.jsonc`;
const defaults = parseFile(join(DEFAULTS_FOLDER, fileName));
let merged = parseFile(join(DEFAULTS_FOLDER, fileName));
for (const mod of mods) {
const modTuningDir = mod.manifest.server?.tuning ?? DEFAULT_MOD_TUNING_DIR;
const modFilePath = join(mod.rootDir, ...modTuningDir.split('/'), fileName);
if (!existsSync(modFilePath)) continue;
report(`tuning ${fileName}: applying mod "${mod.manifest.id}" overrides`);
try {
merged = mergeTuningLayer(merged, parseFile(modFilePath));
} catch (error) {
throw new TuningError(
`mod "${mod.manifest.id}" tuning ${fileName} merge failed: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
const candidate = proposed?.get(name);
if (candidate) return new TuningReader(fileName, mergeOverride(defaults, candidate));
if (overridesFolder === null) return new TuningReader(fileName, defaults);
if (candidate) return new TuningReader(fileName, mergeTuningLayer(merged, candidate));
if (overridesFolder === null) return new TuningReader(fileName, merged);
const overridePath = join(overridesFolder, fileName);
if (!existsSync(overridePath)) return new TuningReader(fileName, defaults);
if (!existsSync(overridePath)) return new TuningReader(fileName, merged);
report(`tuning ${fileName}: using overrides from ${overridePath}`);
return new TuningReader(fileName, mergeOverride(defaults, parseFile(overridePath)));
return new TuningReader(fileName, mergeTuningLayer(merged, parseFile(overridePath)));
},
};
}
@@ -45,14 +66,3 @@ function parseFile(path: string): unknown {
throw new TuningError(`tuning file ${path} cannot be read: ${error instanceof Error ? error.message : String(error)}`);
}
}
function mergeOverride(base: unknown, override: unknown): unknown {
if (!isObject(base) || !isObject(override)) return override;
const merged: Record<string, unknown> = { ...base };
for (const [key, value] of Object.entries(override)) merged[key] = key in base ? mergeOverride(base[key], value) : value;
return merged;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+7 -2
View File
@@ -13,6 +13,7 @@ import { readNewProfileTuning, type NewProfileTuning } from '../profile/new-prof
import { readResearchTuning, type ResearchTuning } from '../research/research-tuning.ts';
import { readRedeemTuning, type RedeemTuning } from '../store/redeem-tuning.ts';
import { readStoreTuning, type StoreTuning } from '../store/store-tuning.ts';
import type { DiscoveredMod } from '@wto/mods';
import { readLimitsTuning, type LimitsTuning } from './limits-tuning.ts';
import { tuningFiles } from './tuning-loader.ts';
@@ -31,8 +32,12 @@ export interface Tuning {
readonly limits: LimitsTuning;
}
export function loadTuning(dataFolder: string, report: (line: string) => void): Tuning {
const files = tuningFiles(dataFolder, report);
export function loadTuning(
dataFolder: string,
report: (line: string) => void,
mods: readonly DiscoveredMod[] = [],
): Tuning {
const files = tuningFiles(dataFolder, report, undefined, mods);
return {
store: readStoreTuning(files.read('store')),
redeemCodes: readRedeemTuning(files.read('redeem-codes')),
+2
View File
@@ -12,6 +12,7 @@
| 改游戏规则、档案或本地服务 | [apps/server](../apps/server) |
| 改游戏副本的构建或补丁检查 | [packages/patcher](../packages/patcher)、[scripts](../scripts)、[tools](../tools) |
| 写客户端补丁或适配新的游戏版本 | [补丁指南](patches.md#zh-cn)和[补丁集](../patches) |
| 制作添加式模组(实验期) | [模组开发文档(mod-dev-docs)](../mod-dev-docs/README.md) |
提交前按[自查清单](contributing.md#zh-cn)整理依据、运行适用的[检查命令](contributing.md#checks),并把检查结果和实机步骤写进 [PR 模板](templates/pull-request.md)。
@@ -27,5 +28,6 @@ Start with a stock client you own and use it as a read-only source. Install the
| Change game rules, saves, or local services | [apps/server](../apps/server) |
| Change the game copy build or patch checks | [packages/patcher](../packages/patcher), [scripts](../scripts), [tools](../tools) |
| Write a client patch or adapt a new game build | [Patch guide](patches.md#english) and the [patch set](../patches) |
| Author additive mods (experimental) | [Mod development docs (mod-dev-docs)](../mod-dev-docs/README.md#english) |
Before submitting, follow the [review checklist](contributing.md#english), run the applicable [checks](contributing.md#checks), and record the results and in-game steps in the [PR template](templates/pull-request.md).
+49
View File
@@ -0,0 +1,49 @@
# WTOffline 模组开发文档 / Mod Development Documentation
简体中文 · [English](#english)
> **实验期声明(API `0.1-experimental`)**
> WTOffline 当前处于极初期开发阶段。服务端脚本接口、内部数据结构、钩子契约及声明式 `exe` 补丁格式均可能随本体开发随时调整,**现阶段不承诺向后兼容**。模组作者使用服务端脚本或客户端二进制补丁时,请做好跟随本体更新维护的准备。
---
## 中文文档目录(`zh-CN/`)
| 章节 | 内容概览 |
| --- | --- |
| [01 · 快速入门与清单规范](zh-CN/01-quick-start.md) | 5 分钟做出第一个模组、目录结构、`mod.jsonc` 全字段表、依赖/互斥/排序、风险徽标与启动器调试 |
| [02 · 客户端数据包与 BLK 增量补丁](zh-CN/02-client-packs-and-blk.md) | 8 个可叠加 `.vromfs.bin` 包、BLK 补丁全部 7 种操作(含 `cloneBlock`)、13 种 BLK 类型写法、文本 `.blk` 自动编译、CSV 词条合并、`config.blk` 补丁 |
| [03 · 添加全新 3D 模型与贴图载具](zh-CN/03-custom-3d-vehicles.md) | `client/addon/res/`(`.grp` + `.dxp.bin`)跨盘 NTFS Junction 零拷贝挂载、挂进科技树/经济/图标/译名、原生涂装瞄具边界说明 |
| [04 · 客户端 GUI 补丁与声明式 EXE 补丁](zh-CN/04-client-gui-and-exe.md) | 增量 GUI 脚本补丁、新增原生 DaGui 弹窗、`sq.exe` Quirrel 完整字节码检查、声明式 `exe` 补丁与核心隔离保护红线 |
| [05 · 服务端零代码数值叠加(Tuning)](zh-CN/05-server-tuning.md) | 12 份 `server/tuning/*.jsonc` 说明、多层合并顺序、`$listOps` 列表增量操作(`append` / `prepend` / `upsertBy` / `removeBy`) |
| [06 · 服务端 JS/TS 脚本完整接口手册](zh-CN/06-server-scripting-api.md) | Node 24 原生 TS 语法要求、`WtoServerModContext`、独立存档区 `storage`、全部生命周期与对局钩子(含 `onFilterMissions`)、`char` / `matching` / `http` 路由与完整范例 |
| [07 · 排错、日志与最佳实践](zh-CN/07-troubleshooting-and-faq.md) | 定位 `launcher.log` 与本地服务器日志、冲突分析、防止损坏玩家存档、跨盘与非 NTFS 磁盘行为说明 |
### 自带官方模组模板(`templates/`)
以下 3 个模组会随 WTOffline 启动器自动分发到玩家首次初始化的全局 `mods/` 目录(默认关闭,勾选即用),可直接对照源码学习或复制改造:
| 模板目录 | 定位 | 演示的核心能力 |
| --- | --- | --- |
| `templates/example-vehicle-tweak/` | 零代码数据与本地化示例 | `server/tuning/battle.jsonc` + `wpcost.blk.patch.jsonc` + `lang/units.csv.patch.csv` |
| `templates/example-server-script/` | 服务端脚本最小示例 | `server/index.ts`、`onDatasetsLoaded`、`profile.onRefresh`、独立存档区、自定义 `/mods/<id>/status` 路由 |
| `templates/official-map-selector/` | 实用全栈官方模组 | 模式选择 UI 按钮补丁 + 原生 DaGui 小地图网格弹窗 + 多语言词条 + 自定义匹配 RPC + 独立存档 + `battle.onFilterMissions` 白/黑名单选图 |
---
<a id="english"></a>
## English Documentation (`en/`)
> **Experimental Notice (API `0.1-experimental`)**
> WTOffline is in early development. Server script APIs, internal data structures, hook contracts, and declarative `exe` patch formats may change without backwards compatibility across releases. Authors using server scripts or binary patches should be ready to update alongside core releases.
| Chapter | Topics |
| --- | --- |
| [01 · Quick Start & Manifest](en/01-quick-start.md) | Build your first mod in 5 minutes, folder layout, full `mod.jsonc` schema, dependencies/conflicts/ordering, risk badges |
| [02 · Client Packs & BLK Patching](en/02-client-packs-and-blk.md) | 8 overlayable `.vromfs.bin` packs, all 7 BLK patch ops (including `cloneBlock`), all 13 BLK types, auto text-BLK compilation, CSV merging, `config.blk` patches |
| [03 · Custom 3D Vehicle Models](en/03-custom-3d-vehicles.md) | `client/addon/res/` (`.grp` + `.dxp.bin`) cross-drive zero-copy NTFS Junction mounting, tech tree/economy/icons/localization wiring, native skins/sights boundary |
| [04 · Client GUI & Declarative EXE Patches](en/04-client-gui-and-exe.md) | Incremental GUI script patches, adding standalone native DaGui modals, full Quirrel bytecode checks (`sq.exe`), declarative `exe` patches & core isolation lock |
| [05 · Server Code-Free Tuning Overlays](en/05-server-tuning.md) | All 12 `server/tuning/*.jsonc` files, multi-layer precedence, `$listOps` (`append`, `prepend`, `upsertBy`, `removeBy`) |
| [06 · Server JS/TS Scripting API Reference](en/06-server-scripting-api.md) | Node 24 erasable TypeScript rules, `WtoServerModContext`, isolated `storage`, all lifecycle & battle hooks (including `onFilterMissions`), `char` / `matching` / `http` routes |
| [07 · Troubleshooting & FAQ](en/07-troubleshooting-and-faq.md) | Reading logs, diagnosing conflicts, keeping player saves clean, cross-drive and exFAT fallback behavior |
+105
View File
@@ -0,0 +1,105 @@
# 01 · Quick Start & Manifest Reference
> **Target Spec**: `format: 1` · `api_version: "0.1-experimental"` (experimental; subject to breaking changes)
## 1. Additive Mod Architecture
WTOffline uses a **stackable, additive** mod system and does **not** accept whole-pack `.vromfs.bin` replacements:
1. Before launching the game, the launcher starts from clean stock backups (`wtoffline/stock/`), applies core offline patches first, then layers every enabled mod's client patches and added files in the order shown on the **Mods** page;
2. Large 3D model and texture addons mount across drives with zero copying via **Windows NTFS Directory Junctions**;
3. The local server extracts static data from the overlaid packs, layers `server/tuning/*.jsonc` in the same order, and loads `server/index.ts` scripts;
4. Disabling a mod or switching presets cleanly unmounts junctions and restores stock packs.
- **Global repository**: defaults to `%APPDATA%\WTOffline Launcher\mods` (configurable to any drive under **Mods › Presets & repository**).
- **Per-client configuration**: toggles, load order, and presets live in each client's `<dataPath>/mods-config.json`.
---
## 2. Build Your First Mod in 5 Minutes
1. Open **Mods › Open mods folder** in the launcher.
2. Create a folder `my-first-mod` containing `mod.jsonc`:
```jsonc
{
"format": 1,
"id": "demo.my-first-mod",
"name": { "en": "My First Mod", "zh-CN": "我的第一个模组" },
"version": "0.1.0",
"author": "YourName",
"description": "Doubles Silver Lions and Research Points battle rewards.",
"api_version": "0.1-experimental",
"game_versions": ["2.61.0.*"]
}
```
3. Create `my-first-mod/server/tuning/battle.jsonc`:
```jsonc
{
"rewardMultiplierSilverLions": 2.0,
"rewardMultiplierResearchPoints": 2.0
}
```
4. Return to the launcher (the Mods page refreshes automatically on focus), enable your mod, and click **Launch**.
---
## 3. Standard Folder Layout
Create only the folders your mod actually needs:
```text
<mod-folder>/
├─ mod.jsonc # Required: manifest
├─ server/ # Optional: server extensions
│ ├─ tuning/ # *.jsonc tuning overlays
│ └─ index.ts (or index.mjs / .js) # server script entry
└─ client/ # Optional: client extensions
├─ packs/ # .vromfs.bin additive overlays
│ ├─ char.vromfs.bin/
│ ├─ aces.vromfs.bin/
│ ├─ gui.vromfs.bin/
│ ├─ lang.vromfs.bin/
│ ├─ mis.vromfs.bin/
│ ├─ game.vromfs.bin/
│ ├─ ui/atlases.vromfs.bin/
│ └─ ui/images.vromfs.bin/
├─ addon/ # 3D model & texture pack (res/*.grp, res/*.dxp.bin)
├─ gui-patches/ # declarative GUI script patches
├─ exe-patches/ # declarative exe patches
├─ files/ # optional companion skins/sights/sounds/missions
└─ config-blk.patch.jsonc # optional root config.blk patch
```
---
## 4. `mod.jsonc` Schema Reference
Unknown fields are rejected by strict validation.
| Field | Required | Type | Description |
| --- | --- | --- | --- |
| `format` | Yes | `1` | Manifest format version (currently `1`) |
| `id` | Yes | `string` | Globally unique ID matching `/^[a-z0-9][a-z0-9._-]{0,63}$/` |
| `name` | Yes | `string \| { [lang]: string }` | Display name (plain string or locale map) |
| `version` | Yes | `string` | Mod version (SemVer recommended) |
| `author` | Yes | `string` | Author or team name |
| `description` | No | `string \| { [lang]: string }` | Short description |
| `api_version` | Yes | `string` | Target API tag, currently `"0.1-experimental"` |
| `game_versions` | No | `string[]` | Game version wildcards (e.g. `["2.61.0.*"]`); mismatch warns only |
| `requires` | No | `string[]` | Required dependency mod IDs (blocking error if missing/disabled) |
| `conflicts` | No | `string[]` | Incompatible mod IDs (blocking error if both enabled) |
| `load_after` | No | `string[]` | Recommended load-order predecessors (used by Auto-sort) |
| `load_before` | No | `string[]` | Recommended load-order successors |
| `server` | No | `{ entry?: string, tuning?: string }` | Custom relative paths for server script entry and tuning folder |
---
## 5. Load Order, Risk Badges & Conflict Detection
- **Priority**: items lower in the list load later and take higher priority.
- **Risk badges**: automatically inferred as `data`, `gui`, `script`, and `exe`.
- **Conflict checks**: missing/disabled dependencies and declared conflicts block launching; whole-file overrides warn; shared BLK/CSV/tuning overlays report informational merge notices.
@@ -0,0 +1,53 @@
# 02 · Client Packs & BLK Incremental Patching
## 1. Supported `.vromfs.bin` Packs
Place overlays under `client/packs/<pack-path>/`:
- **Always rebuilt from stock**: `char.vromfs.bin`, `aces.vromfs.bin`, `gui.vromfs.bin`
- **On-demand backup & restore**: `lang.vromfs.bin`, `mis.vromfs.bin`, `game.vromfs.bin`, `ui/atlases.vromfs.bin`, `ui/images.vromfs.bin`
Because the local server extracts static datasets directly from the overlaid packs on startup, vehicles added or edited in `shop.blk` and `wpcost.blk` automatically flow into research trees, prices, modifications, AI pools, and offline store bundle GUIDs.
---
## 2. File Handling Rules
1. **`<target>.patch.jsonc`** — Type-preserving structured BLK patch applied to `<target>` inside the pack.
2. **`<target>.patch.csv`** — Semicolon-separated localization CSV merger keyed by column 0.
3. **Any other file** — Added or replaced directly. Plain text `.blk` files are compiled to binary BLK automatically before packing.
---
## 3. BLK Patch Operations (`*.blk.patch.jsonc`)
Every patch file has `{ "ops": [...] }`. Path segments support indexed sibling selectors such as `"range[2]"` (zero-based).
- **`setParam`**: `{ "op": "setParam", "path": [...], "name": "...", "value": ..., "createBlocks": false }`
- **`addParam`**: appends a repeated parameter without removing existing entries (ideal for `slaveUnit`, `folder`, `aircraftGift`).
- **`removeParam`**: removes all matching params by `name` (or only those matching optional `value`).
- **`upsertBlock`**: finds or creates a block along `path` and merges `block.params` and `block.blocks`.
- **`addBlock`**: inserts a new child block (`before` / `after` sibling anchor optional).
- **`removeBlock`**: deletes the block at `path`.
- **`cloneBlock`**: deep-clones an existing block (`from`) into `toParent` under `newName`, optionally applying nested `ops` rooted at the cloned block (fastest way to derive a modded vehicle in `wpcost.blk`).
### Explicit BLK Types
Use `{ "type": "<blkType>", "value": <val> }` whenever an exact Dagor BLK type is needed:
`string`, `int`, `real`, `bool`, `int64`, `point2`, `point3`, `point4`, `ipoint2`, `ipoint3`, `ipoint4`, `color` (`[r,g,b,a]` or packed `0xAARRGGBB`), `matrix` (12 reals).
---
## 4. Localization CSV Patches (`*.csv.patch.csv`)
```csv
"<ID|readonly|noverify>";"<English>";"<Chinese>";"<HChinese>"
"my_custom_tank_shop";"M1A2 Mod";"M1A2 魔改型";"M1A2 魔改型"
```
Existing keys update only the supplied non-empty language columns; new keys are appended cleanly.
---
## 5. Root `config.blk` Patches (`client/config-blk.patch.jsonc`)
Uses the exact same BLK patch format against `<copy>/config.blk`. The launcher backs up the stock `config.blk` automatically and restores it when no enabled mod patches it.
+33
View File
@@ -0,0 +1,33 @@
# 03 · Adding Custom 3D Vehicle Models & Textures
## 1. How 3D Asset Mounting Works
Verified directly against 2.61.0.x `aces.exe` (`dlContent.cpp`) and `config/settings.blk`:
- Any addon path under `/pkg_user/` skips the `res/grp_hdr.vromfs.bin` check and directly scans `<addon>/res/` for all `.grp` (3D geometry/skeleton/collision) and `.dxp.bin` (DDSx texture) archives;
- If a mod ships a compiled CDK `res/grp_hdr.vromfs.bin`, the patcher mounts it under `content/pkg_wto_<modId>` so the native `grp_hdr` loader handles it;
- The patcher automatically registers all enabled mod addon folders in `aces.vromfs.bin` `config/settings.blk` (`addons`, `addons_no_check`, `addonsWithBasePath`).
### Cross-Drive Zero-Copy Mounting
Each mod's `client/addon/` is mounted into `<copy>/content/pkg_user/<safeModId>` via a **Windows NTFS Directory Junction**:
- Works across drives (e.g. `mods/` on C: or D:, client on J:);
- Requires no administrator privileges;
- Uses 0 extra bytes and mounts/unmounts in ~1 ms without touching source files in `mods/`.
---
## 2. 6-Step Checklist for a Custom 3D Vehicle
1. **`client/addon/res/<unit>.grp` + `<unit>.dxp.bin`**: 3D model and textures exported via War Thunder CDK;
2. **`client/packs/aces.vromfs.bin/gamedata/units/.../<unit>.blk`**: vehicle FM/DM/weapons (plain text BLK compiles automatically);
3. **`client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc`**: economy, BR, modifications (use `cloneBlock` from a similar stock vehicle);
4. **`client/packs/char.vromfs.bin/config/shop.blk.patch.jsonc`** & **`unittags.blk.patch.jsonc`**: tech tree slot and unit tags;
5. **`client/packs/lang.vromfs.bin/lang/units.csv.patch.csv`**: localized names (`_shop`, `_0`, `_1`, `_2`);
6. **`client/packs/ui/atlases.vromfs.bin/gameuiskin/<lowercase_unit>_ico.svg`** & optional **`ui/images.vromfs.bin/units/<unit>.ddsx`**: silhouette icon (used in tech tree and local web store) and statcard image.
---
## 3. Native Skins, Sights & Companion Files Boundary
- Standalone user skins (`UserSkins/`), sights (`UserSights/`), and missions (`UserMissions/`) continue to use the game's native folders and are never managed or deleted by the launcher.
- Large overhaul/vehicle mods may optionally bundle companion skins, sights, or sound banks under `client/files/`. Exclusive subdirectories under `UserSkins/`, `UserSights/`, and `UserMissions/` mount via cross-drive Junctions; any target colliding with a player-owned native file is skipped with a warning and never overwritten.
+33
View File
@@ -0,0 +1,33 @@
# 04 · Client GUI Patches & Declarative EXE Patches
> **Experimental Notice**: GUI script patches and declarative `exe` patches depend on target client builds and may need updates after game or core patches.
---
## 1. Extending Client UI (Recommended Pattern)
1. Place new standalone `.nut`, `.tpl`, and `.css` files under `client/packs/gui.vromfs.bin/` (keep paths lowercase to match stock archive conventions);
2. Place minimal entry-point edits under `client/gui-patches/<patch-name>/` using `patch.jsonc` + `find.nut` / `replace.nut` fragments.
Core offline GUI patches always run first; mod GUI patches apply afterward in load order. Every `find` snippet must match uniquely once or the patch is skipped safely. `{{LOCAL_ENDPOINT}}` in replacement text expands to `127.0.0.1:<port>`.
### Mandatory Quirrel Bytecode Check
Before shipping any new or patched `.nut` script, compile the complete resulting script with `compilestring` via `sq.exe` to catch lexical scope conflicts, reserved keywords (such as `base`), and forward references that would otherwise hang login at "Loading":
```powershell
& "build\quirrel-cli\bin\Release\sq.exe" -e "local f = compilestring(readfile('your_script.nut'), 'your_script.nut'); println('OK')"
```
---
## 2. Declarative EXE Patches (`client/exe-patches/`)
Mods reuse WTOffline's `@wto/exepatch` format (`patch.jsonc` with `id`, `title`, `features`, `requires`, and `variants` using `signature`, `string_ref`, or `within` locators). **Never distribute modified `aces.exe` binaries.**
### Core Isolation Lock (Hard Security Boundary)
1. Core offline and isolation patches are planned first and their byte ranges are locked;
2. Any mod `exe` patch whose write range overlaps a protected core patch is **rejected** (`overlaps protected core patch`);
3. Overlapping patches between two mods reject the later patch with the conflicting mod ID;
4. Unmatched patterns on another game build are skipped cleanly and logged without breaking the core build.
+31
View File
@@ -0,0 +1,31 @@
# 05 · Server Code-Free Tuning Overlays
The local server stores all offline-defined economy, battle, store, marketplace, chest, redeem-code, clan, and limit values in **12 `.jsonc` tuning files**. Mods can overlay any of them under `server/tuning/<name>.jsonc` without writing code.
## 1. Merge Precedence
1. Shipped defaults (`apps/server/tuning/<name>.jsonc`)
2. Enabled mods' `server/tuning/<name>.jsonc` in load order
3. Player overrides (`<dataFolder>/tuning/<name>.jsonc`, highest priority)
## 2. All 12 Tuning Files
`battle.jsonc`, `battle-economy.jsonc`, `store.jsonc`, `marketplace.jsonc`, `trophies.jsonc`, `supply-chests.jsonc`, `recycling.jsonc`, `redeem-codes.jsonc`, `new-profile.jsonc`, `research.jsonc`, `clans.jsonc`, `limits.jsonc`.
## 3. Additive List Operations (`$listOps`)
Objects merge recursively by key; plain arrays replace the previous array. To stack items across multiple mods without clobbering, wrap list edits in `{ "$listOps": [...] }`:
```jsonc
{
"multiVehiclePacks": {
"$listOps": [
{ "op": "append", "items": [{ "id": "mod_duo_pack", "priceGjn": 49.99, "vehicles": ["us_m2a4"] }] },
{ "op": "upsertBy", "key": "id", "item": { "id": "wto_pack_two_fronts", "priceGjn": 19.99 } },
{ "op": "removeBy", "key": "id", "value": "some_pack_id" }
]
}
}
```
Supported ops: `append`, `prepend`, `upsertBy`, `removeBy`.
@@ -0,0 +1,40 @@
# 06 · Server JS/TS Scripting API Reference
> **Experimental Warning (API `0.1-experimental`)**: All server script contracts, internal catalogue classes, and hook shapes are unstable and may change across releases without backwards compatibility.
## 1. Runtime & TypeScript Rules
Server scripts run inside Electron 43's bundled **Node.js 24** with built-in TypeScript type stripping (`erasableSyntaxOnly` syntax: no `enum`, `namespace`, or parameter properties). Pre-bundled `.mjs` / `.js` files are also supported.
Default entry lookup order: `server/index.ts` → `server/index.mjs` → `server/index.js` (or explicit `server.entry` in `mod.jsonc`).
```ts
export default {
async setup(ctx) {
ctx.logger.info('mod initialized');
},
};
```
Full TypeScript definitions live in `packages/mods/src/server-api.ts`.
## 2. `WtoServerModContext`
- `apiVersion`, `manifest`, `modDir`, `gameFolder`, `dataFolder`, `port`
- `logger`: `{ info(msg), warn(msg), error(msg) }` (prefixed with `[mod:<id>]`)
- `storage`:
- `storage.forPlayer(userId)` → atomic JSON file under `<dataFolder>/saves/<userId>/mods/<modId>.json` (never mutate stock `profile.blk` with custom keys)
- `storage.shared()` → `<dataFolder>/mods-data/<modId>.json`
- `hooks`:
- `onDatasetsLoaded(datasets)` — inspect/mutate `vehicles`, `battleEconomy`, `battleSpawnRules`, `multiplayerMissions`, `uiLabels`, `unitNames`, or `get(id)` / `set(id, value)`
- `onCataloguesReady(catalogues)` — access `tuning`, `gameModes`, `profiles`, `accounts`, `research`, `equipment`, `repair`, `store`, `inventory`, `trophies`, `items`, `crew`, `decor`, `unlocks`, `clans`, `battleMatchmaker`, `battleEconomy`, `battleStreaks`, `notifyInventoryChanged()`, `notifyUser(userId, eventName, payload)`
- `onServerListening({ port })` / `onServerClosing()`
- `profile.onRefresh(profile, userId)`
- `battle.onBeforeMatchmake({ userId, eventName, request })`
- `battle.onFilterMissions({ userId, modeId, modeName, economicName, minMrank, maxMrank, missions })` — return a filtered/reordered subset of candidate missions (empty results safely fall back to the prior pool)
- `battle.onLiveFact({ userId, roomId, fact })`
- `battle.onAfterSettle({ userId, roomId, summary })`
- `routes`:
- `routes.char.register(action, handler)` / `routes.char.wrap(action, wrapper)`
- `routes.matching.register(method, handler)` / `routes.matching.wrap(method, wrapper)` (callable from client Quirrel via `matchingApiFunc`)
- `routes.http.register(subPath, handler)` — automatically namespaced under `/mods/<modId>/...` (supports exact paths and `/*` wildcards)
@@ -0,0 +1,21 @@
# 07 · Troubleshooting & Best Practices
## 1. Where to Check Logs
Open **Settings › Diagnostics › Open logs folder** or **About › Export diagnostics**:
- **`launcher.log`**: filter `[build]` for pack/GUI/exe patch reports, `[mods]` for Junction mount and native-file conflict warnings, and `[mod:<id>]` for server script logs and stack traces.
- **`<copy>/.game_logs/*.clog`**: client Quirrel runtime errors and `[PACK]` / `pkg_user` asset loading logs.
## 2. Common Issues
- **Discovery error in Mods page**: check `mod.jsonc` JSON syntax, unknown keys, `id` format, and `server.entry` path.
- **Blocking errors on Launch**: enable missing `requires` dependencies or disable one of two mutually conflicting mods.
- **Node TS syntax error**: avoid `enum`/`namespace`/parameter properties in raw `.ts`, or bundle to `.mjs`.
- **`overlaps protected core patch`**: mod `exe` patch collided with a locked core isolation patch; choose a non-overlapping site.
- **Client hangs at "Loading"**: run full `sq.exe` `compilestring` bytecode checks on all modified/added `.nut` files.
## 3. Cross-Drive & Non-NTFS Behavior
- NTFS drives mount `client/addon/` and exclusive `UserSkins/`/`UserSights/`/`UserMissions/` folders via cross-drive **NTFS Directory Junctions** (no admin required, 0 extra space).
- Flat shared files (`sound/mod/*.bank`) try file symlink → same-drive hardlink → size/mtime cached copy.
- exFAT drives automatically fall back to incremental cached copies.
@@ -0,0 +1,19 @@
// Example experimental server-side TypeScript mod.
// Demonstrates dataset/catalogue hooks, per-account isolated storage, and a custom HTTP endpoint.
{
"format": 1,
"id": "example.server-script",
"name": {
"zh-CN": "示例:服务端 TS 脚本钩子",
"en": "Example: Server TS Script Hooks"
},
"version": "0.1.0",
"author": "WTOffline",
"description": {
"zh-CN": "演示实验期服务端 TypeScript 钩子、独立存档区与自定义 /mods/<id>/status 网页接口。",
"en": "Demonstrates experimental server TypeScript hooks, isolated mod storage, and a custom /mods/<id>/status HTTP route."
},
"api_version": "0.1-experimental",
"game_versions": ["2.61.0.*"],
"load_after": ["example.vehicle-tweak"]
}
@@ -0,0 +1,60 @@
/**
* Example server-side TypeScript mod (erasable TypeScript syntax, runs directly on Electron's Node 24).
*
* EXPERIMENTAL: Internal server contracts and hook shapes may change across WTOffline releases.
*/
interface ModState {
refreshes: number;
lastUpdated: string;
}
export default {
setup(ctx: {
readonly apiVersion: string;
readonly manifest: { readonly id: string; readonly version: string };
readonly logger: { info(msg: string): void };
readonly storage: {
forPlayer(userId: string): { read<T>(): T | undefined; write(value: unknown): void };
};
readonly hooks: {
onDatasetsLoaded(fn: (datasets: { readonly vehicles: unknown[] }) => void): void;
onServerListening(fn: (info: { readonly port: number }) => void): void;
readonly profile: {
onRefresh(fn: (profile: unknown, userId: string) => void): void;
};
};
readonly routes: {
readonly http: {
register(subPath: string, fn: () => { status: number; contentType: string; body: string }): void;
};
};
}) {
let vehicleCount = 0;
ctx.hooks.onDatasetsLoaded((datasets) => {
vehicleCount = datasets.vehicles.length;
ctx.logger.info(`observed ${vehicleCount} vehicles in merged dataset`);
});
ctx.hooks.profile.onRefresh((_profile, userId) => {
const store = ctx.storage.forPlayer(userId);
const prev = store.read<ModState>() ?? { refreshes: 0, lastUpdated: '' };
store.write({ refreshes: prev.refreshes + 1, lastUpdated: new Date().toISOString() });
});
ctx.hooks.onServerListening(({ port }) => {
ctx.logger.info(`custom status endpoint ready at http://127.0.0.1:${port}/mods/${ctx.manifest.id}/status`);
});
ctx.routes.http.register('/status', () => ({
status: 200,
contentType: 'application/json; charset=utf-8',
body: JSON.stringify({
modId: ctx.manifest.id,
version: ctx.manifest.version,
apiVersion: ctx.apiVersion,
vehicleCount,
}),
}));
},
};
@@ -0,0 +1,12 @@
// Incremental BLK patch applied to char.vromfs.bin config/wpcost.blk.
// Only touches the target vehicle block so other mods editing different vehicles stack cleanly.
{
"ops": [
{
"op": "setParam",
"path": ["us_m2a4"],
"name": "rewardMulHistorical",
"value": { "type": "real", "value": 1.2 }
}
]
}
@@ -0,0 +1,2 @@
"<ID|readonly|noverify>";"<English>";"<Chinese>";"<HChinese>"
"us_m2a4_shop";"M2A4 (Modded)";"M2A4(模组示例)";"M2A4(模組示例)"
1 <ID|readonly|noverify> <English> <Chinese> <HChinese>
2 us_m2a4_shop M2A4 (Modded) M2A4(模组示例) M2A4(模組示例)
@@ -0,0 +1,18 @@
// Example additive data mod: adjusts battle rewards via server tuning, patches a stock
// vehicle's economy block in char.vromfs.bin, and updates a localization label in lang.vromfs.bin.
{
"format": 1,
"id": "example.vehicle-tweak",
"name": {
"zh-CN": "示例:载具数值与收益微调",
"en": "Example: Vehicle & Economy Tweak"
},
"version": "0.1.0",
"author": "WTOffline",
"description": {
"zh-CN": "演示零代码叠加:修改对局收益倍率、增量修补 wpcost.blk 与本地化词条。",
"en": "Demonstrates code-free stacking: battle reward tuning, incremental wpcost.blk patching, and localization CSV merging."
},
"api_version": "0.1-experimental",
"game_versions": ["2.61.0.*"]
}
@@ -0,0 +1,5 @@
// Server tuning overlay: multiplies Silver Lions and Research Points rewards by 1.5x.
{
"rewardMultiplierSilverLions": 1.5,
"rewardMultiplierResearchPoints": 1.5
}
@@ -0,0 +1 @@
@import "missions\mapPreferences.css"
@@ -0,0 +1,20 @@
// Register the Custom Map Pool Selector DaGui stylesheet in the root CSS manifest.
{
"id": "official-map-selector/register-css",
"title": "Include wtomapselector.css in gui/css.css",
"features": [
"Custom Map Pool Selector"
],
"variants": [
{
"written_for": "2.61.0.58",
"file": "gui/css.css",
"edits": [
{
"find": "find-css.css",
"replace": "replace-css.css"
}
]
}
]
}
@@ -0,0 +1,2 @@
@import "missions\mapPreferences.css"
@import "missions\wtomapselector.css"
@@ -0,0 +1,4 @@
function updateButtons() {
let wikiLinkBtn = showObjById("wiki_link", hasFeature("AllowExternalLink"), this.scene)
wikiLinkBtn.link = getCurCircuitOverride("wikiMatchmakerURL", loc("url/wiki_matchmaker"))
}
@@ -0,0 +1,3 @@
from "dagor.workcycle" import defer
import "%scripts/missions/mapPreferencesModal.nut" as mapPreferencesModal
import "%scripts/missions/mapPreferencesParams.nut" as mapPreferencesParams
@@ -0,0 +1,25 @@
// Wire the Custom Map Pool button in GameModeSelect to open the native WtoMapSelectorModal
// for the currently selected game mode and display the target mode name on the button.
{
"id": "official-map-selector/mode-select-button-script",
"title": "Wire Custom Map Pool button in GameModeSelect handler",
"features": [
"Custom Map Pool Selector"
],
"variants": [
{
"written_for": "2.61.0.58",
"file": "scripts/gamemodes/gamemodeselect.nut",
"edits": [
{
"find": "find-imports.nut",
"replace": "replace-imports.nut"
},
{
"find": "find-buttons.nut",
"replace": "replace-buttons.nut"
}
]
}
]
}
@@ -0,0 +1,31 @@
function updateButtons() {
let wikiLinkBtn = showObjById("wiki_link", hasFeature("AllowExternalLink"), this.scene)
wikiLinkBtn.link = getCurCircuitOverride("wikiMatchmakerURL", loc("url/wiki_matchmaker"))
this.updateWtoMapSelectorButton()
}
function updateWtoMapSelectorButton() {
let btnObj = this.scene.findObject("wto_map_selector_button")
if (!checkObj(btnObj))
return
let curGm = getCurrentGameMode()
let hasMode = curGm != null
btnObj.show(hasMode)
btnObj.enable(hasMode)
if (!hasMode)
return
let modeTitle = (curGm?.getText != null) ? curGm.getText() : (curGm?.id ?? "")
btnObj.setValue(modeTitle != ""
? loc("wto/mapSelector/btnWithMode", { mode = modeTitle })
: loc("wto/mapSelector/btnTitle"))
btnObj.tooltip = modeTitle != ""
? loc("wto/mapSelector/btnTooltipWithMode", { mode = modeTitle })
: loc("wto/mapSelector/btnTooltip")
}
function onOpenWtoMapSelector(_obj) {
let curGm = getCurrentGameMode()
if (curGm == null)
return
wtoMapSelectorModal.open({ gameMode = curGm })
}
@@ -0,0 +1,4 @@
from "dagor.workcycle" import defer
import "%scripts/missions/mapPreferencesModal.nut" as mapPreferencesModal
import "%scripts/missions/mapPreferencesParams.nut" as mapPreferencesParams
import "%scripts/missions/wtomapselectormodal.nut" as wtoMapSelectorModal
@@ -0,0 +1,7 @@
Button_text {
id:t='back_button'
text:t = '#mainmenu/btnBack'
_on_click:t = 'goBack'
btnName:t='B'
ButtonImg {}
}
@@ -0,0 +1,20 @@
// Add the Custom Map Pool button on the right side of the Mode Selection footer bar.
{
"id": "official-map-selector/mode-select-button-tpl",
"title": "Add Custom Map Pool button to Mode Selection template",
"features": [
"Custom Map Pool Selector"
],
"variants": [
{
"written_for": "2.61.0.58",
"file": "gui/gamemodeselect/gamemodeselect.tpl",
"edits": [
{
"find": "find-nav-right.tpl",
"replace": "replace-nav-right.tpl"
}
]
}
]
}
@@ -0,0 +1,16 @@
Button_text {
id:t='wto_map_selector_button'
text:t='#wto/mapSelector/btnTitle'
tooltip:t='#wto/mapSelector/btnTooltip'
on_click:t='onOpenWtoMapSelector'
visualStyle:t='secondary'
ButtonImg {}
}
Button_text {
id:t='back_button'
text:t = '#mainmenu/btnBack'
_on_click:t = 'goBack'
btnName:t='B'
ButtonImg {}
}
@@ -0,0 +1,104 @@
wtoMapCard {
behavior: button;
snd_click: click;
width: 1@mapPreferenceIconSize + 2@blockInterval;
flow: vertical;
margin: 1@mapPreferenceIconMargin, 1@blockInterval;
padding: 1@blockInterval;
background-color: #36101418;
border: yes;
border-color: #38ffffff;
css-hier-invalidate: yes;
}
wtoMapCard:hover {
background-color: #58202c38;
border-color: @hoverMenuButtonColor;
}
[wtoFilterMode=include] wtoMapCard[wtoSelected=yes] {
background-color: #48184222;
border-color: @checkBoxLikedCheckColor;
}
[wtoFilterMode=exclude] wtoMapCard[wtoSelected=yes] {
background-color: #484a1818;
border-color: @checkBoxBannedCheckColor;
}
[wtoFilterMode=all] wtoMapCard[wtoSelected=yes] {
background-color: #3a243242;
border-color: #88b8d8ff;
}
wtoMapThumb {
size: 1@mapPreferenceIconSize, 1@mapPreferenceIconSize;
position: relative;
background-color: #cccccc;
input-transparent: yes;
css-hier-invalidate: yes;
}
wtoMapCard:hover > wtoMapThumb,
wtoMapCard[wtoSelected=yes] > wtoMapThumb {
background-color: @white;
}
wtoMapCheckBox {
position: absolute;
pos: pw - w - 4@dp, 4@dp;
size: 1@checkboxImgSize, 1@checkboxImgSize;
border: yes;
background-color: #c8101418;
border-color: @checkboxBorderColor;
input-transparent: yes;
css-hier-invalidate: yes;
}
wtoMapCheckIcon {
position: relative;
pos: 0.5pw - 0.5w, 0.5ph - 0.5h;
size: 1@checkboxImgSize - 4@dp, 1@checkboxImgSize - 4@dp;
background-svg-size: 1@checkboxImgSize - 4@dp, 1@checkboxImgSize - 4@dp;
display: hide;
input-transparent: yes;
}
[wtoFilterMode=include] wtoMapCard[wtoSelected=yes] wtoMapCheckBox {
border-color: @checkBoxLikedCheckColor;
}
[wtoFilterMode=include] wtoMapCard[wtoSelected=yes] wtoMapCheckIcon {
display: show;
background-image: #ui/gameuiskin#check.svg;
background-color: @checkBoxLikedCheckColor;
}
[wtoFilterMode=exclude] wtoMapCard[wtoSelected=yes] wtoMapCheckBox {
border-color: @checkBoxBannedCheckColor;
}
[wtoFilterMode=exclude] wtoMapCard[wtoSelected=yes] wtoMapCheckIcon {
display: show;
background-image: #ui/gameuiskin#ban_icon.svg;
background-color: @checkBoxBannedCheckColor;
}
[wtoFilterMode=all] wtoMapCard[wtoSelected=yes] wtoMapCheckIcon {
display: show;
background-image: #ui/gameuiskin#check.svg;
background-color: @commonTextColor;
}
wtoMapCard > textareaNoTab {
width: 1@mapPreferenceIconSize;
font: @fontSmall;
color: @commonTextColor;
margin-top: 1@blockInterval;
input-transparent: yes;
}
wtoMapCard:hover > textareaNoTab,
wtoMapCard[wtoSelected=yes] > textareaNoTab {
color: @highlightedTextColor;
}
@@ -0,0 +1,35 @@
<<#cards>>
wtoMapCard {
id:t='card_<<idx>>'
wtoMapKey:t='<<mapId>>'
wtoSelected:t='<<#isSelected>>yes<</isSelected>><<^isSelected>>no<</isSelected>>'
on_click:t='onToggleMapCard'
on_hover:t='onHoverMapCard'
wtoMapThumb {
background-image:t='<<image>>'
wtoMapCheckBox {
wtoMapCheckIcon {}
}
<<#variantBadge>>
textareaNoTab {
padding:t='4@sf/@pf, 0'
valign:t='bottom'
style:t='color:@white'
background-color:t='@blurBgrColor'
input-transparent:t='yes'
text:t='<<variantBadge>>'
}
<</variantBadge>>
}
textareaNoTab {
id:t='card_title'
word-wrap:t='no'
pare-text:t='yes'
text:t=''
}
}
<</cards>>
@@ -0,0 +1,265 @@
root {
blur {}
blur_foreground {}
frame {
width:t='0.92@rw'
max-width:t='1@rw'
height:t='1@maxWindowHeight'
class:t='wnd'
css-hier-invalidate:t='yes'
isCenteredUnderLogo:t='yes'
frame_header {
activeText {
id:t='wnd_title'
caption:t='yes'
text:t='<<wndTitle>>'
}
textareaNoTab {
id:t='selected_counter'
position:t='relative'
pos:t='0, 0.5ph-0.5h'
margin-left:t='2@blockInterval'
text:t=''
}
Button_close { id:t='btn_back' }
}
tdiv {
size:t='pw, fh'
flow:t='vertical'
css-hier-invalidate:t='yes'
tdiv {
width:t='pw'
padding:t='1@blockInterval, 1@blockInterval'
flow:t='vertical'
tdiv {
width:t='pw'
flow:t='horizontal'
HorizontalListBox {
id:t='filter_mode_tabs'
position:t='relative'
on_select:t='onFilterModeChange'
shopFilter {
id:t='mode_all'
selected:t='yes'
shopFilterText { text:t='#wto/mapSelector/modeAll' }
}
shopFilter {
id:t='mode_include'
shopFilterText { text:t='#wto/mapSelector/modeInclude' }
}
shopFilter {
id:t='mode_exclude'
shopFilterText { text:t='#wto/mapSelector/modeExclude' }
}
}
}
textareaNoTab {
id:t='filter_mode_hint'
width:t='pw'
smallFont:t='yes'
overlayTextColor:t='silver'
margin-top:t='0.5@blockInterval'
text:t='#wto/mapSelector/hintAll'
}
}
tdiv {
width:t='pw'
padding:t='1@blockInterval, 0'
padding-bottom:t='1@blockInterval'
flow:t='horizontal'
tdiv {
id:t='search_container'
width:t='fw'
margin-right:t='1@blockInterval'
EditBox {
id:t='filter_edit_box'
pos:t='0, 0.5ph-0.5h'
position:t='relative'
width:t='fw'
on_activate:t='onFilterEditBoxActivate'
on_change_value:t='onFilterEditBoxChangeValue'
on_cancel_edit:t='onFilterEditBoxCancel'
text:t=''
edit-hint:t='#wto/mapSelector/searchHint'
}
Button_text {
id:t='filter_edit_cancel_btn'
pos:t='0, 0.5ph-0.5h'
position:t='relative'
class:t='image'
showConsoleImage:t='no'
noMargin:t='yes'
tooltip:t='#mainmenu/btnReset'
on_click:t='onFilterEditBoxCancel'
display:t='hide'
img {
background-image:t='#ui/gameuiskin#btn_close.svg'
}
}
}
Button_text {
id:t='btn_select_all'
text:t='#wto/mapSelector/selectAllVisible'
on_click:t='onSelectAllVisible'
margin-right:t='1@blockInterval'
ButtonImg {}
}
Button_text {
id:t='btn_clear_selection'
text:t='#wto/mapSelector/clearSelection'
on_click:t='onClearSelection'
ButtonImg {}
}
}
rowSeparator {}
tdiv {
size:t='pw, fh'
flow:t='horizontal'
css-hier-invalidate:t='yes'
tdiv {
size:t='fw, ph'
position:t='relative'
tdiv {
id:t='maps_list'
size:t='pw, ph'
flow:t='h-flow'
overflow-y:t='auto'
scrollbarShortcuts:t='yes'
position:t='relative'
css-hier-invalidate:t='yes'
wtoFilterMode:t='all'
}
textAreaCentered {
id:t='empty_list_label'
width:t='0.8pw'
pos:t='0.5pw-0.5w, 0.5ph-0.5h'
position:t='absolute'
text:t='#wto/mapSelector/loading'
}
}
blockSeparator {}
tdiv {
id:t='map_preview'
width:t='1@mapPreferencePreviewSize + 2@framePadding'
height:t='ph'
padding:t='1@framePadding'
flow:t='vertical'
position:t='relative'
css-hier-invalidate:t='yes'
tdiv {
size:t='pw, 1@mapPreferencePreviewSize'
position:t='relative'
img {
id:t='img_preview'
size:t='pw, 1@mapPreferencePreviewSize'
max-width:t='h'
max-height:t='w'
pos:t='0.5pw-0.5w, 0'
position:t='absolute'
background-image:t=''
display:t='hide'
}
tdiv {
id:t='tactical-map'
size:t='pw, 1@mapPreferencePreviewSize'
max-width:t='h'
max-height:t='w'
pos:t='0.5pw-0.5w, 0'
position:t='absolute'
display:t='hide'
tacticalMap {
size:t='pw, ph'
}
}
}
textAreaCentered {
id:t='preview_title'
width:t='pw'
margin-top:t='1@blockInterval'
class:t='active'
text:t=''
}
textAreaCentered {
id:t='preview_variants'
width:t='pw'
smallFont:t='yes'
margin-top:t='0.5@blockInterval'
text:t=''
}
textAreaCentered {
id:t='preview_status'
width:t='pw'
smallFont:t='yes'
overlayTextColor:t='silver'
margin-top:t='0.5@blockInterval'
text:t='#wto/mapSelector/previewHint'
}
}
}
}
navBar {
navLeft {
textareaNoTab {
id:t='footer_summary'
pos:t='0, 0.5ph-0.5h'
position:t='relative'
smallFont:t='yes'
text:t=''
}
}
navRight {
Button_text {
id:t='btn_cancel'
text:t='#wto/mapSelector/btnCancel'
_on_click:t='goBack'
btnName:t='B'
ButtonImg {}
}
Button_text {
id:t='btn_save'
text:t='#wto/mapSelector/btnSave'
on_click:t='onSave'
visualStyle:t='secondary'
btnName:t='A'
ButtonImg {}
}
}
}
}
gamercard_div {}
}
@@ -0,0 +1,488 @@
// Official WTOffline Mod: Native DaGui Custom Map Pool Selector modal.
// Communicates with the local server's wto_mod.map_selector.get and wto_mod.map_selector.set
// matching RPC endpoints and reuses War Thunder's native map thumbnails and setMapPreview.
import "regexp2" as regexp2
from "%scripts/sqDagui/framework/gui_handlers.nut" import register_gui_handler
from "%scripts/baseGuiHandlerWT.nut" import BaseGuiHandlerWT
from "%scripts/sqDagui/framework/handlerType.nut" import handlerType
from "%sqStdLibs/helpers/handyman.nut" import handyman
from "%scripts/missions/mapPreview.nut" import setMapPreview, getMissionBriefingConfig
from "%scripts/missions/missionsText.nut" import getMissionLocName
from "%scripts/events/eventInfo.nut" import getEventEconomicName
from "%scripts/gameModes/gameModeManagerState.nut" import getCurrentGameMode, getGameModeEvent
from "%scripts/popups/popups.nut" import addPopup
from "%scripts/matching/api.nut" import matchingApiFunc
from "%sqstd/string.nut" import trim, utf8ToLower
from "guiMission" import get_meta_mission_info_by_name
from "%scripts/dagui_natives.nut" import get_level_texture, map_to_location
from "%scripts/dagui_library.nut" import *
let { handlersManager } = require("%scripts/baseGuiHandlerManagerWT.nut")
dagui_propid_add_name_id("wtoSelected")
dagui_propid_add_name_id("wtoFilterMode")
dagui_propid_add_name_id("wtoMapKey")
let FILTER_MODES = ["all", "include", "exclude"]
let GROUND_OR_NAVAL_LEVEL_RE = regexp2(@"^av(n|g)")
function resolveMapThumbnail(mapId, missionInfo) {
let levelPath = missionInfo?.level ?? ""
if (levelPath == "")
return ""
let isGroundOrNaval = GROUND_OR_NAVAL_LEVEL_RE.match(mapId)
let rawTex = get_level_texture(levelPath, isGroundOrNaval)
if (rawTex.len() > 1 && rawTex.endswith("*"))
return $"{rawTex.slice(0, -1)}_thumb*"
return rawTex
}
function resolveMapTitle(mapId, sampleMission, missionInfo) {
let byDirectLoc = loc($"location/{mapId}", "")
if (byDirectLoc != "")
return byDirectLoc
let levelPath = missionInfo?.level ?? ""
if (levelPath != "") {
let mappedLocId = map_to_location(levelPath)
if ((mappedLocId ?? "") != "") {
let byMappedLoc = loc($"location/{mappedLocId}", "")
if (byMappedLoc != "")
return byMappedLoc
}
}
if (missionInfo != null) {
let byMissionLoc = getMissionLocName(missionInfo, "locName")
if ((byMissionLoc ?? "") != "")
return byMissionLoc
}
let bySampleId = loc($"missions/{sampleMission}", "")
if (bySampleId != "")
return bySampleId
return mapId
}
let WtoMapSelectorModal = class (BaseGuiHandlerWT) {
wndType = handlerType.MODAL
sceneTplName = "%gui/missions/wtomapselectormodal.tpl"
gameMode = null
modeName = ""
economicName = ""
modeDisplayName = ""
filterMode = "all"
mapsList = null
mapByKey = null
selectedSet = null
focusedMapKey = ""
isLoading = true
isSaving = false
function getSceneTplView() {
let gm = this.gameMode ?? getCurrentGameMode()
this.gameMode = gm
let event = getGameModeEvent(gm)
this.modeName = event?.name ?? gm?.id ?? ""
this.economicName = event != null ? getEventEconomicName(event) : ""
this.modeDisplayName = (gm?.getText != null) ? gm.getText() : this.modeName
let title = this.modeDisplayName != ""
? loc("wto/mapSelector/titleWithMode", { mode = this.modeDisplayName })
: loc("wto/mapSelector/title")
return {
wndTitle = title
}
}
function initScreen() {
this.mapsList = []
this.mapByKey = {}
this.selectedSet = {}
this.focusedMapKey = ""
this.isLoading = true
this.isSaving = false
this.updateActionButtonsState()
this.updateFilterModeUi()
this.updateCounterText()
this.requestMapPool()
}
function requestMapPool() {
if (this.modeName == "" && this.economicName == "") {
this.isLoading = false
this.showEmptyLabel(loc("wto/mapSelector/emptyMode"))
this.updateActionButtonsState()
return
}
this.showEmptyLabel(loc("wto/mapSelector/loading"))
matchingApiFunc("wto_mod.map_selector.get",
Callback(@(resp) this.onMapPoolLoaded(resp), this),
{
modeName = this.modeName
economicName = this.economicName
})
}
function onMapPoolLoaded(resp) {
if (!this.isValid())
return
this.isLoading = false
if ((resp?.error ?? 0) != 0 || !(resp?.ok ?? false)) {
this.showEmptyLabel(loc("wto/mapSelector/loadFailed"))
this.updateActionButtonsState()
return
}
let resolvedMode = resp?.modeName ?? ""
if (resolvedMode != "")
this.modeName = resolvedMode
let serverFilter = resp?.filterMode ?? "all"
this.filterMode = FILTER_MODES.indexof(serverFilter) != null ? serverFilter : "all"
this.selectedSet = {}
foreach (mapId in (resp?.selectedMaps ?? []))
this.selectedSet[mapId] <- true
this.mapsList = []
this.mapByKey = {}
foreach (entry in (resp?.maps ?? [])) {
let mapId = entry?.id ?? ""
if (mapId == "")
continue
let sampleMission = entry?.sampleMission ?? ""
let missionCount = entry?.missionCount ?? 1
let missionInfo = sampleMission != "" ? get_meta_mission_info_by_name(sampleMission) : null
let title = resolveMapTitle(mapId, sampleMission, missionInfo)
let image = resolveMapThumbnail(mapId, missionInfo)
let item = {
idx = 0
mapId = mapId
sampleMission = sampleMission
missionCount = missionCount
title = title
searchKey = utf8ToLower(title)
image = image
variantBadge = missionCount > 1 ? $"{missionCount}x" : ""
isSelected = mapId in this.selectedSet
}
this.mapsList.append(item)
this.mapByKey[mapId] <- item
}
this.mapsList.sort(@(a, b) a.searchKey <=> b.searchKey || a.mapId <=> b.mapId)
foreach (idx, item in this.mapsList)
item.idx = idx
this.syncFilterTabsToState()
this.renderMapCards()
this.updateFilterModeUi()
this.updateCounterText()
this.updateActionButtonsState()
if (this.mapsList.len() > 0)
this.focusMapPreview(this.mapsList[0].mapId)
else
this.showEmptyLabel(loc("wto/mapSelector/emptyMode"))
}
function renderMapCards() {
let listObj = this.scene.findObject("maps_list")
if (!checkObj(listObj))
return
let markup = handyman.renderCached("%gui/missions/wtomapselectorcards.tpl", { cards = this.mapsList })
this.guiScene.replaceContentFromText(listObj, markup, markup.len(), this)
foreach (item in this.mapsList) {
let cardObj = listObj.findObject($"card_{item.idx}")
if (checkObj(cardObj)) {
cardObj.findObject("card_title")?.setValue(item.title)
cardObj.tooltip = item.title
}
}
this.applySearchFilter()
}
function showEmptyLabel(text) {
let labelObj = this.scene.findObject("empty_list_label")
if (!checkObj(labelObj))
return
labelObj.setValue(text)
labelObj.show(text != "")
}
function syncFilterTabsToState() {
let tabsObj = this.scene.findObject("filter_mode_tabs")
if (!checkObj(tabsObj))
return
let idx = FILTER_MODES.indexof(this.filterMode) ?? 0
if (tabsObj.getValue() != idx)
tabsObj.setValue(idx)
}
function onFilterModeChange(obj) {
if (!checkObj(obj))
return
let idx = obj.getValue()
if (idx < 0 || idx >= FILTER_MODES.len())
return
this.filterMode = FILTER_MODES[idx]
this.updateFilterModeUi()
this.updateCounterText()
this.updatePreviewStatusText()
}
function updateFilterModeUi() {
let listObj = this.scene.findObject("maps_list")
if (checkObj(listObj))
listObj.wtoFilterMode = this.filterMode
let hintKey = this.filterMode == "include" ? "wto/mapSelector/hintInclude"
: this.filterMode == "exclude" ? "wto/mapSelector/hintExclude"
: "wto/mapSelector/hintAll"
this.scene.findObject("filter_mode_hint")?.setValue(loc(hintKey))
}
function updateCounterText() {
let selectedCount = this.selectedSet.len()
let totalCount = this.mapsList.len()
let text = loc("wto/mapSelector/counter", {
selected = selectedCount
total = totalCount
})
this.scene.findObject("selected_counter")?.setValue(text)
this.scene.findObject("footer_summary")?.setValue(text)
}
function updateActionButtonsState() {
let hasMaps = !this.isLoading && this.mapsList.len() > 0
let canSave = hasMaps && !this.isSaving
this.scene.findObject("btn_select_all")?.enable(hasMaps)
this.scene.findObject("btn_clear_selection")?.enable(hasMaps)
this.scene.findObject("btn_save")?.enable(canSave)
}
function onToggleMapCard(obj) {
let mapId = obj?.wtoMapKey ?? ""
if (mapId == "" || !(mapId in this.mapByKey))
return
let isNowSelected = !(mapId in this.selectedSet)
if (isNowSelected)
this.selectedSet[mapId] <- true
else
this.selectedSet.$rawdelete(mapId)
let item = this.mapByKey[mapId]
item.isSelected = isNowSelected
obj.wtoSelected = isNowSelected ? "yes" : "no"
// Selecting a map while in "all" mode smoothly switches to Whitelist if user hasn't picked one yet?
// Keep the chosen mode explicit so users never lose track of which filter tab is active.
this.updateCounterText()
this.focusMapPreview(mapId)
}
function onHoverMapCard(obj) {
let mapId = obj?.wtoMapKey ?? ""
if (mapId != "" && mapId != this.focusedMapKey && (mapId in this.mapByKey))
this.focusMapPreview(mapId)
}
function focusMapPreview(mapId) {
let item = this.mapByKey?[mapId]
if (item == null)
return
this.focusedMapKey = mapId
let previewObj = this.scene.findObject("map_preview")
if (!checkObj(previewObj))
return
previewObj.findObject("preview_title")?.setValue(item.title)
previewObj.findObject("preview_variants")?.setValue(
loc("wto/mapSelector/variantsCount", { count = item.missionCount }))
this.updatePreviewStatusText()
let curMission = item.sampleMission != ""
? get_meta_mission_info_by_name(item.sampleMission)
: null
let tacticalObj = previewObj.findObject("tactical-map")
let imgObj = previewObj.findObject("img_preview")
if (curMission != null && checkObj(tacticalObj)) {
let config = getMissionBriefingConfig({ blk = curMission })
setMapPreview(tacticalObj, config)
tacticalObj.show(true)
imgObj?.show(false)
}
else if (checkObj(imgObj)) {
imgObj["background-image"] = item.image
imgObj.show(item.image != "")
tacticalObj?.show(false)
}
}
function updatePreviewStatusText() {
let statusObj = this.scene.findObject("preview_status")
if (!checkObj(statusObj))
return
if (this.focusedMapKey == "" || !(this.focusedMapKey in this.mapByKey)) {
statusObj.setValue(loc("wto/mapSelector/previewHint"))
return
}
let isSelected = this.focusedMapKey in this.selectedSet
let key = !isSelected || this.filterMode == "all"
? "wto/mapSelector/statusNormal"
: this.filterMode == "include"
? "wto/mapSelector/statusIncluded"
: "wto/mapSelector/statusExcluded"
statusObj.setValue(loc(key))
}
function getSearchQuery() {
let editObj = this.scene.findObject("filter_edit_box")
return checkObj(editObj) ? utf8ToLower(trim(editObj.getValue())) : ""
}
function applySearchFilter() {
let listObj = this.scene.findObject("maps_list")
if (!checkObj(listObj))
return
let query = this.getSearchQuery()
local visibleCount = 0
foreach (item in this.mapsList) {
let isVisible = query == "" || item.searchKey.indexof(query) != null || item.mapId.indexof(query) != null
listObj.findObject($"card_{item.idx}")?.show(isVisible)
if (isVisible)
visibleCount++
}
if (this.mapsList.len() == 0)
this.showEmptyLabel(loc("wto/mapSelector/emptyMode"))
else if (visibleCount == 0)
this.showEmptyLabel(loc("wto/mapSelector/noSearchResults"))
else
this.showEmptyLabel("")
}
function onFilterEditBoxChangeValue(obj) {
let value = obj.getValue()
this.scene.findObject("filter_edit_cancel_btn")?.show(value.len() != 0)
this.applySearchFilter()
}
function onFilterEditBoxActivate() {
this.applySearchFilter()
}
function onFilterEditBoxCancel() {
let editObj = this.scene.findObject("filter_edit_box")
if (checkObj(editObj) && editObj.getValue() != "") {
editObj.setValue("")
this.scene.findObject("filter_edit_cancel_btn")?.show(false)
this.applySearchFilter()
}
else
this.goBack()
}
function onSelectAllVisible(_obj) {
let listObj = this.scene.findObject("maps_list")
if (!checkObj(listObj))
return
let query = this.getSearchQuery()
foreach (item in this.mapsList) {
let isVisible = query == "" || item.searchKey.indexof(query) != null || item.mapId.indexof(query) != null
if (!isVisible)
continue
this.selectedSet[item.mapId] <- true
item.isSelected = true
let cardObj = listObj.findObject($"card_{item.idx}")
if (checkObj(cardObj))
cardObj.wtoSelected = "yes"
}
this.updateCounterText()
this.updatePreviewStatusText()
}
function onClearSelection(_obj) {
let listObj = this.scene.findObject("maps_list")
this.selectedSet.clear()
foreach (item in this.mapsList) {
item.isSelected = false
if (checkObj(listObj)) {
let cardObj = listObj.findObject($"card_{item.idx}")
if (checkObj(cardObj))
cardObj.wtoSelected = "no"
}
}
this.updateCounterText()
this.updatePreviewStatusText()
}
function onSave(_obj) {
if (this.isSaving || this.isLoading || this.modeName == "")
return
this.isSaving = true
this.updateActionButtonsState()
let selectedMaps = []
foreach (item in this.mapsList)
if (item.mapId in this.selectedSet)
selectedMaps.append(item.mapId)
matchingApiFunc("wto_mod.map_selector.set",
Callback(@(resp) this.onSaveComplete(resp, selectedMaps.len()), this),
{
modeName = this.modeName
economicName = this.economicName
filterMode = this.filterMode
selectedMaps = selectedMaps
})
}
function onSaveComplete(resp, selectedCount) {
if (!this.isValid())
return
this.isSaving = false
if ((resp?.error ?? 0) != 0 || !(resp?.ok ?? false)) {
this.updateActionButtonsState()
addPopup(loc("wto/mapSelector/title"), loc("wto/mapSelector/saveFailed"), null, null, null, "wto_map_selector_err")
return
}
let modeLabel = this.modeDisplayName != "" ? this.modeDisplayName : this.modeName
let notice = this.filterMode == "include" && selectedCount > 0
? loc("wto/mapSelector/savedInclude", { mode = modeLabel, count = selectedCount })
: this.filterMode == "exclude" && selectedCount > 0
? loc("wto/mapSelector/savedExclude", { mode = modeLabel, count = selectedCount })
: loc("wto/mapSelector/savedAll", { mode = modeLabel })
addPopup(loc("wto/mapSelector/title"), notice, null, null, null, "wto_map_selector_saved")
this.goBack()
}
}
register_gui_handler("WtoMapSelectorModal", WtoMapSelectorModal)
return freeze({
open = function(params = null) {
handlersManager.loadHandler(WtoMapSelectorModal, params ?? {})
}
})
@@ -0,0 +1,32 @@
"<ID|readonly|noverify>";"<English>";"<Chinese>";"<TChinese>";"<HChinese>"
"wto/mapSelector/btnTitle";"Map Pool";"自定义地图池";"自訂地圖池";"自定义地图池"
"wto/mapSelector/btnWithMode";"Map Pool: {mode}";"地图池:{mode}";"地圖池:{mode}";"地图池:{mode}"
"wto/mapSelector/btnTooltip";"Configure custom map pool (whitelist / blacklist) for the current game mode";"为当前游戏模式配置自定义匹配地图池(白名单 / 黑名单)";"為目前遊戲模式設定自訂配對地圖池(白名單 / 黑名單)";"为当前游戏模式配置自定义匹配地图池(白名单 / 黑名单)"
"wto/mapSelector/btnTooltipWithMode";"Configure custom map pool for {mode}";"为「{mode}」配置自定义匹配地图池(白名单 / 无上限黑名单)";"為「{mode}」設定自訂配對地圖池(白名單 / 無上限黑名單)";"为「{mode}」配置自定义匹配地图池(白名单 / 无上限黑名单)"
"wto/mapSelector/title";"Custom Map Pool";"自定义匹配地图池";"自訂配對地圖池";"自定义匹配地图池"
"wto/mapSelector/titleWithMode";"Custom Map Pool - {mode}";"自定义匹配地图池 - {mode}";"自訂配對地圖池 - {mode}";"自定义匹配地图池 - {mode}"
"wto/mapSelector/counter";"Selected: {selected} / {total}";"已选:{selected} / {total}";"已選:{selected} / {total}";"已选:{selected} / {total}"
"wto/mapSelector/modeAll";"All Maps";"全部地图";"全部地圖";"全部地图"
"wto/mapSelector/modeInclude";"Whitelist (Only Selected)";"白名单(仅匹配所选)";"白名單(僅配對所選)";"白名单(仅匹配所选)"
"wto/mapSelector/modeExclude";"Blacklist (Exclude Selected)";"黑名单(排除所选)";"黑名單(排除所選)";"黑名单(排除所选)"
"wto/mapSelector/hintAll";"No restriction. Matchmaker can pick any map in this mode.";"无限制:匹配将从当前模式的全部地图中随机抽取。";"無限制:配對將從目前模式的全部地圖中隨機抽取。";"无限制:匹配将从当前模式的全部地图中随机抽取。"
"wto/mapSelector/hintInclude";"Whitelist active: matchmaker only picks from checked maps. If none are checked, all maps are used.";"白名单生效:仅会匹配下方勾选的地图;若未勾选任何地图则回退为全部地图。";"白名單生效:僅會配對下方勾選的地圖;若未勾選任何地圖則回退為全部地圖。";"白名单生效:仅会匹配下方勾选的地图;若未勾选任何地图则回退为全部地图。"
"wto/mapSelector/hintExclude";"Blacklist active: checked maps are never matched (unlimited count, no premium required).";"黑名单生效:已勾选的地图不会被匹配到(无数量限制,无需高级账号)。";"黑名單生效:已勾選的地圖不會被配對到(無數量限制,無需高級帳號)。";"黑名单生效:已勾选的地图不会被匹配到(无数量限制,无需高级账号)。"
"wto/mapSelector/searchHint";"Search maps...";"搜索地图名称...";"搜尋地圖名稱...";"搜索地图名称..."
"wto/mapSelector/selectAllVisible";"Select All Visible";"全选可见";"全選可見";"全选可见"
"wto/mapSelector/clearSelection";"Clear Selection";"清空选择";"清空選擇";"清空选择"
"wto/mapSelector/loading";"Loading map pool...";"正在加载地图列表...";"正在載入地圖清單...";"正在加载地图列表..."
"wto/mapSelector/emptyMode";"This mode does not have a configurable PvP map pool.";"当前模式没有可配置的 PvP 地图池。";"目前模式沒有可設定的 PvP 地圖池。";"当前模式没有可配置的 PvP 地图池。"
"wto/mapSelector/noSearchResults";"No maps match the current search filter.";"没有符合搜索条件的地图。";"沒有符合搜尋條件的地圖。";"没有符合搜索条件的地图。"
"wto/mapSelector/loadFailed";"Failed to load map pool from local server.";"无法从本地服务器加载地图池。";"無法從本機伺服器載入地圖池。";"无法从本地服务器加载地图池。"
"wto/mapSelector/saveFailed";"Failed to save map pool settings.";"保存地图池设置失败。";"儲存地圖池設定失敗。";"保存地图池设置失败。"
"wto/mapSelector/savedAll";"Map pool reset to all maps for {mode}.";"已将「{mode}」恢复为匹配全部地图。";"已將「{mode}」恢復為配對全部地圖。";"已将「{mode}」恢复为匹配全部地图。"
"wto/mapSelector/savedInclude";"Saved whitelist ({count} maps) for {mode}.";"已为「{mode}」保存白名单(共 {count} 张地图)。";"已為「{mode}」儲存白名單(共 {count} 張地圖)。";"已为「{mode}」保存白名单(共 {count} 张地图)。"
"wto/mapSelector/savedExclude";"Saved blacklist ({count} maps) for {mode}.";"已为「{mode}」保存黑名单(排除 {count} 张地图)。";"已為「{mode}」儲存黑名單(排除 {count} 張地圖)。";"已为「{mode}」保存黑名单(排除 {count} 张地图)。"
"wto/mapSelector/variantsCount";"Mission variants: {count}";"包含任务变体:{count} 个";"包含任務變體:{count} 個";"包含任务变体:{count} 个"
"wto/mapSelector/previewHint";"Hover or click a map card to preview its tactical map.";"悬停或点击地图卡片以预览战术地图。";"懸停或點擊地圖卡片以預覽戰術地圖。";"悬停或点击地图卡片以预览战术地图。"
"wto/mapSelector/statusIncluded";"Status: Included in whitelist";"状态:已加入白名单";"狀態:已加入白名單";"状态:已加入白名单"
"wto/mapSelector/statusExcluded";"Status: Excluded by blacklist";"状态:已加入黑名单";"狀態:已加入黑名單";"状态:已加入黑名单"
"wto/mapSelector/statusNormal";"Status: Default";"状态:默认";"狀態:預設";"状态:默认"
"wto/mapSelector/btnSave";"Save";"保存";"儲存";"保存"
"wto/mapSelector/btnCancel";"Cancel";"取消";"取消";"取消"
1 <ID|readonly|noverify> <English> <Chinese> <TChinese> <HChinese>
2 wto/mapSelector/btnTitle Map Pool 自定义地图池 自訂地圖池 自定义地图池
3 wto/mapSelector/btnWithMode Map Pool: {mode} 地图池:{mode} 地圖池:{mode} 地图池:{mode}
4 wto/mapSelector/btnTooltip Configure custom map pool (whitelist / blacklist) for the current game mode 为当前游戏模式配置自定义匹配地图池(白名单 / 黑名单) 為目前遊戲模式設定自訂配對地圖池(白名單 / 黑名單) 为当前游戏模式配置自定义匹配地图池(白名单 / 黑名单)
5 wto/mapSelector/btnTooltipWithMode Configure custom map pool for {mode} 为「{mode}」配置自定义匹配地图池(白名单 / 无上限黑名单) 為「{mode}」設定自訂配對地圖池(白名單 / 無上限黑名單) 为「{mode}」配置自定义匹配地图池(白名单 / 无上限黑名单)
6 wto/mapSelector/title Custom Map Pool 自定义匹配地图池 自訂配對地圖池 自定义匹配地图池
7 wto/mapSelector/titleWithMode Custom Map Pool - {mode} 自定义匹配地图池 - {mode} 自訂配對地圖池 - {mode} 自定义匹配地图池 - {mode}
8 wto/mapSelector/counter Selected: {selected} / {total} 已选:{selected} / {total} 已選:{selected} / {total} 已选:{selected} / {total}
9 wto/mapSelector/modeAll All Maps 全部地图 全部地圖 全部地图
10 wto/mapSelector/modeInclude Whitelist (Only Selected) 白名单(仅匹配所选) 白名單(僅配對所選) 白名单(仅匹配所选)
11 wto/mapSelector/modeExclude Blacklist (Exclude Selected) 黑名单(排除所选) 黑名單(排除所選) 黑名单(排除所选)
12 wto/mapSelector/hintAll No restriction. Matchmaker can pick any map in this mode. 无限制:匹配将从当前模式的全部地图中随机抽取。 無限制:配對將從目前模式的全部地圖中隨機抽取。 无限制:匹配将从当前模式的全部地图中随机抽取。
13 wto/mapSelector/hintInclude Whitelist active: matchmaker only picks from checked maps. If none are checked, all maps are used. 白名单生效:仅会匹配下方勾选的地图;若未勾选任何地图则回退为全部地图。 白名單生效:僅會配對下方勾選的地圖;若未勾選任何地圖則回退為全部地圖。 白名单生效:仅会匹配下方勾选的地图;若未勾选任何地图则回退为全部地图。
14 wto/mapSelector/hintExclude Blacklist active: checked maps are never matched (unlimited count, no premium required). 黑名单生效:已勾选的地图不会被匹配到(无数量限制,无需高级账号)。 黑名單生效:已勾選的地圖不會被配對到(無數量限制,無需高級帳號)。 黑名单生效:已勾选的地图不会被匹配到(无数量限制,无需高级账号)。
15 wto/mapSelector/searchHint Search maps... 搜索地图名称... 搜尋地圖名稱... 搜索地图名称...
16 wto/mapSelector/selectAllVisible Select All Visible 全选可见 全選可見 全选可见
17 wto/mapSelector/clearSelection Clear Selection 清空选择 清空選擇 清空选择
18 wto/mapSelector/loading Loading map pool... 正在加载地图列表... 正在載入地圖清單... 正在加载地图列表...
19 wto/mapSelector/emptyMode This mode does not have a configurable PvP map pool. 当前模式没有可配置的 PvP 地图池。 目前模式沒有可設定的 PvP 地圖池。 当前模式没有可配置的 PvP 地图池。
20 wto/mapSelector/noSearchResults No maps match the current search filter. 没有符合搜索条件的地图。 沒有符合搜尋條件的地圖。 没有符合搜索条件的地图。
21 wto/mapSelector/loadFailed Failed to load map pool from local server. 无法从本地服务器加载地图池。 無法從本機伺服器載入地圖池。 无法从本地服务器加载地图池。
22 wto/mapSelector/saveFailed Failed to save map pool settings. 保存地图池设置失败。 儲存地圖池設定失敗。 保存地图池设置失败。
23 wto/mapSelector/savedAll Map pool reset to all maps for {mode}. 已将「{mode}」恢复为匹配全部地图。 已將「{mode}」恢復為配對全部地圖。 已将「{mode}」恢复为匹配全部地图。
24 wto/mapSelector/savedInclude Saved whitelist ({count} maps) for {mode}. 已为「{mode}」保存白名单(共 {count} 张地图)。 已為「{mode}」儲存白名單(共 {count} 張地圖)。 已为「{mode}」保存白名单(共 {count} 张地图)。
25 wto/mapSelector/savedExclude Saved blacklist ({count} maps) for {mode}. 已为「{mode}」保存黑名单(排除 {count} 张地图)。 已為「{mode}」儲存黑名單(排除 {count} 張地圖)。 已为「{mode}」保存黑名单(排除 {count} 张地图)。
26 wto/mapSelector/variantsCount Mission variants: {count} 包含任务变体:{count} 个 包含任務變體:{count} 個 包含任务变体:{count} 个
27 wto/mapSelector/previewHint Hover or click a map card to preview its tactical map. 悬停或点击地图卡片以预览战术地图。 懸停或點擊地圖卡片以預覽戰術地圖。 悬停或点击地图卡片以预览战术地图。
28 wto/mapSelector/statusIncluded Status: Included in whitelist 状态:已加入白名单 狀態:已加入白名單 状态:已加入白名单
29 wto/mapSelector/statusExcluded Status: Excluded by blacklist 状态:已加入黑名单 狀態:已加入黑名單 状态:已加入黑名单
30 wto/mapSelector/statusNormal Status: Default 状态:默认 狀態:預設 状态:默认
31 wto/mapSelector/btnSave Save 保存 儲存 保存
32 wto/mapSelector/btnCancel Cancel 取消 取消 取消
@@ -0,0 +1,19 @@
// Official bundled additive mod: Custom Map Pool Selector.
// Adds a native DaGui map pool selector modal to the Mode Selection UI and enforces per-mode
// whitelist / unlimited blacklist rules during local battle matchmaking.
{
"format": 1,
"id": "official.map-selector",
"name": {
"zh-CN": "官方模组:自定义匹配地图池",
"en": "Official Mod: Custom Map Pool Selector"
},
"version": "0.1.0",
"author": "WTOffline",
"description": {
"zh-CN": "在模式选择界面新增自定义地图池弹窗,支持按模式设置全部地图、白名单(仅匹配所选)或无上限黑名单(排除所选),并附带原生小地图预览。",
"en": "Adds a native Custom Map Pool modal to the Mode Selection screen with per-mode All, Whitelist (only selected), and unlimited Blacklist (exclude selected) rules plus native map thumbnails."
},
"api_version": "0.1-experimental",
"game_versions": ["2.61.0.*"]
}
@@ -0,0 +1,420 @@
/**
* Official WTOffline Mod: Custom Map Pool Selector (`official.map-selector`).
*
* Indexes each offered PvP game mode's playable two-sided missions grouped by location/level id,
* exposes matching RPC endpoints (`wto_mod.map_selector.get` / `wto_mod.map_selector.set`) backed
* by per-account isolated mod storage, and enforces whitelist/blacklist rules via
* `battle.onFilterMissions`.
*/
type FilterMode = 'all' | 'include' | 'exclude';
interface ModeMapRule {
filterMode: FilterMode;
selectedMaps: string[];
}
interface PlayerMapSelectorStore {
version: 1;
modes: Record<string, ModeMapRule>;
}
interface MissionSlotsView {
readonly teamA: number;
readonly teamB: number;
}
interface MissionHeaderView {
readonly name: string;
readonly path: string;
readonly level?: string;
readonly playerSlots?: MissionSlotsView;
}
interface GameModeDeclarationView {
readonly gameModeId: number;
readonly name: string;
readonly tag?: string;
readonly economicName: string;
readonly displayType?: string;
}
interface OfferedGameModeView {
readonly declaration: GameModeDeclarationView;
readonly missions: readonly MissionHeaderView[];
}
interface GameModesCatalogueView {
ids(): number[];
byId(id: number): OfferedGameModeView | undefined;
byName(name: string): OfferedGameModeView | undefined;
byEconomicName(economicName: string): readonly OfferedGameModeView[];
}
interface MapPoolItem {
readonly id: string;
readonly sampleMission: string;
readonly missionCount: number;
}
interface ModeMapPool {
readonly modeName: string;
readonly economicName: string;
readonly maps: readonly MapPoolItem[];
readonly mapIdSet: ReadonlySet<string>;
}
interface BattleMissionCandidateView {
readonly name: string;
readonly path: string;
readonly level?: string;
}
interface BattleFilterContextView {
readonly userId: string;
readonly modeId: number;
readonly modeName: string;
readonly economicName: string;
readonly minMrank: number;
readonly maxMrank: number;
readonly missions: readonly BattleMissionCandidateView[];
}
interface ModMatchingRequestView {
readonly method: string;
readonly params: Readonly<Record<string, unknown>>;
readonly userId: string | undefined;
}
interface ServerModContextView {
readonly logger: {
info(message: string): void;
warn(message: string): void;
error(message: string): void;
};
readonly storage: {
forPlayer(userId: string): {
read<T = unknown>(): T | undefined;
write(value: unknown): void;
};
};
readonly hooks: {
onCataloguesReady(handler: (catalogues: { readonly gameModes: unknown }) => void): void;
readonly battle: {
onFilterMissions(
handler: (ctx: BattleFilterContextView) => readonly BattleMissionCandidateView[] | void,
): void;
};
};
readonly routes: {
readonly matching: {
register(method: string, handler: (request: ModMatchingRequestView) => Record<string, unknown>): void;
};
};
}
const VALID_FILTER_MODES = new Set<FilterMode>(['all', 'include', 'exclude']);
/**
* Normalize a mission's `level` path (e.g. `levels/avg_poland.bin`) into a lowercase location id
* (`avg_poland`). Falls back to the mission name when `level` is absent.
*/
function normalizeMapId(level: string | undefined, missionName: string): string {
const raw = typeof level === 'string' ? level.trim() : '';
if (raw.length > 0) {
const unified = raw.replaceAll('\\', '/');
const slashIdx = unified.lastIndexOf('/');
const baseName = slashIdx >= 0 ? unified.slice(slashIdx + 1) : unified;
const withoutBin = baseName.toLowerCase().endsWith('.bin')
? baseName.slice(0, -4)
: baseName;
const normalized = withoutBin.trim().toLowerCase();
if (normalized.length > 0) return normalized;
}
return missionName.trim().toLowerCase();
}
function isTwoSidedMission(mission: MissionHeaderView): boolean {
if (!mission.playerSlots) return true;
return mission.playerSlots.teamA > 0 && mission.playerSlots.teamB > 0;
}
function isGameModesCatalogue(value: unknown): value is GameModesCatalogueView {
if (typeof value !== 'object' || value === null) return false;
const candidate = value as Record<string, unknown>;
return (
typeof candidate.ids === 'function' &&
typeof candidate.byId === 'function' &&
typeof candidate.byName === 'function' &&
typeof candidate.byEconomicName === 'function'
);
}
function sanitizeFilterMode(raw: unknown): FilterMode | undefined {
if (typeof raw !== 'string') return undefined;
const lowered = raw.trim().toLowerCase() as FilterMode;
return VALID_FILTER_MODES.has(lowered) ? lowered : undefined;
}
function sanitizeSelectedMaps(raw: unknown): string[] {
if (!Array.isArray(raw)) return [];
const seen = new Set<string>();
const out: string[] = [];
for (const item of raw) {
if (typeof item !== 'string') continue;
const id = item.trim().toLowerCase();
if (id.length === 0 || seen.has(id)) continue;
seen.add(id);
out.push(id);
}
return out;
}
function readPlayerStore(
storage: ServerModContextView['storage'],
userId: string,
): PlayerMapSelectorStore {
const raw = storage.forPlayer(userId).read<unknown>();
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
return { version: 1, modes: {} };
}
const obj = raw as Record<string, unknown>;
const rawModes = obj.modes;
if (typeof rawModes !== 'object' || rawModes === null || Array.isArray(rawModes)) {
return { version: 1, modes: {} };
}
const modes: Record<string, ModeMapRule> = {};
for (const [modeKey, entry] of Object.entries(rawModes as Record<string, unknown>)) {
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) continue;
const rec = entry as Record<string, unknown>;
const filterMode = sanitizeFilterMode(rec.filterMode) ?? 'all';
const selectedMaps = sanitizeSelectedMaps(rec.selectedMaps);
modes[modeKey] = { filterMode, selectedMaps };
}
return { version: 1, modes };
}
function buildModePools(gameModes: GameModesCatalogueView): {
readonly byModeName: Map<string, ModeMapPool>;
readonly byEconomicName: Map<string, ModeMapPool>;
} {
const byModeName = new Map<string, ModeMapPool>();
const byEconomicName = new Map<string, ModeMapPool>();
// Group offered PvP modes by their primary mode name, keeping primary (untagged) modes first
// so sample missions come from the classic pool before sub-mode additions.
const groupedModes = new Map<string, OfferedGameModeView[]>();
for (const id of gameModes.ids()) {
const offered = gameModes.byId(id);
if (!offered) continue;
if (offered.declaration.displayType === 'pve_battle') continue;
const key = offered.declaration.name;
const bucket = groupedModes.get(key) ?? [];
bucket.push(offered);
groupedModes.set(key, bucket);
}
for (const [modeName, modes] of groupedModes) {
modes.sort((left, right) => {
const leftTagged = left.declaration.tag ? 1 : 0;
const rightTagged = right.declaration.tag ? 1 : 0;
return leftTagged - rightTagged || left.declaration.gameModeId - right.declaration.gameModeId;
});
const economicName = modes[0]!.declaration.economicName;
const byMapId = new Map<string, { sampleMission: string; missionNames: Set<string> }>();
for (const offered of modes) {
for (const mission of offered.missions) {
if (!isTwoSidedMission(mission)) continue;
const mapId = normalizeMapId(mission.level, mission.name);
const existing = byMapId.get(mapId);
if (existing) {
existing.missionNames.add(mission.name);
} else {
byMapId.set(mapId, {
sampleMission: mission.name,
missionNames: new Set([mission.name]),
});
}
}
}
if (byMapId.size === 0) continue;
const maps: MapPoolItem[] = [...byMapId.entries()]
.sort(([leftId], [rightId]) => leftId.localeCompare(rightId))
.map(([id, info]) => ({
id,
sampleMission: info.sampleMission,
missionCount: info.missionNames.size,
}));
const pool: ModeMapPool = {
modeName,
economicName,
maps,
mapIdSet: new Set(maps.map((item) => item.id)),
};
byModeName.set(modeName, pool);
if (!byEconomicName.has(economicName)) {
byEconomicName.set(economicName, pool);
}
}
return { byModeName, byEconomicName };
}
function readOptionalString(params: Readonly<Record<string, unknown>>, key: string): string {
const value = params[key];
return typeof value === 'string' ? value.trim() : '';
}
export default {
setup(ctx: ServerModContextView) {
let poolsByModeName = new Map<string, ModeMapPool>();
let poolsByEconomicName = new Map<string, ModeMapPool>();
const resolvePool = (modeName: string, economicName: string): ModeMapPool | undefined => {
if (modeName) {
const direct = poolsByModeName.get(modeName) ?? poolsByEconomicName.get(modeName);
if (direct) return direct;
}
if (economicName) {
return poolsByEconomicName.get(economicName) ?? poolsByModeName.get(economicName);
}
return undefined;
};
const lookupSavedRule = (
store: PlayerMapSelectorStore,
modeName: string,
economicName: string,
): ModeMapRule | undefined => {
if (modeName && store.modes[modeName]) return store.modes[modeName];
if (economicName && store.modes[economicName]) return store.modes[economicName];
return undefined;
};
ctx.hooks.onCataloguesReady((catalogues) => {
if (!isGameModesCatalogue(catalogues.gameModes)) {
ctx.logger.warn('gameModes catalogue did not match expected shape; map selector pools remain empty');
return;
}
const indexed = buildModePools(catalogues.gameModes);
poolsByModeName = indexed.byModeName;
poolsByEconomicName = indexed.byEconomicName;
ctx.logger.info(`indexed map pools for ${poolsByModeName.size} game modes`);
});
ctx.routes.matching.register('wto_mod.map_selector.get', (request) => {
const userId = request.userId;
if (!userId) {
return {
ok: false,
error: 'AUTH_REQUIRED',
modeName: '',
filterMode: 'all',
selectedMaps: [],
maps: [],
};
}
const requestedMode = readOptionalString(request.params, 'modeName');
const requestedEconomic = readOptionalString(request.params, 'economicName');
const pool = resolvePool(requestedMode, requestedEconomic);
if (!pool) {
return {
ok: true,
modeName: requestedMode || requestedEconomic,
filterMode: 'all',
selectedMaps: [],
maps: [],
};
}
const store = readPlayerStore(ctx.storage, userId);
const saved = lookupSavedRule(store, pool.modeName, pool.economicName);
const filterMode: FilterMode = saved?.filterMode ?? 'all';
const selectedMaps = saved
? saved.selectedMaps.filter((mapId) => pool.mapIdSet.has(mapId))
: [];
return {
ok: true,
modeName: pool.modeName,
economicName: pool.economicName,
filterMode,
selectedMaps,
maps: pool.maps.map((item) => ({
id: item.id,
sampleMission: item.sampleMission,
missionCount: item.missionCount,
})),
};
});
ctx.routes.matching.register('wto_mod.map_selector.set', (request) => {
const userId = request.userId;
if (!userId) {
return { ok: false, error: 'AUTH_REQUIRED' };
}
const requestedMode = readOptionalString(request.params, 'modeName');
const requestedEconomic = readOptionalString(request.params, 'economicName');
const pool = resolvePool(requestedMode, requestedEconomic);
const canonicalMode = pool?.modeName ?? requestedMode;
if (!canonicalMode) {
return { ok: false, error: 'INVALID_MODE' };
}
const filterMode = sanitizeFilterMode(request.params.filterMode);
if (!filterMode) {
return { ok: false, error: 'INVALID_FILTER_MODE' };
}
const rawSelected = sanitizeSelectedMaps(request.params.selectedMaps);
const selectedMaps = pool
? rawSelected.filter((mapId) => pool.mapIdSet.has(mapId))
: rawSelected;
const store = readPlayerStore(ctx.storage, userId);
store.modes[canonicalMode] = { filterMode, selectedMaps };
ctx.storage.forPlayer(userId).write(store);
ctx.logger.info(
`saved map rule for user=${userId} mode=${canonicalMode} filter=${filterMode} selected=${selectedMaps.length}`,
);
return {
ok: true,
modeName: canonicalMode,
filterMode,
selectedMaps,
};
});
ctx.hooks.battle.onFilterMissions((battleCtx) => {
const store = readPlayerStore(ctx.storage, battleCtx.userId);
const rule = lookupSavedRule(store, battleCtx.modeName, battleCtx.economicName);
if (!rule || rule.filterMode === 'all' || rule.selectedMaps.length === 0) {
return undefined;
}
const selectedSet = new Set(rule.selectedMaps);
const filtered = battleCtx.missions.filter((mission) => {
const mapId = normalizeMapId(mission.level, mission.name);
return rule.filterMode === 'include' ? selectedSet.has(mapId) : !selectedSet.has(mapId);
});
if (filtered.length === 0) {
ctx.logger.warn(
`map filter (${rule.filterMode}, ${rule.selectedMaps.length} selected) matched 0/${battleCtx.missions.length} missions for ${battleCtx.modeName} (mrank ${battleCtx.minMrank}..${battleCtx.maxMrank}); falling back to full pool`,
);
return undefined;
}
return filtered;
});
},
};
+124
View File
@@ -0,0 +1,124 @@
# 01 · 快速入门与清单规范
> **适用版本**:`format: 1` · `api_version: "0.1-experimental"`(实验期接口,随本体开发可能调整)
## 1. 核心思路:为什么是「添加式」模组?
WTOffline **不接受**整包覆盖原版 `char.vromfs.bin` / `aces.vromfs.bin` 的旧做法,而是采用**按加载顺序逐层叠加**的架构:
1. 启动游戏前,启动器从纯净原版备份(`wtoffline/stock/`)出发,先应用离线版核心补丁,再按玩家在「模组」页排好的顺序,依次叠加所有启用模组的客户端补丁与新增文件;
2. 大体积 3D 模型和贴图包通过 **Windows NTFS 目录联接点(Junction)** 跨盘零拷贝挂载;
3. 本地服务器启动时自动读取叠加后的客户端数据包,再按同一顺序合并各模组的 `server/tuning/*.jsonc` 与加载 `server/index.ts` 脚本;
4. 关掉模组或切换预设,启动器自动拆除联接点并还原原版文件,不破坏客户端本体。
- **全局模组仓库**:默认位于 `%APPDATA%\WTOffline Launcher\mods`(可在启动器「模组 › 预设与仓库」修改到任意硬盘)。
- **每客户端独立配置**:开关、加载顺序和命名预设分别保存在各自客户端的数据目录 `mods-config.json` 里。
---
## 2. 5 分钟做出你的第一个模组
1. 在启动器里打开 **「模组 › 打开模组目录」**;
2. 在里面新建文件夹 `my-first-mod`;
3. 创建清单文件 `my-first-mod/mod.jsonc`:
```jsonc
{
"format": 1,
"id": "demo.my-first-mod",
"name": {
"zh-CN": "我的第一个模组",
"en": "My First Mod"
},
"version": "0.1.0",
"author": "YourName",
"description": {
"zh-CN": "把对局银狮和研发点倍率调整为 2 倍。",
"en": "Doubles Silver Lions and Research Points battle rewards."
},
"api_version": "0.1-experimental",
"game_versions": ["2.61.0.*"]
}
```
4. 创建 `my-first-mod/server/tuning/battle.jsonc`:
```jsonc
{
"rewardMultiplierSilverLions": 2.0,
"rewardMultiplierResearchPoints": 2.0
}
```
5. 切回启动器窗口(页面会自动刷新,或点击「刷新」),勾选启用并启动游戏即可生效。
---
## 3. 完整标准目录结构
只创建你用到的目录,未用到的部分完全不必建立:
```text
<mod-folder>/
├─ mod.jsonc # 必需:模组清单
├─ server/ # 可选:服务端部分
│ ├─ tuning/ # 可调数值增量覆盖(*.jsonc)
│ └─ index.ts (或 index.mjs / .js) # 服务端脚本入口(默认自动探测)
└─ client/ # 可选:客户端部分
├─ packs/ # .vromfs.bin 数据包增量叠加
│ ├─ char.vromfs.bin/
│ ├─ aces.vromfs.bin/
│ ├─ gui.vromfs.bin/
│ ├─ lang.vromfs.bin/
│ ├─ mis.vromfs.bin/
│ ├─ game.vromfs.bin/
│ ├─ ui/atlases.vromfs.bin/
│ └─ ui/images.vromfs.bin/
├─ addon/ # 3D 模型与贴图扩展包(res/*.grp, res/*.dxp.bin)
├─ gui-patches/ # GUI 脚本增量补丁(与本体 patches/gui 同格式)
├─ exe-patches/ # 声明式 exe 补丁(与本体 patches/exe 同格式)
├─ files/ # 可选:大型整合包附带的配套涂装/瞄具/音效/任务
└─ config-blk.patch.jsonc # 可选:游戏根目录 config.blk 的增量补丁
```
---
## 4. `mod.jsonc` 全字段参考
清单元数据解析采用**严格白名单校验**,写错字段名或出现未定义字段会被拒绝并在启动器报错区显示具体原因。
| 字段 | 必填 | 类型 | 说明 |
| --- | --- | --- | --- |
| `format` | 是 | `1` | 清单格式版本号,目前固定为整数 `1` |
| `id` | 是 | `string` | 全局唯一模组 ID,仅允许小写字母、数字、`.`、`_`、`-`,首字符须为字母或数字,最长 64 位(推荐 `<作者>.<模组名>`) |
| `name` | 是 | `string \| { [lang]: string }` | 展示名称,支持字符串或按语言代码映射(如 `zh-CN`、`en`) |
| `version` | 是 | `string` | 模组版本号(推荐语义化版本,如 `0.1.0`) |
| `author` | 是 | `string` | 作者或制作组名称 |
| `description` | 否 | `string \| { [lang]: string }` | 模组简介,支持多语言对象 |
| `api_version` | 是 | `string` | 目标接口标识,当前固定填 `"0.1-experimental"` |
| `game_versions` | 否 | `string[]` | 声明适配的游戏版本通配符列表(如 `["2.61.0.*"]`);与客户端版本不符时仅警告,不强行阻断 |
| `requires` | 否 | `string[]` | 前置依赖模组 ID 列表;缺失或未启用时作为**阻塞错误**阻止启动 |
| `conflicts` | 否 | `string[]` | 已知互斥模组 ID 列表;同时启用时作为**阻塞错误**阻止启动 |
| `load_after` | 否 | `string[]` | 建议排在这些模组 ID 之后(越靠后优先级越高);供启动器「按依赖自动排序」使用 |
| `load_before` | 否 | `string[]` | 建议排在这些模组 ID 之前 |
| `server` | 否 | `{ entry?: string, tuning?: string }` | 显式覆盖服务端入口文件(相对路径,不得含 `..`)和 `tuning` 目录路径(默认自动探测 `server/index.{ts,mjs,js}` 与 `server/tuning`) |
---
## 5. 启动器自动计算的能力与风险徽标
启动器扫描模组目录后会自动标注以下徽标,帮助玩家判断安全性:
- **数据/资源(`data`)**:仅包含 `server/tuning`、`client/packs`、`client/addon`、`client/files`、`config-blk.patch.jsonc`;
- **界面补丁(`gui`)**:包含 `client/gui-patches/`;
- **服务端脚本(`script`)**:包含可执行服务端 JS/TS 脚本;
- **二进制补丁(`exe`)**:包含 `client/exe-patches/`(高风险,且受核心隔离补丁锁保护)。
---
## 6. 排序规则与冲突检测
- **优先级**:列表中**越靠下(序号越大)越晚加载、优先级越高**;
- **叠加合并**(提示 `info`):两个模组对同一个 BLK / CSV / `tuning` 文件做增量补丁时,按顺序先后叠加;
- **文件覆写**(警告 `warning`):后序模组用整文件替换了前序模组改过的数据包文件或外置文件;
- **阻塞错误**(错误 `error`):缺少 `requires` 前置、前置未启用、或触发 `conflicts` 互斥时,启动器禁止启动并高亮提示处理。
@@ -0,0 +1,195 @@
# 02 · 客户端数据包与 BLK 增量补丁
大多数战雷模组(魔改载具性能、炮弹穿深、导弹机动、科技树排布、价格权重、新任务、新译名、载具图标)都落在游戏的数据包(`.vromfs.bin`)里。本章介绍如何以**完全可叠加、互不顶掉**的方式修改这些数据包。
---
## 1. 支持叠加的 8 个客户端数据包
把文件按目标包名放进 `client/packs/<包路径>/` 下即可:
| 目标目录名 | 常见内容 | 备份方式 |
| --- | --- | --- |
| `client/packs/char.vromfs.bin/` | `config/shop.blk`(科技树)、`config/wpcost.blk`(经济/权重/改装件)、`config/unittags.blk`、`config/items.blk`、`config/modifications.blk` | 常驻备份 |
| `client/packs/aces.vromfs.bin/` | `gamedata/units/.../*.blk`(载具模型/DM/炮塔)、`gamedata/flightmodels/...`(气动)、`gamedata/weapons/...`(武器/炮弹/导弹)、`config/settings.blk` | 常驻备份 |
| `client/packs/gui.vromfs.bin/` | 新增独立 `.nut` 脚本、`.tpl` 模板、`.css` 样式(修改已有脚本请看第 04 章 `gui-patches`) | 常驻备份 |
| `client/packs/lang.vromfs.bin/` | `lang/units.csv`、`lang/menu.csv`、`lang/units_weaponry.csv` 等本地化表 | 按需自动备份,关闭还原 |
| `client/packs/mis.vromfs.bin/` | `gamedata/missions/.../*.blk` 联机/自定义任务 | 按需自动备份,关闭还原 |
| `client/packs/game.vromfs.bin/` | `danetlibs/...`、`game/...` 脚本与配置 | 按需自动备份,关闭还原 |
| `client/packs/ui/atlases.vromfs.bin/` | `gameuiskin/<载具名>_ico.svg`(科技树与本地商城剪影图标) | 按需自动备份,关闭还原 |
| `client/packs/ui/images.vromfs.bin/` | `units/<载具名>.ddsx` 或 `.png`(资料卡/乘员栏载具图) | 按需自动备份,关闭还原 |
> **自动联动服务端**:本地服务器在启动时直接读取叠加后的 `.vromfs.bin`。因此你通过补丁往 `shop.blk` / `wpcost.blk` 新增或修改载具后,服务端会自动识别新车价格、前置科技树、研发点、改装件、权重、AI 池与礼包 GUID,无需手工同步两遍。
---
## 2. 包内文件的 3 种处理模式(按后缀自动识别)
构建器根据你在 `client/packs/<包>/` 下放置的文件名自动决定处理方式:
1. **`<原路径>.patch.jsonc` → BLK 结构化增量补丁**:解析目标 `.blk` 为保留类型的内存树,按 `ops` 逐条修改后重新编码为自包容二进制 BLK 写回;
2. **`<原路径>.patch.csv` → CSV 本地化增量合并**:按第 1 列词条键合并进目标 `.csv`(已有键更新对应语言列,新键追加到表尾);
3. **其余文件(如 `my_tank.blk`、`my_tank_ico.svg`)→ 新增或替换文件**:
- 如果路径以 `.blk` 结尾且你的源文件是**可读文本 BLK**(如从 CDK/解包工具改出来的),构建器会自动将其编译为游戏引擎所需的**二进制 BLK** 写进包内;
- 如果已经是二进制 BLK 或 `.svg` / `.ddsx` / `.nut` / `.tpl`,则原样写入包内。
---
## 3. BLK 增量补丁(`*.blk.patch.jsonc`)完整手册
### 3.1 基本格式与路径寻址
```jsonc
{
"ops": [
// 按顺序执行的操作列表
]
}
```
- `path` 是从 BLK 根节点出发的子块名数组,例如 `["country_usa", "army", "range[0]"]`;
- 同名子块(如 `shop.blk` 里连续多个 `range` 块)可以用 **`名称[索引]`**(0 起始)精确定位,不写索引默认命中第 0 个;
- `[]` 表示根节点本身。
### 3.2 全部 7 种操作(`op`)
#### ① `setParam`:设置参数(存在则覆盖并去重,不存在则新增)
```jsonc
{
"op": "setParam",
"path": ["us_m2a4"],
"name": "rewardMulHistorical",
"value": { "type": "real", "value": 1.2 },
"createBlocks": false // 可选,默认 false;设为 true 时自动补建缺失路径子块
}
```
#### ② `addParam`:追加同名参数(不删除已有同名项,适合 `slaveUnit`、`folder`、`aircraftGift` 等重复键)
```jsonc
{
"op": "addParam",
"path": ["country_usa", "army", "range[0]", "us_m2a4"],
"name": "slaveUnit",
"value": "my_extra_launcher"
}
```
#### ③ `removeParam`:删除参数(不填 `value` 删除全部同名参数;填 `value` 只删匹配值)
```jsonc
{
"op": "removeParam",
"path": ["us_m2a4"],
"name": "showOnlyWhenBought"
}
```
#### ④ `upsertBlock`:查找或创建子块,并合并传入的 `params` 与 `blocks`
```jsonc
{
"op": "upsertBlock",
"path": ["country_usa", "army", "range[0]", "my_custom_tank"],
"block": {
"params": [
{ "name": "rank", "value": { "type": "int", "value": 8 } },
{ "name": "reqAir", "value": "us_m1a2_sep2_abrams" }
]
}
}
```
#### ⑤ `addBlock`:在父块下新增一个子块(支持 `before` / `after` 指定插入位置)
```jsonc
{
"op": "addBlock",
"path": ["country_usa", "army", "range[0]"],
"name": "my_custom_tank",
"after": "us_m1a2_sep2_abrams",
"block": {
"params": [
{ "name": "rank", "value": { "type": "int", "value": 8 } }
]
}
}
```
#### ⑥ `removeBlock`:删除指定路径的子块
```jsonc
{
"op": "removeBlock",
"path": ["country_usa", "army", "range[0]", "some_vehicle"]
}
```
#### ⑦ `cloneBlock`:复制同文档里的已有块为新名称并嵌套 `ops` 微调(魔改/衍生新车利器!)
```jsonc
{
"op": "cloneBlock",
"from": ["us_m1a2_sep2_abrams"],
"toParent": [],
"newName": "us_m1a2_mod_example",
"replaceExisting": true,
"ops": [
{ "op": "setParam", "path": [], "name": "value", "value": { "type": "int", "value": 10000 } },
{ "op": "setParam", "path": [], "name": "reqExp", "value": { "type": "int", "value": 50000 } },
{ "op": "setParam", "path": [], "name": "economicRankHistorical", "value": { "type": "int", "value": 34 } }
]
}
```
> 注意:`cloneBlock` 内部的嵌套 `ops` 是以**克隆出来的新块为根节点**(所以改它自身字段时 `path` 写 `[]`)。
### 3.3 全部 13 种 BLK 数据类型写法
直接写 JS 原始值时,构建器会优先沿用原字段的 BLK 类型(找不到原字段时:字符串→`string`,布尔→`bool`,整数→`int`,小数→`real`)。需要强制指定类型时,写 `{ "type": "<类型>", "value": <值> }`:
| `type` | BLK 文本后缀 | `value` 示例 |
| --- | --- | --- |
| `string` | `:t` | `"us_m2a4"` |
| `int` | `:i` | `120` |
| `real` | `:r` | `1.5`(即使数值为 `2`,也会严格按浮点写入) |
| `bool` | `:b` | `true` / `false` |
| `int64` | `:i64` | `"133700000000000000"` 或整数 |
| `point2` | `:p2` | `[1.0, 2.5]` |
| `point3` | `:p3` | `[0.0, 1.5, -2.0]` |
| `point4` | `:p4` | `[0.0, 1.0, 0.0, 1.0]` |
| `ipoint2` | `:ip2` | `[10, 20]` |
| `ipoint3` | `:ip3` | `[1, 2, 3]` |
| `ipoint4` | `:ip4` | `[0, 1, 2, 3]` |
| `color` | `:c` | `[255, 128, 0, 255]`(`[r, g, b, a]`)或打包整数 `0xAARRGGBB` |
| `matrix` | `:m` | 12 个浮点数的数组(4 行 × 3 列) |
---
## 4. CSV 本地化增量合并(`*.csv.patch.csv`)
在 `client/packs/lang.vromfs.bin/lang/` 下放置与原文件同名加 `.patch.csv` 的文件(如 `units.csv.patch.csv`、`menu.csv.patch.csv`):
```csv
"<ID|readonly|noverify>";"<English>";"<Chinese>";"<HChinese>"
"my_custom_tank_shop";"M1A2 Mod";"M1A2 魔改型";"M1A2 魔改型"
"my_custom_tank_0";"M1A2 Mod Experimental";"M1A2 实验魔改型";"M1A2 實驗魔改型"
```
- 必须以分号 `;` 分隔并用双引号包裹字段,第一行写表头列名(只需列出你要填的语言列,缺失语言列会自动留空或保留原值);
- 如果第 1 列 ID 在原表已存在,只更新你提供的非空语言列;不存在则追加到表尾。
---
## 5. 修改游戏根目录 `config.blk`(`client/config-blk.patch.jsonc`)
如果模组需要调整游戏根目录的 `config.blk`(例如开启音效包 `sound{ enable_mod:b=yes }` 或指定自定义机库 `hangarBlk:t="..."`),放一份标准 BLK 补丁到 `client/config-blk.patch.jsonc` 即可:
```jsonc
{
"ops": [
{
"op": "setParam",
"path": ["sound"],
"name": "enable_mod",
"value": { "type": "bool", "value": true },
"createBlocks": true
}
]
}
```
启动器会自动先备份原版 `config.blk` 到 `wtoffline/stock/config.blk`,关掉模组后自动还原。
@@ -0,0 +1,75 @@
# 03 · 添加全新 3D 模型与贴图载具
本章专门讲解如何在 WTOffline 中制作**带自定义 3D 模型(`.grp`)和贴图(`.dxp.bin`)的全新载具模组**,并让多款不同作者的新车模组同时叠加共存、跨盘零拷贝秒挂、关闭即还原。
---
## 1. 引擎加载机制(为什么放 `client/addon/` 就够了)
经对 2.61.0.x 客户端 `aces.exe` 与 `config/settings.blk` 核对:
- 引擎启动时会读取 `aces.vromfs.bin` `config/settings.blk` 中的 `addons`、`addons_no_check` 与 `addonsWithBasePath` 三个列表;
- 凡是路径包含 `/pkg_user/` 的扩展目录,引擎会**跳过 `res/grp_hdr.vromfs.bin` 强制校验,直接扫描 `<目录>/res/` 下的全部 `.grp` 模型与 `.dxp.bin` 贴图包并注册进全局资源管理器**,同时读取里面的 `gamedata/units/unitsList.blk`;
- 如果模组自带正式 War Thunder CDK 编译的 `res/grp_hdr.vromfs.bin`,启动器会自动改挂到 `content/pkg_wto_<modId>` 走原生 `grp_hdr` 路径。
### 跨盘零拷贝挂载(不复制几个 GB 的模型!)
无论全局 `mods/` 目录在 C 盘还是 D 盘、游戏副本在 J 盘,启动器都会用 **Windows NTFS 目录联接点(Junction)** 把你的 `client/addon/` 直接挂载到 `<游戏副本>/content/pkg_user/<安全模组ID>`:
- **不需要管理员权限**;
- **支持跨盘符**;
- **0 字节额外空间、约 1 毫秒完成**;
- 关闭模组时只拆除联接点本身,绝不删改 `mods/` 里的源文件。
---
## 2. 添加一辆全新 3D 模型载具的 6 步清单
假设你的模组 ID 是 `demo.new-mbt`,新车内部 ID 叫 `us_mbt_demo`:
```text
mods/demo-new-mbt/
├─ mod.jsonc
└─ client/
├─ addon/
│ └─ res/
│ ├─ us_mbt_demo.grp # ① 3D 模型、骨架、碰撞体(CDK 导出)
│ └─ us_mbt_demo.dxp.bin # ① 压缩贴图包(DDSx)
└─ packs/
├─ aces.vromfs.bin/
│ └─ gamedata/units/tankmodels/
│ └─ us_mbt_demo.blk # ② 载具物理、装甲、炮塔、武器配置(文本 BLK 自动编译)
├─ char.vromfs.bin/
│ └─ config/
│ ├─ wpcost.blk.patch.jsonc # ③ 价格、研发点、权重、改装件(用 cloneBlock 最快)
│ ├─ shop.blk.patch.jsonc # ④ 挂进对应国家科技树位置
│ └─ unittags.blk.patch.jsonc # ④ 注册载具类型/年代/标签
├─ lang.vromfs.bin/
│ └─ lang/
│ └─ units.csv.patch.csv # ⑤ 中英文名称(_shop、_0、_1、_2)
├─ ui/atlases.vromfs.bin/
│ └─ gameuiskin/
│ └─ us_mbt_demo_ico.svg # ⑥ 科技树与本地商城剪影图标(文件名全小写)
└─ ui/images.vromfs.bin/
└─ units/
└─ us_mbt_demo.ddsx # ⑥ 载具资料卡/乘员栏卡片图(可选,无图时游戏回退占位)
```
### 关键细节提醒
1. **确保 `wpcost.blk` 与 `shop.blk` 的载具块名完全一致**:
- 本地服务器会从叠加后的 `char.vromfs.bin` 自动提取这辆车的研发链、银狮/金鹰/礼包价格、分房权重、改装件与挂载预设;
- 如果在 `wpcost.blk` 里设置了 `gift:t="msi_notebook"`,构建器会自动给这辆新车分配确定性的本地商城 GUID,玩家可以立刻在本地网页商店看到并购买它(还可以在 `server/tuning/store.jsonc` 里给它定自定义 GJN 价格和附赠内容!)。
2. **`ui/atlases.vromfs.bin` 路径大小写**:
- 原版图标包内部路径统一为**全小写**,请把图标命名为 `gameuiskin/<全小写载具id>_ico.svg`。
3. **验证 3D 模型资源名匹配**:
- `gamedata/units/tankmodels/us_mbt_demo.blk` 里的 `model:t="..."` 与 `animChar` 名称必须与 `.grp` 内部导出的资产名一致。
---
## 3. 配套涂装、瞄具、音效与原生目录的边界
- **独立涂装 / 瞄具 / 单人任务**:玩家照旧直接放进游戏目录的 `UserSkins/`、`UserSights/`、`UserMissions/` 即可,**不需要**封装成模组;
- **大型新车整合包附带配套资源**:如果你的新车模组顺手附带了专属涂装、火控瞄具或音效包,可以放进 `client/files/`:
- `client/files/UserSkins/us_mbt_demo_camo/...`(独占子目录 → 跨盘 Junction 零拷贝)
- `client/files/UserSights/us_mbt_demo/...`(独占子目录 → 跨盘 Junction 零拷贝)
- `client/files/sound/mod/my_cannon.bank`(平铺散文件 → 优先符号链接/同盘硬链接,跨盘退化增量缓存)
- **原生文件保护红线**:如果 `client/files/` 中的某路径与玩家自己手动放进 `UserSkins/` / `UserSights/` 的文件重名,启动器会跳过并在日志中提示冲突,**绝不覆盖玩家原生文件**。
+125
View File
@@ -0,0 +1,125 @@
# 04 · 客户端 GUI 补丁与声明式 EXE 补丁
> **实验期提示**:界面脚本补丁(`gui-patches`)与声明式 `exe` 补丁(`exe-patches`)依赖目标游戏客户端的代码结构,游戏更新或本体补丁演进时可能需要同步维护。
---
## 1. 客户端界面扩展的两种组合做法(推荐最佳实践)
如果你要给游戏加一个新界面(例如自带的 `official-map-selector` 地图池弹窗),最佳实践是**“大块逻辑独立新建 + 极简增量补丁挂入口”**:
1. **新增独立的 `.nut` / `.tpl` / `.css` 文件**:直接放进 `client/packs/gui.vromfs.bin/` 下(例如 `scripts/missions/wtoMapSelectorModal.nut`、`gui/missions/wtoMapSelectorModal.tpl`、`gui/missions/wtoMapSelector.css`)。独立文件零冲突、极易维护;
2. **用最小 GUI 增量补丁挂载入口按钮**:把修改原版脚本的几行放进 `client/gui-patches/<补丁名>/`。
> 注意:`gui.vromfs.bin` 内部路径为**全小写**。虽然 Quirrel 的 `import` 路径大小写不敏感,但放进 `client/packs/gui.vromfs.bin/` 的文件名建议保持小写或与原版一致。
---
## 2. `client/gui-patches/` 补丁格式
每个补丁一个子目录,内含 `patch.jsonc` 和引用的原文/替换片段文件:
```text
client/gui-patches/
└─ my-button-patch/
├─ patch.jsonc
├─ find.nut
└─ replace.nut
```
`patch.jsonc` 示例:
```jsonc
// Adds a custom entry button to the mode selection panel.
// Needed because the stock UI has no hook for custom modal windows.
// Without this patch, the custom map selector button is not shown.
{
"id": "my-mod/add-button",
"title": "Add custom button to mode selector",
"features": [],
"variants": [
{
"written_for": "2.61.0.58",
"file": "scripts/gamemodes/gamemodeselect.nut",
"edits": [
{
"find": "find.nut",
"replace": "replace.nut"
}
]
}
]
}
```
### 规则与注意事项
- **执行顺序**:离线版核心 GUI 补丁永远先应用,各模组的 `gui-patches` 在其后按启动器排序依次应用;
- **唯一命中保护**:每条 `edit` 的 `find` 文本必须在目标脚本中**恰好出现 1 次**,否则该补丁整条跳过并写入日志,绝不半应用写坏脚本;
- 替换文本里可以使用占位符 `{{LOCAL_ENDPOINT}}`,构建器会自动替换为当前本地服务器地址(`127.0.0.1:<端口>`);
- **多版本适配**:当游戏版本更新导致原文变化时,只需在 `variants` 数组里追加一个新的写法条目,构建器会自动选取恰好命中的那一条。
### 必做检查:用 Quirrel `compilestring` 做完整字节码检查
战雷使用的 Quirrel 脚本在登录阶段预加载。如果 `.nut` 存在**词法作用域冲突**(例如局部变量和顶部 `from ... import *` 常量重名)、**前向引用未声明函数**、或误用 **Quirrel 保留字(如 `base`)**,会导致登录一直卡在「正在加载」。
只做 AST 语法检查会漏掉这些错误,**必须**用项目匹配的 Quirrel 编译器(`sq.exe`)通过 `compilestring` 跑完整字节码编译:
```powershell
# 示例:用 sq.exe 验证单个 .nut 文件能否通过完整字节码编译
& "build\quirrel-cli\bin\Release\sq.exe" -e "local f = compilestring(readfile('your_script.nut'), 'your_script.nut'); println('OK')"
```
---
## 3. 声明式 `exe` 补丁(`client/exe-patches/`)
模组可以直接复用 WTOffline 本体的 `@wto/exepatch` 引擎对 `win64/aces.exe` 做特征码定位补丁,**严禁直接分发修改后的 `aces.exe`**。
```text
client/exe-patches/
└─ my-tweak/
└─ patch.jsonc
```
`patch.jsonc` 结构:
```jsonc
// Brief description of what this binary patch changes.
// Why the local server cannot do this alone.
// What happens if this patch is skipped.
{
"id": "my-tweak",
"title": "Example declarative exe patch",
"features": [],
"requires": [],
"variants": [
{
"written_for": "2.61.0.58",
"locate": {
"kind": "signature",
"pattern": "48 8B ?? ?? ?? ?? ?? 84 C0 74 ??",
"captures": []
},
"edit": {
"offset": 9,
"asm": "nop; nop",
"bytes": "90 90",
"expect_original": "74 ??",
"fixups": []
}
}
]
}
```
### 定位方式(`locate.kind`)
- `signature`:字节特征码扫描(支持 `??` 通配与 `captures` 捕获偏移/相对跳转目标);
- `string_ref`:按代码引用的固定 ASCII 字符串定位,可附加局部指令特征校验;
- `within`:在依赖补丁或锚点所在的函数范围(按 PE 异常表边界)内搜索局部特征。
### 安全红线与核心补丁锁(不可绕过)
1. **核心离线与隔离补丁永远最先规划并锁定字节区间**(包括不连 Gaijin、不加载反作弊、目录与注册表隔离、禁止拉起官方启动器、本地 TLS/匹配公钥等);
2. **任何模组 `exe` 补丁如果与核心补丁字节重叠,会被构建器硬拒绝**并在日志中报错 `overlaps protected core patch`;
3. 如果两个模组的 `exe` 补丁写入同一段字节,后序补丁会被拒绝并标注冲突模组 ID;
4. 如果当前游戏版本找不到特征码或原字节不匹配,该补丁会被跳过并写入日志,不会导致核心构建崩溃。
+90
View File
@@ -0,0 +1,90 @@
# 05 · 服务端零代码数值叠加(Tuning)
本地服务器把离线版自定的经济、对局、商城、补给箱、兑换码、联队、研发策略等数值统一放进了 **12 份 `.jsonc` 配置文件**。模组作者一行代码都不用写,只需在 `server/tuning/` 下放同名 `.jsonc` 文件即可按字段叠加修改。
---
## 1. 多层合并优先级
从低到高依次合并(后者覆盖前者):
```text
1. 离线版内置默认配置(apps/server/tuning/<名称>.jsonc)
2. 已启用模组 1 的 server/tuning/<名称>.jsonc
3. 已启用模组 2 的 server/tuning/<名称>.jsonc
...(按启动器「模组」页从上到下顺序)
N. 玩家在启动器「数值」页的手动设置(<客户端数据目录>/tuning/<名称>.jsonc,最高优先级)
```
> 所有合并结果在服务器启动时都会经过严格类型和范围校验;字段类型或范围不合法时会直接报出模组 ID、文件名与期望值。
---
## 2. 全部 12 份可叠加配置文件一览
| 文件名 | 管辖内容 | 典型模组用途 |
| --- | --- | --- |
| `battle.jsonc` | 银狮/研发倍率、房间人数、AI 数量与重生次数、分房权重跨度(`brSpreadMrank`)、子模式概率、攻击无人机出生分 | 爽游倍率、大混战人数、无分房压权、无限 AI 重生 |
| `battle-economy.jsonc` | 各类战斗行为基价与对局结算经济参数 | 精细调整击杀/占点/助攻收益占比 |
| `store.jsonc` | 金鹰包、银狮包、高账价格、单车礼包价(`byVehicle`/`byRank`)、多车礼包(`multiVehiclePacks`) | 为新增载具定礼包价、打包自定义多车特惠礼包 |
| `marketplace.jsonc` | 交易所载具券与外观券参考价、品质与手续费 | 调整市场物价、给新增市场车定价 |
| `trophies.jsonc` | 经典战利品箱(银狮箱、老兵箱、奖池直购价)与权重规则 | 新增自定义抽卡箱、调整稀有载具掉率 |
| `supply-chests.jsonc` | 新版外部库存补给箱与掉落池 | 新增自制外部库存箱子 |
| `recycling.jsonc` | 道具回收与零件再合成配方 | 修改合成消耗或产出权重 |
| `redeem-codes.jsonc` | 离线兑换码与作弊码规则 | 添加专属模组礼包兑换码 |
| `new-profile.jsonc` | 新建存档初始银狮、金鹰与 GJN 余额 | 自定义开荒或全解锁爽游开局 |
| `research.jsonc` | 自动挑选默认研发目标策略 | 修改研发体验 |
| `clans.jsonc` | 联队活跃度、人数上限、预置联队 | 新增自定义预置联队 |
| `limits.jsonc` | 单次购买道具上限、战报/日志保留条数 | 提高单次购买上限或日志保留量 |
---
## 3. 列表增量合并语法(`$listOps`)
默认情况下,JSON 对象按字段递归合并,普通数组会**整体替换**上一层的数组。
为了避免两个模组同时往多车礼包、兑换码、补给箱列表里加内容时互相顶掉,任何数组字段都支持用 **`{ "$listOps": [...] }`** 做增量操作:
```jsonc
// 示例:server/tuning/store.jsonc
{
"multiVehiclePacks": {
"$listOps": [
// ① 追加新条目到列表末尾
{
"op": "append",
"items": [
{
"id": "mod_modern_duo_pack",
"title": { "en": "Modern Duo Pack", "zh": "现代双车组合包" },
"priceGjn": 49.99,
"goldenEagles": 2000,
"premiumDays": 15,
"vehicles": ["us_m1a2_sep2_abrams", "germ_leopard_2a7v"]
}
]
},
// ② 按指定键(如 id)查找:存在则按对象递归合并修改,不存在则追加
{
"op": "upsertBy",
"key": "id",
"item": {
"id": "wto_pack_two_fronts",
"priceGjn": 19.99
}
},
// ③ 按指定键与值删除某一项
{
"op": "removeBy",
"key": "id",
"value": "some_unwanted_pack_id"
}
]
}
}
```
支持的 4 种 `$listOps` 操作:
- `append`:`{ "op": "append", "items": [...] }` — 追加到末尾;
- `prepend`:`{ "op": "prepend", "items": [...] }` — 插入到开头;
- `upsertBy`:`{ "op": "upsertBy", "key": "<字段名>", "item": { ... } }` — 按字段匹配合并,找不到就追加;
- `removeBy`:`{ "op": "removeBy", "key": "<字段名>", "value": <匹配值> }` — 删除全部匹配条目。
@@ -0,0 +1,157 @@
# 06 · 服务端 JS/TS 脚本完整接口手册
> **实验期警告(API `0.1-experimental`)**
> 本章描述的所有服务端脚本接口与内部对象均处于极初期开发阶段,随时可能随本体开发变动,不保证向后兼容。
---
## 1. 运行环境与语法规则
本地服务器运行在启动器内置的 **Electron 43 / Node.js 24** 上,**原生开启 TypeScript 类型剥离(`strip`)**,玩家电脑无需安装 Node 或 TypeScript。
- **入口探测顺序**:默认依次查找 `server/index.ts` → `server/index.mjs` → `server/index.js`(也可在 `mod.jsonc` 的 `server.entry` 中自定义相对路径);
- **直接写 `.ts` 的语法约定**:遵循 TypeScript 的 `erasableSyntaxOnly` 规则——支持全部类型注解、`interface`、`type`、泛型与 `as`,但**不要使用**需要代码生成的 `enum`、`namespace` 或构造函数参数属性(改用 `as const` 对象与联合类型即可);
- 如果你的项目想使用任意 TS 语法或第三方 npm 包,自行用 esbuild / tsc 打包成单文件 `.mjs` 分发即可。
### 标准导出写法
```ts
export default {
async setup(ctx) {
ctx.logger.info('mod initialized');
// 在此注册钩子、路由与初始化逻辑
},
};
```
(也支持直接导出默认函数 `export default function (ctx) { ... }` 或具名导出 `export function setup(ctx) { ... }`。)
---
## 2. `WtoServerModContext`(注入给 `setup(ctx)` 的上下文对象)
| 属性 | 类型 | 说明 |
| --- | --- | --- |
| `ctx.apiVersion` | `string` | 当前运行时的实验期 API 版本号(`"0.1-experimental"`) |
| `ctx.manifest` | `ModManifest` | 本模组解析后的 `mod.jsonc` 清单对象 |
| `ctx.modDir` | `string` | 本模组根目录的绝对路径(可用 `node:fs` 读取模组自带的配置文件) |
| `ctx.gameFolder` | `string` | 当前运行的离线游戏副本根目录 |
| `ctx.dataFolder` | `string` | 当前客户端的数据目录(含存档、缓存、日志) |
| `ctx.port` | `number` | 本次启动的本地服务器监听端口 |
| `ctx.logger` | `{ info, warn, error }` | 带 `[mod:<id>]` 前缀的日志输出器,自动进入启动器日志与诊断导出 |
| `ctx.storage` | `ModStorageApi` | 按账号隔离或全局共享的独立 JSON 存档区(见第 3 节) |
| `ctx.hooks` | `ServerModHooksApi` | 生命周期、档案、匹配与对局钩子(见第 4 节) |
| `ctx.routes` | `ServerModRoutesApi` | `char`、`matching` 与本地 HTTP 路由扩展(见第 5 节) |
完整 TypeScript 定义源码见仓库 `packages/mods/src/server-api.ts`。
---
## 3. 独立存档区(`ctx.storage`)
**硬性最佳实践**:请勿往原版 `profile.blk` 写入非标准字段(容易影响客户端序列化或卸载模组后污染存档)。统一使用 `ctx.storage`:
```ts
// ① 按本地玩家账号隔离:<dataFolder>/saves/<userId>/mods/<modId>.json
const playerStore = ctx.storage.forPlayer(userId);
const prev = playerStore.read<{ wins: number }>() ?? { wins: 0 };
playerStore.write({ wins: prev.wins + 1 }); // 原子写盘
// playerStore.remove();
// ② 模组全局共享存储:<dataFolder>/mods-data/<modId>.json
const sharedStore = ctx.storage.shared();
```
---
## 4. 全部生命周期与业务钩子(`ctx.hooks`)
### 4.1 `ctx.hooks.onDatasetsLoaded(async (datasets) => { ... })`
在本地服务器从叠加后的 `.vromfs.bin` 提取完静态数据集、尚未组装业务目录前触发。可读取或原地修改:
- `datasets.vehicles`:载具目录数组(含价格、研发点、权重、科技树信息)
- `datasets.battleEconomy`:对局收益基数与每车系数表
- `datasets.battleSpawnRules`:出生点、支援机与规则数据
- `datasets.multiplayerMissions`:`{ categories, missions }` 联机任务数据
- `datasets.uiLabels` / `datasets.unitNames`:多语言标签与载具名映射
- `datasets.get(datasetId)` / `datasets.set(datasetId, value)`:按 ID 读取或替换任意数据集
### 4.2 `ctx.hooks.onCataloguesReady(async (catalogues) => { ... })`
在所有业务目录与核心服务装配完成后、开监听之前触发,可访问:
- `catalogues.tuning`:合并完成后的全部只读 `Tuning`
- `catalogues.gameModes`:`GameModes` 实例(提供 `ids()`、`byId(id)`、`byName(name)`、`byEconomicName(name)`、`countries()`)
- `catalogues.profiles` / `accounts` / `research` / `equipment` / `repair`
- `catalogues.store` / `inventory` / `trophies` / `items` / `crew` / `decor` / `unlocks` / `clans`
- `catalogues.battleMatchmaker` / `battleEconomy` / `battleStreaks`
- `catalogues.notifyInventoryChanged()`:向客户端推送外部库存变更实时刷新
- `catalogues.notifyUser(userId, eventName, payload)`:向指定登录玩家发送匹配服 `mrpc.generic_notify` 实时推送
### 4.3 `ctx.hooks.onServerListening(({ port }) => { ... })` / `onServerClosing(() => { ... })`
服务器开始监听端口后、以及关闭前触发(适合启动/清理定时器或打印日志)。
### 4.4 档案钩子:`ctx.hooks.profile.onRefresh((profile, userId) => { ... })`
每次读取或更新玩家档案并执行完原生刷新管线后调用(`profile` 是 `@wto/blk` 的 `BlkBlock`)。
### 4.5 对局与匹配钩子(`ctx.hooks.battle`)
#### ① `ctx.hooks.battle.onBeforeMatchmake((ctx) => { ... })`
玩家点击「加入战斗」进入匹配队列、尚未调用 `BattleMatchmaker` 之前触发:
- `ctx`:`{ userId, eventName, request }`(`request` 为客户端发来的原始 `match.enqueue` 参数对象)。
#### ② `ctx.hooks.battle.onFilterMissions((ctx) => { ... })`
`BattleMatchmaker` 已按模式与分房权重筛选出两队候选任务池、尚未随机抽图时触发。
- `ctx`:`{ userId, modeId, modeName, economicName, minMrank, maxMrank, missions }`;
- 每条 `mission` 包含 `{ name, path, level, type, locName, postfix }`;
- **返回值**:返回过滤/重排后的子集数组(返回 `undefined` 表示不干预)。若返回空数组,服务端会记录告警并自动回退到上一层候选池,避免卡死匹配。
```ts
// 示例:只允许匹配名称包含 poland 或 berlin 的地图
ctx.hooks.battle.onFilterMissions(({ missions }) => {
const picked = missions.filter((m) => /poland|berlin/i.test(m.level ?? m.name));
return picked.length > 0 ? picked : undefined;
});
```
#### ③ `ctx.hooks.battle.onLiveFact((ctx) => { ... })`
对局进行中收到客户端上报的实时战斗事实(击杀、占点、生命段、核弹爆炸)时触发:
- `ctx`:`{ userId, roomId, fact }`。
#### ④ `ctx.hooks.battle.onAfterSettle((ctx) => { ... })`
对局结束并写入原生结算后、档案落盘前触发:
- `ctx`:`{ userId, roomId, summary }`(`summary` 含 `{ profile, report, session }`),可在此发放额外自定义奖励或累计模组统计。
---
## 5. 协议路由与本地网页扩展(`ctx.routes`)
### 5.1 Char 动作扩展(`ctx.routes.char`)
- `ctx.routes.char.register(action, handler)`:注册全新的自定义 `cln_*` 动作(如配合客户端 GUI 补丁发来的请求);
- `ctx.routes.char.wrap(action, async (req, next) => { ... })`:拦截并包装现有 `cln_*` 动作(可在调用 `await next(req)` 前后改请求或改响应)。
### 5.2 匹配服 RPC 扩展(`ctx.routes.matching`)
客户端 Quirrel 脚本可以直接用 `matchingApiFunc("wto_mod.<你的方法>", params, callback)` 调用本地服务器匹配接口!
- `ctx.routes.matching.register(method, (req) => ({ ... }))`:注册自定义 RPC(`req` 含 `{ method, params, userId }`,直接返回 JSON 对象);
- `ctx.routes.matching.wrap(method, (req, next) => { ... })`:包装现有匹配服 RPC。
```ts
ctx.routes.matching.register('wto_mod.my_mod.ping', ({ userId, params }) => ({
ok: true,
userId,
echo: params,
}));
```
### 5.3 本地 HTTP / 内置浏览器网页路由(`ctx.routes.http`)
自动挂载在 **`/mods/<你的modId>/...`** 命名空间下,支持精确路径和 `/*` 通配后缀,既可用系统浏览器访问,也可以通过游戏内置浏览器直接打开:
```ts
ctx.routes.http.register('/panel', () => ({
status: 200,
contentType: 'text/html; charset=utf-8',
body: '<h1>My Mod Panel</h1>',
}));
ctx.routes.http.register('/api/*', (req) => ({
status: 200,
contentType: 'application/json; charset=utf-8',
body: JSON.stringify({ path: req.path, query: req.query }),
}));
```
@@ -0,0 +1,44 @@
# 07 · 排错、日志与最佳实践
## 1. 模组出错了去哪里看日志?
启动器所有模组构建与运行日志都会汇入标准日志目录,可在 **「设置 › 诊断 › 打开日志目录」** 或 **「关于 › 导出诊断日志」** 直接查看:
1. **启动器主日志(`launcher.log`)**:
- 搜索 `[build]`:查看本轮启用了哪些模组、各数据包叠加统计、以及哪条 GUI 补丁或 `exe` 补丁被跳过及精确原因;
- 搜索 `[mods]`:查看跨盘 Junction 挂载结果、被跳过的原生文件冲突告警、以及还原的可选数据包;
- 搜索 `[server]` 或 `[mod:<你的modId>]`:查看服务端脚本加载报错、堆栈、以及你在脚本里调用 `ctx.logger.info/warn/error` 打印的全部输出。
2. **游戏客户端日志(`<客户端目录>/.game_logs/*.clog`)**:
- 若客户端 GUI 脚本报错或卡在「正在加载」,查看最新的 `.clog`(或先用 `sq.exe` 做完整字节码检查定位);
- 若新增 3D 模型未渲染,搜索 `.clog` 中的 `[PACK]`、`pkg_user` 或模型资源名确认是否被引擎加载。
---
## 2. 常见报错速查
| 现象 / 报错 | 原因 | 解决方法 |
| --- | --- | --- |
| 启动器提示某模组目录读取失败 | `mod.jsonc` JSON 语法错误、含未知字段、`id` 不合规范或 `server.entry` 路径不存在 | 对照第 01 章字段表核对 `mod.jsonc` |
| 点启动提示「存在阻塞性模组错误」 | 启用的模组缺少 `requires` 前置、前置未勾选,或同时启用了声明 `conflicts` 互斥的模组 | 按「模组」页顶部的红色错误列表补齐前置或关闭互斥项 |
| 服务端加载 `.ts` 报语法错(如 `enum` 不支持) | Node 24 原生 TS 剥离不支持需要代码生成的旧语法 | 改用 `as const` 对象 + 联合类型,或自行编译为 `.mjs` |
| 日志提示 `overlaps protected core patch` | 模组的 `client/exe-patches/` 试图修改离线版核心隔离补丁锁定的字节 | 不可覆盖核心隔离区段,请改用其他钩点或服务端方案 |
| 日志提示 `target already exists as a native/player file` | `client/files/` 中的某文件与玩家自己在 `UserSkins/` 或 `UserSights/` 手动放的文件重名 | 给模组自带的配套子目录加上专属前缀(如 `mod_<你的id>_...`)避免撞名 |
| 进机库一直卡在「正在加载」 | 新增或修补的 `.nut` 脚本存在 Quirrel 词法作用域冲突、保留字误用或前向引用 | 用 `sq.exe` 对最终 `.nut` 跑完整 `compilestring` 字节码检查 |
---
## 3. 跨盘与非 NTFS 磁盘说明
- **NTFS 硬盘(绝大多数 Windows 电脑)**:`client/addon/`(3D 模型与贴图)和独占子目录(如 `UserSkins/<子目录>`)全部通过 **NTFS Directory Junction** 挂载——**跨盘可用、免管理员、0 额外空间、1 毫秒完成**;
- **平铺散文件(如 `sound/mod/*.bank`)**:依次尝试文件符号链接(开 Windows 开发者模式时跨盘零拷贝)→ 同盘硬链接 → 增量缓存复制(未修改文件下次启动自动跳过);
- **exFAT 移动硬盘**:因文件系统不支持 Junction 和硬链接,自动退化为按大小与修改时间比对的增量缓存复制,功能照常可用。
---
## 4. 给模组制作组的 5 条黄金习惯
1. **命名空间隔离一切**:模组 ID 用 `<作者>.<模组名>`;新增载具、武器、涂装子目录、自定义匹配 RPC、自定义 Char 动作全部带自己前缀(如 `wto_mod.<名称>`),避免和其他模组撞车;
2. **公共表一律用补丁,绝不整文件覆盖**:修改 `shop.blk`、`wpcost.blk`、`unittags.blk`、`units.csv` 时永远用 `.patch.jsonc` / `.patch.csv`;
3. **只读原版,不污染主存档**:模组持久化数据全部写进 `ctx.storage.forPlayer(userId)`,卸载模组后玩家主存档干干净净;
4. **界面大逻辑拆独立文件**:新弹窗放 `client/packs/gui.vromfs.bin/`,`gui-patches/` 里只留几行挂入口按钮的代码,换版本几乎不用重写;
5. **发布前做一次“开 → 玩 → 关 → 重启”循环**:确认启用时生效、关掉后彻底还原,且与其他模组一起开不冲突。
+12
View File
@@ -1934,6 +1934,10 @@
"resolved": "apps/launcher",
"link": true
},
"node_modules/@wto/mods": {
"resolved": "packages/mods",
"link": true
},
"node_modules/@wto/patcher": {
"resolved": "packages/patcher",
"link": true
@@ -6151,6 +6155,14 @@
"name": "@wto/jsonc",
"version": "0.1.0"
},
"packages/mods": {
"name": "@wto/mods",
"version": "0.1.0",
"dependencies": {
"@wto/blk": "*",
"@wto/jsonc": "*"
}
},
"packages/patcher": {
"name": "@wto/patcher",
"version": "0.1.0",
+2 -1
View File
@@ -10,6 +10,7 @@ export { emptyBlock } from './model.ts';
export { BlkFormatError } from './errors.ts';
export { BlkLabel, decodeBlk, encodeBlk, type SharedNameContext } from './binary/format.ts';
export { parseSharedNameMap, type SharedNameMap } from './shared-name-map.ts';
export { appendParam, ensureBlock, findBlock, findParam, setParam, visitParams } from './tree.ts';
export { appendParam, cloneBlock, ensureBlock, findBlock, findParam, setParam, visitParams } from './tree.ts';
export { formatBlkText } from './text/format-text.ts';
export { isBinaryBlk, parseBlkText } from './text/parse-text.ts';
export { singleVehiclePackId, stableGuid } from './stable-guid.ts';
+317
View File
@@ -0,0 +1,317 @@
/**
* Parse a BLK document in Dagor's text syntax back into the typed in-memory model.
*
* Syntax source: DagorEngine prog/engine/ioSys/dataBlock/blk_read.cpp (BSD-3).
* Supports C/C++ comments, quoted and bare identifiers, `~` string escapes, nested blocks,
* optional semicolons, and every typed parameter suffix emitted by `format-text.ts`.
*/
import { BlkFormatError } from '../errors.ts';
import { emptyBlock, type BlkBlock, type BlkValue } from '../model.ts';
export function isBinaryBlk(bytes: Uint8Array): boolean {
if (bytes.length === 0) return false;
const first = bytes[0]!;
// Binary BLK labels used by DagorEngine (see binary/format.ts BlkLabel: 0x00..0x06, zstd 0x28).
return first <= 0x06 || first === 0x28;
}
export function parseBlkText(source: string): BlkBlock {
const parser = new BlkTextParser(source);
const root = emptyBlock('');
parser.readBlockBody(root, false);
return root;
}
class BlkTextParser {
readonly #text: string;
#pos = 0;
constructor(text: string) {
// Strip UTF-8 BOM if present.
this.#text = text.startsWith('\uFEFF') ? text.slice(1) : text;
}
readBlockBody(target: BlkBlock, expectClosingBrace: boolean): void {
while (true) {
this.#skipIgnored();
if (this.#eof()) {
if (expectClosingBrace) this.#fail('unexpected end of BLK text inside block');
return;
}
if (this.#peek() === '}') {
if (!expectClosingBrace) this.#fail('unexpected closing brace "}" at root');
this.#pos += 1;
return;
}
const key = this.#readIdentifierOrString();
this.#skipIgnored();
const ch = this.#peek();
if (ch === '{') {
this.#pos += 1;
const child = emptyBlock(key);
this.readBlockBody(child, true);
target.blocks.push(child);
continue;
}
if (ch === ':') {
this.#pos += 1;
const suffix = this.#readTypeSuffix();
this.#skipHorizontalAndComments();
if (this.#peek() !== '=') this.#fail(`expected "=" after type suffix ":${suffix}"`);
this.#pos += 1;
const value = this.#readValue(suffix);
target.params.push({ name: key, value });
continue;
}
// Untyped `include "..."` directive or unknown syntax.
if (key === 'include' && (ch === '"' || ch === "'")) {
const included = this.#readQuotedString();
target.params.push({ name: 'include', value: { type: 'string', value: included } });
continue;
}
this.#fail(`expected "{" or ":" after "${key}"`);
}
}
#readIdentifierOrString(): string {
const ch = this.#peek();
if (ch === '"' || ch === "'") return this.#readQuotedString();
const start = this.#pos;
while (!this.#eof()) {
const c = this.#text[this.#pos]!;
if (c === ':' || c === '{' || c === '}' || c === '=' || c === ';' || /\s/.test(c)) break;
if (c === '/' && (this.#text[this.#pos + 1] === '/' || this.#text[this.#pos + 1] === '*')) break;
this.#pos += 1;
}
if (this.#pos === start) this.#fail(`unexpected character "${ch ?? ''}"`);
return this.#text.slice(start, this.#pos);
}
#readTypeSuffix(): string {
const start = this.#pos;
while (!this.#eof() && /[A-Za-z0-9]/.test(this.#text[this.#pos]!)) this.#pos += 1;
const suffix = this.#text.slice(start, this.#pos);
if (!suffix) this.#fail('missing BLK type suffix after ":"');
return suffix;
}
#readValue(suffix: string): BlkValue {
this.#skipHorizontalAndComments();
switch (suffix) {
case 't': return { type: 'string', value: this.#readStringValue() };
case 'i': return { type: 'int', value: this.#readInt() };
case 'i64': return { type: 'int64', value: this.#readBigInt() };
case 'r': return { type: 'real', value: this.#readReal() };
case 'b': return { type: 'bool', value: this.#readBool() };
case 'p2': return { type: 'point2', value: this.#readReals(2) as [number, number] };
case 'p3': return { type: 'point3', value: this.#readReals(3) as [number, number, number] };
case 'p4': return { type: 'point4', value: this.#readReals(4) as [number, number, number, number] };
case 'ip2': return { type: 'ipoint2', value: this.#readInts(2) as [number, number] };
case 'ip3': return { type: 'ipoint3', value: this.#readInts(3) as [number, number, number] };
case 'ip4': return { type: 'ipoint4', value: this.#readInts(4) as [number, number, number, number] };
case 'c': return { type: 'color', value: this.#readColor() };
case 'm': return { type: 'matrix', value: this.#readMatrix() };
default: this.#fail(`unsupported BLK type suffix ":${suffix}"`);
}
}
#readStringValue(): string {
const ch = this.#peek();
if (ch === '"' || ch === "'") return this.#readQuotedString();
// Unquoted single-line string terminated by newline, semicolon, brace, or comment.
const start = this.#pos;
while (!this.#eof()) {
const c = this.#text[this.#pos]!;
if (c === '\r' || c === '\n' || c === ';' || c === '}') break;
if (c === '/' && (this.#text[this.#pos + 1] === '/' || this.#text[this.#pos + 1] === '*')) break;
this.#pos += 1;
}
return this.#text.slice(start, this.#pos).trim();
}
#readQuotedString(): string {
const quote = this.#text[this.#pos]!;
this.#pos += 1;
let out = '';
while (!this.#eof()) {
const c = this.#text[this.#pos]!;
this.#pos += 1;
if (c === quote) return out;
if (c === '~' && !this.#eof()) {
const next = this.#text[this.#pos]!;
this.#pos += 1;
switch (next) {
case 'n': out += '\n'; break;
case 'r': out += '\r'; break;
case 't': out += '\t'; break;
case '~': out += '~'; break;
case '"': out += '"'; break;
case "'": out += "'"; break;
default: out += next; break;
}
continue;
}
out += c;
}
this.#fail('unterminated string literal');
}
#readToken(): string {
this.#skipHorizontalAndComments();
const start = this.#pos;
while (!this.#eof()) {
const c = this.#text[this.#pos]!;
if (c === ',' || c === ';' || c === '}' || c === ']' || /\s/.test(c)) break;
if (c === '/' && (this.#text[this.#pos + 1] === '/' || this.#text[this.#pos + 1] === '*')) break;
this.#pos += 1;
}
if (this.#pos === start) this.#fail('expected value token');
return this.#text.slice(start, this.#pos);
}
#readInt(): number {
const raw = this.#readToken();
const parsed = raw.startsWith('0x') || raw.startsWith('0X') ? Number.parseInt(raw, 16) : Number(raw);
if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) this.#fail(`invalid integer "${raw}"`);
return parsed | 0;
}
#readBigInt(): bigint {
const raw = this.#readToken();
try {
return BigInt(raw);
} catch {
this.#fail(`invalid int64 "${raw}"`);
}
}
#readReal(): number {
const raw = this.#readToken();
const parsed = Number(raw);
if (!Number.isFinite(parsed)) this.#fail(`invalid real "${raw}"`);
return parsed;
}
#readBool(): boolean {
const raw = this.#readToken().toLowerCase();
if (raw === 'yes' || raw === 'true' || raw === '1') return true;
if (raw === 'no' || raw === 'false' || raw === '0') return false;
this.#fail(`invalid bool "${raw}"`);
}
#readReals(count: number): number[] {
const values: number[] = [];
for (let i = 0; i < count; i += 1) {
if (i > 0) this.#expectComma();
values.push(this.#readReal());
}
return values;
}
#readInts(count: number): number[] {
const values: number[] = [];
for (let i = 0; i < count; i += 1) {
if (i > 0) this.#expectComma();
values.push(this.#readInt());
}
return values;
}
#readColor(): number {
const channels = this.#readInts(4);
const [r, g, b, a] = channels as [number, number, number, number];
return (((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)) >>> 0;
}
#readMatrix(): number[] {
this.#expectChar('[');
const values: number[] = [];
for (let row = 0; row < 4; row += 1) {
this.#skipIgnored();
this.#expectChar('[');
for (let col = 0; col < 3; col += 1) {
if (col > 0) this.#expectComma();
values.push(this.#readReal());
}
this.#skipHorizontalAndComments();
this.#expectChar(']');
this.#skipHorizontalAndComments();
if (this.#peek() === ',') this.#pos += 1;
}
this.#skipIgnored();
this.#expectChar(']');
return values;
}
#expectComma(): void {
this.#skipHorizontalAndComments();
if (this.#peek() !== ',') this.#fail('expected "," between tuple components');
this.#pos += 1;
}
#expectChar(expected: string): void {
this.#skipHorizontalAndComments();
if (this.#peek() !== expected) this.#fail(`expected "${expected}"`);
this.#pos += 1;
}
#skipIgnored(): void {
while (!this.#eof()) {
const c = this.#text[this.#pos]!;
if (c === ';' || /\s/.test(c)) {
this.#pos += 1;
continue;
}
if (this.#skipComment()) continue;
break;
}
}
#skipHorizontalAndComments(): void {
while (!this.#eof()) {
const c = this.#text[this.#pos]!;
if (c === ' ' || c === '\t') {
this.#pos += 1;
continue;
}
if (this.#skipComment()) continue;
break;
}
}
#skipComment(): boolean {
if (this.#text[this.#pos] !== '/') return false;
const next = this.#text[this.#pos + 1];
if (next === '/') {
this.#pos += 2;
while (!this.#eof() && this.#text[this.#pos] !== '\n') this.#pos += 1;
return true;
}
if (next === '*') {
this.#pos += 2;
while (!this.#eof()) {
if (this.#text[this.#pos] === '*' && this.#text[this.#pos + 1] === '/') {
this.#pos += 2;
return true;
}
this.#pos += 1;
}
this.#fail('unterminated block comment');
}
return false;
}
#peek(): string | undefined {
return this.#text[this.#pos];
}
#eof(): boolean {
return this.#pos >= this.#text.length;
}
#fail(message: string): never {
const prefix = this.#text.slice(0, this.#pos);
const line = prefix.split('\n').length;
throw new BlkFormatError(`BLK text parse error on line ${line}: ${message}`);
}
}
+25
View File
@@ -34,6 +34,31 @@ export function appendParam(block: BlkBlock, name: string, value: BlkValue): voi
block.params.push({ name, value });
}
/** Deep-clone a BLK block tree, optionally under a new block name. */
export function cloneBlock(block: BlkBlock, newName = block.name): BlkBlock {
return {
name: newName,
params: block.params.map((param) => ({
name: param.name,
value: cloneValue(param.value),
})),
blocks: block.blocks.map((child) => cloneBlock(child)),
};
}
function cloneValue(value: BlkValue): BlkValue {
switch (value.type) {
case 'point2': return { type: 'point2', value: [...value.value] as [number, number] };
case 'point3': return { type: 'point3', value: [...value.value] as [number, number, number] };
case 'point4': return { type: 'point4', value: [...value.value] as [number, number, number, number] };
case 'ipoint2': return { type: 'ipoint2', value: [...value.value] as [number, number] };
case 'ipoint3': return { type: 'ipoint3', value: [...value.value] as [number, number, number] };
case 'ipoint4': return { type: 'ipoint4', value: [...value.value] as [number, number, number, number] };
case 'matrix': return { type: 'matrix', value: [...value.value] };
default: return { ...value };
}
}
/** Visit every parameter of the tree, depth first, with the path of block names leading to it. */
export function visitParams(block: BlkBlock, visit: (param: BlkParam, path: readonly string[]) => void,
path: readonly string[] = []): void {
+1 -1
View File
@@ -13,6 +13,6 @@ export { DefinitionError, LocateError, PatchError, PeFormatError, VerifyError }
export { asObject, readJsonObject, rejectUnknownKeys, requiredString, stringList, variantObjects } from './json-fields.ts';
export { NO_CONTEXT, type LocateContext } from './locate/index.ts';
export { PeImage, type FunctionRange, type Section } from './pe-image.ts';
export { describePlan, planPatches, type PatchFailure, type PatchPlan, type PlannedWrite } from './plan.ts';
export { describePlan, planAdditionalPatches, planPatches, type PatchFailure, type PatchPlan, type PlannedWrite } from './plan.ts';
export { findSite, readSiteSpec, type FoundSite, type SiteSpec } from './site.ts';
export { chooseVariant, type Chosen, type Variant } from './variants.ts';
+61
View File
@@ -58,6 +58,67 @@ export function planPatches(image: PeImage, definitions: readonly PatchDefinitio
return { writes, failures };
}
/**
* Plan additive patches (such as declarative mod exe patches) on top of locked core writes.
* Any patch that fails to locate/verify, depends on a failed patch, overlaps a protected core
* write, or overlaps an earlier accepted additive write is recorded in `failures` rather than
* throwing, so core offline isolation patches are never overwritten or broken.
*/
export function planAdditionalPatches(
image: PeImage,
definitions: readonly PatchDefinition[],
protectedWrites: readonly PlannedWrite[],
): PatchPlan {
const planned = new Map<string, PlannedWrite>();
const failed = new Map<string, string>();
for (const definition of definitions) {
try {
const chosen = chooseVariant(definition.variants, (variant) => planVariant(image, variant));
planned.set(definition.id, { patchId: definition.id, variant: chosen.variant.writtenFor, ...chosen.value });
} catch (error) {
if (!(error instanceof PatchError)) throw error;
failed.set(definition.id, error.message);
}
}
propagateFailures(definitions, failed);
const accepted: PlannedWrite[] = [];
for (const definition of definitions) {
if (failed.has(definition.id)) continue;
const candidate = planned.get(definition.id)!;
const coreConflict = findOverlappingWrite(candidate, protectedWrites);
if (coreConflict) {
failed.set(definition.id, `overlaps protected core patch "${coreConflict.patchId}" at ${hex(candidate.rva)}`);
continue;
}
const earlierConflict = findOverlappingWrite(candidate, accepted);
if (earlierConflict) {
failed.set(definition.id, `overlaps earlier patch "${earlierConflict.patchId}" at ${hex(candidate.rva)}`);
continue;
}
accepted.push(candidate);
}
// Re-propagate if an overlap rejection broke a downstream dependency.
const beforeSecondPass = failed.size;
propagateFailures(definitions, failed);
const writes = failed.size === beforeSecondPass
? accepted
: accepted.filter((write) => !failed.has(write.patchId));
const failures = definitions.filter((item) => failed.has(item.id))
.map((item) => ({ patchId: item.id, features: item.features, reason: failed.get(item.id)! }));
return { writes, failures };
}
function findOverlappingWrite(candidate: PlannedWrite, existing: readonly PlannedWrite[]): PlannedWrite | undefined {
const cStart = candidate.fileOffset;
const cEnd = cStart + candidate.payload.length;
return existing.find((write) => {
const wStart = write.fileOffset;
const wEnd = wStart + write.payload.length;
return cStart < wEnd && wStart < cEnd;
});
}
export function describePlan(plan: PatchPlan): string {
const lines = [`${plan.writes.length} patch(es) ready, ${plan.failures.length} unavailable`];
for (const write of plan.writes) lines.push(` ready ${write.patchId} at ${hex(write.rva)} (variant ${write.variant})`);
+13
View File
@@ -0,0 +1,13 @@
{
"name": "@wto/mods",
"version": "0.1.0",
"private": true,
"type": "module",
"exports": {
".": "./src/index.ts"
},
"dependencies": {
"@wto/blk": "*",
"@wto/jsonc": "*"
}
}
+450
View File
@@ -0,0 +1,450 @@
/**
* Structured, type-preserving incremental patches for BLK documents (`*.blk.patch.jsonc`).
*
* Allows multiple mods to add vehicles to config/shop.blk, adjust prices/BR in config/wpcost.blk,
* tweak weapon/FM parameters, or clone an existing vehicle block and customize it without
* shipping whole stock files.
*/
import {
appendParam,
cloneBlock,
emptyBlock,
ensureBlock,
findParam,
setParam,
type BlkBlock,
type BlkValue,
type BlkValueType,
} from '@wto/blk';
import { parseJsonc } from '@wto/jsonc';
export interface BlkPathStep {
readonly name: string;
/** Zero-based occurrence index when multiple sibling blocks share the same name (e.g. `range[2]`). */
readonly index?: number;
}
export type BlkPatchValueInput =
| string
| number
| boolean
| { readonly type: BlkValueType; readonly value: unknown };
export interface BlkBlockBlueprint {
readonly name?: string;
readonly params?: ReadonlyArray<{ readonly name: string; readonly value: BlkPatchValueInput }>;
readonly blocks?: readonly BlkBlockBlueprint[];
}
export type BlkPatchOp =
| {
readonly op: 'setParam';
readonly path: readonly string[];
readonly name: string;
readonly value: BlkPatchValueInput;
readonly createBlocks?: boolean;
}
| {
readonly op: 'addParam';
readonly path: readonly string[];
readonly name: string;
readonly value: BlkPatchValueInput;
readonly createBlocks?: boolean;
}
| {
readonly op: 'removeParam';
readonly path: readonly string[];
readonly name: string;
readonly value?: string | number | boolean;
}
| {
readonly op: 'upsertBlock';
readonly path: readonly string[];
readonly block?: BlkBlockBlueprint;
}
| {
readonly op: 'addBlock';
readonly path: readonly string[];
readonly name: string;
readonly block?: BlkBlockBlueprint;
readonly before?: string;
readonly after?: string;
readonly createBlocks?: boolean;
}
| {
readonly op: 'removeBlock';
readonly path: readonly string[];
}
| {
readonly op: 'cloneBlock';
readonly from: readonly string[];
readonly toParent: readonly string[];
readonly newName: string;
readonly replaceExisting?: boolean;
readonly before?: string;
readonly after?: string;
readonly ops?: readonly BlkPatchOp[];
};
export interface BlkPatchDocument {
readonly ops: readonly BlkPatchOp[];
}
export class BlkPatchError extends Error {
override name = 'BlkPatchError';
}
export function parseBlkPatchDocument(text: string, where = 'blk patch'): BlkPatchDocument {
let raw: unknown;
try {
raw = parseJsonc(text);
} catch (error) {
throw new BlkPatchError(`${where}: cannot parse JSONC: ${error instanceof Error ? error.message : String(error)}`);
}
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
throw new BlkPatchError(`${where}: root must be an object with an "ops" array`);
}
const opsRaw = (raw as Record<string, unknown>).ops;
if (!Array.isArray(opsRaw)) {
throw new BlkPatchError(`${where}: missing "ops" array`);
}
return { ops: opsRaw.map((item, idx) => validateOp(item, `${where}.ops[${idx}]`)) };
}
export function applyBlkPatch(root: BlkBlock, patch: BlkPatchDocument, where = 'blk patch'): void {
for (let i = 0; i < patch.ops.length; i += 1) {
applyOp(root, patch.ops[i]!, `${where}.ops[${i}]`);
}
}
function applyOp(root: BlkBlock, op: BlkPatchOp, where: string): void {
switch (op.op) {
case 'setParam': {
const target = resolveBlock(root, op.path, op.createBlocks ?? false, where);
const existing = findParam(target, op.name);
const value = toBlkValue(op.value, existing?.value.type, where);
setParam(target, op.name, value);
return;
}
case 'addParam': {
const target = resolveBlock(root, op.path, op.createBlocks ?? false, where);
const existing = findParam(target, op.name);
const value = toBlkValue(op.value, existing?.value.type, where);
appendParam(target, op.name, value);
return;
}
case 'removeParam': {
const target = tryResolveBlock(root, op.path);
if (!target) return;
target.params = target.params.filter((param) => {
if (param.name !== op.name) return true;
if (op.value === undefined) return false;
return !paramValueMatchesPrimitive(param.value, op.value);
});
return;
}
case 'upsertBlock': {
const target = resolveBlock(root, op.path, true, where);
if (op.block) mergeBlockBlueprint(target, op.block, where);
return;
}
case 'addBlock': {
const parent = resolveBlock(root, op.path, op.createBlocks ?? false, where);
const created = emptyBlock(op.name);
if (op.block) mergeBlockBlueprint(created, op.block, where);
insertBlockPositioned(parent, created, op.before, op.after);
return;
}
case 'removeBlock': {
if (op.path.length === 0) throw new BlkPatchError(`${where}: cannot remove root block`);
const parent = tryResolveBlock(root, op.path.slice(0, -1));
if (!parent) return;
const step = parsePathStep(op.path[op.path.length - 1]!, where);
const index = findChildBlockIndex(parent, step);
if (index >= 0) parent.blocks.splice(index, 1);
return;
}
case 'cloneBlock': {
const source = resolveBlock(root, op.from, false, `${where}.from`);
const parent = resolveBlock(root, op.toParent, true, `${where}.toParent`);
const cloned = cloneBlock(source, op.newName);
if (op.ops) {
for (let i = 0; i < op.ops.length; i += 1) {
applyOp(cloned, op.ops[i]!, `${where}.ops[${i}]`);
}
}
if (op.replaceExisting) {
const existingIdx = parent.blocks.findIndex((child) => child.name === op.newName);
if (existingIdx >= 0) {
parent.blocks[existingIdx] = cloned;
return;
}
}
insertBlockPositioned(parent, cloned, op.before, op.after);
return;
}
}
}
function insertBlockPositioned(parent: BlkBlock, block: BlkBlock, before?: string, after?: string): void {
if (before !== undefined) {
const idx = parent.blocks.findIndex((child) => child.name === before);
if (idx >= 0) {
parent.blocks.splice(idx, 0, block);
return;
}
}
if (after !== undefined) {
const idx = parent.blocks.findIndex((child) => child.name === after);
if (idx >= 0) {
parent.blocks.splice(idx + 1, 0, block);
return;
}
}
parent.blocks.push(block);
}
function mergeBlockBlueprint(target: BlkBlock, blueprint: BlkBlockBlueprint, where: string): void {
if (blueprint.params) {
for (const [idx, param] of blueprint.params.entries()) {
const existing = findParam(target, param.name);
const value = toBlkValue(param.value, existing?.value.type, `${where}.params[${idx}]`);
appendParam(target, param.name, value);
}
}
if (blueprint.blocks) {
for (const [idx, childBlueprint] of blueprint.blocks.entries()) {
const name = childBlueprint.name;
if (!name) throw new BlkPatchError(`${where}.blocks[${idx}]: child block must have a "name"`);
const child = emptyBlock(name);
mergeBlockBlueprint(child, childBlueprint, `${where}.blocks[${idx}]`);
target.blocks.push(child);
}
}
}
function resolveBlock(root: BlkBlock, path: readonly string[], createMissing: boolean, where: string): BlkBlock {
let current = root;
for (const rawStep of path) {
const step = parsePathStep(rawStep, where);
const idx = findChildBlockIndex(current, step);
if (idx >= 0) {
current = current.blocks[idx]!;
} else if (createMissing && step.index === undefined) {
current = ensureBlock(current, step.name);
} else {
throw new BlkPatchError(`${where}: block "${rawStep}" not found along path [${path.join(' / ')}]`);
}
}
return current;
}
function tryResolveBlock(root: BlkBlock, path: readonly string[]): BlkBlock | undefined {
let current = root;
for (const rawStep of path) {
const step = parsePathStep(rawStep, 'path');
const idx = findChildBlockIndex(current, step);
if (idx < 0) return undefined;
current = current.blocks[idx]!;
}
return current;
}
function parsePathStep(raw: string, where: string): BlkPathStep {
const match = /^(.+)\[(\d+)\]$/.exec(raw);
if (!match) {
if (!raw) throw new BlkPatchError(`${where}: empty path segment`);
return { name: raw };
}
return { name: match[1]!, index: Number(match[2]!) };
}
function findChildBlockIndex(parent: BlkBlock, step: BlkPathStep): number {
const wanted = step.index ?? 0;
let seen = 0;
for (let i = 0; i < parent.blocks.length; i += 1) {
if (parent.blocks[i]!.name !== step.name) continue;
if (seen === wanted) return i;
seen += 1;
}
return -1;
}
function toBlkValue(input: BlkPatchValueInput, inferredType: BlkValueType | undefined, where: string): BlkValue {
if (typeof input === 'string') return { type: 'string', value: input };
if (typeof input === 'boolean') return { type: 'bool', value: input };
if (typeof input === 'number') {
if (inferredType === 'real') return { type: 'real', value: input };
if (inferredType === 'int') return { type: 'int', value: input | 0 };
if (inferredType === 'int64') return { type: 'int64', value: BigInt(Math.trunc(input)) };
return Number.isInteger(input) ? { type: 'int', value: input | 0 } : { type: 'real', value: input };
}
if (!input || typeof input !== 'object') {
throw new BlkPatchError(`${where}: invalid BLK value`);
}
const { type, value } = input;
switch (type) {
case 'string':
if (typeof value !== 'string') throw new BlkPatchError(`${where}: string value expected`);
return { type: 'string', value };
case 'bool':
if (typeof value !== 'boolean') throw new BlkPatchError(`${where}: bool value expected`);
return { type: 'bool', value };
case 'int':
if (typeof value !== 'number' || !Number.isInteger(value)) throw new BlkPatchError(`${where}: int value expected`);
return { type: 'int', value: value | 0 };
case 'real':
if (typeof value !== 'number' || !Number.isFinite(value)) throw new BlkPatchError(`${where}: real value expected`);
return { type: 'real', value };
case 'int64':
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint') {
return { type: 'int64', value: BigInt(value) };
}
throw new BlkPatchError(`${where}: int64 value expected`);
case 'color':
if (typeof value === 'number' && Number.isInteger(value)) return { type: 'color', value: value >>> 0 };
if (Array.isArray(value) && value.length === 4 && value.every((n) => typeof n === 'number')) {
const [r, g, b, a] = value as [number, number, number, number];
return { type: 'color', value: (((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)) >>> 0 };
}
throw new BlkPatchError(`${where}: color expects integer or [r,g,b,a]`);
case 'point2': return { type: 'point2', value: expectNumberTuple(value, 2, false, where) as [number, number] };
case 'point3': return { type: 'point3', value: expectNumberTuple(value, 3, false, where) as [number, number, number] };
case 'point4': return { type: 'point4', value: expectNumberTuple(value, 4, false, where) as [number, number, number, number] };
case 'ipoint2': return { type: 'ipoint2', value: expectNumberTuple(value, 2, true, where) as [number, number] };
case 'ipoint3': return { type: 'ipoint3', value: expectNumberTuple(value, 3, true, where) as [number, number, number] };
case 'ipoint4': return { type: 'ipoint4', value: expectNumberTuple(value, 4, true, where) as [number, number, number, number] };
case 'matrix': return { type: 'matrix', value: expectNumberTuple(value, 12, false, where) };
default:
throw new BlkPatchError(`${where}: unsupported BLK type "${String(type)}"`);
}
}
function expectNumberTuple(raw: unknown, length: number, integerOnly: boolean, where: string): number[] {
if (!Array.isArray(raw) || raw.length !== length) {
throw new BlkPatchError(`${where}: expected array of ${length} numbers`);
}
return raw.map((item) => {
if (typeof item !== 'number' || !Number.isFinite(item) || (integerOnly && !Number.isInteger(item))) {
throw new BlkPatchError(`${where}: invalid numeric element in tuple`);
}
return integerOnly ? (item | 0) : item;
});
}
function paramValueMatchesPrimitive(value: BlkValue, expected: string | number | boolean): boolean {
if (typeof expected === 'string') return value.type === 'string' && value.value === expected;
if (typeof expected === 'boolean') return value.type === 'bool' && value.value === expected;
return (value.type === 'int' || value.type === 'real') && value.value === expected;
}
function validateOp(raw: unknown, where: string): BlkPatchOp {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
throw new BlkPatchError(`${where}: operation must be an object`);
}
const obj = raw as Record<string, unknown>;
const op = obj.op;
switch (op) {
case 'setParam':
case 'addParam':
return {
op,
path: expectStringArray(obj.path ?? [], `${where}.path`),
name: expectNonEmptyString(obj.name, `${where}.name`),
value: obj.value as BlkPatchValueInput,
...(typeof obj.createBlocks === 'boolean' ? { createBlocks: obj.createBlocks } : {}),
};
case 'removeParam':
return {
op,
path: expectStringArray(obj.path ?? [], `${where}.path`),
name: expectNonEmptyString(obj.name, `${where}.name`),
...(typeof obj.value === 'string' || typeof obj.value === 'number' || typeof obj.value === 'boolean'
? { value: obj.value }
: {}),
};
case 'upsertBlock':
return {
op,
path: expectStringArray(obj.path, `${where}.path`),
...(obj.block !== undefined ? { block: validateBlueprint(obj.block, `${where}.block`) } : {}),
};
case 'addBlock':
return {
op,
path: expectStringArray(obj.path ?? [], `${where}.path`),
name: expectNonEmptyString(obj.name, `${where}.name`),
...(obj.block !== undefined ? { block: validateBlueprint(obj.block, `${where}.block`) } : {}),
...(typeof obj.before === 'string' ? { before: obj.before } : {}),
...(typeof obj.after === 'string' ? { after: obj.after } : {}),
...(typeof obj.createBlocks === 'boolean' ? { createBlocks: obj.createBlocks } : {}),
};
case 'removeBlock':
return {
op,
path: expectStringArray(obj.path, `${where}.path`),
};
case 'cloneBlock':
return {
op,
from: expectStringArray(obj.from, `${where}.from`),
toParent: expectStringArray(obj.toParent ?? [], `${where}.toParent`),
newName: expectNonEmptyString(obj.newName, `${where}.newName`),
...(typeof obj.replaceExisting === 'boolean' ? { replaceExisting: obj.replaceExisting } : {}),
...(typeof obj.before === 'string' ? { before: obj.before } : {}),
...(typeof obj.after === 'string' ? { after: obj.after } : {}),
...(Array.isArray(obj.ops)
? { ops: obj.ops.map((nested, idx) => validateOp(nested, `${where}.ops[${idx}]`)) }
: {}),
};
default:
throw new BlkPatchError(`${where}: unsupported op "${String(op)}"`);
}
}
function validateBlueprint(raw: unknown, where: string): BlkBlockBlueprint {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
throw new BlkPatchError(`${where}: block blueprint must be an object`);
}
const obj = raw as Record<string, unknown>;
const name = obj.name === undefined ? undefined : expectNonEmptyString(obj.name, `${where}.name`);
const params = obj.params === undefined ? undefined : expectParamList(obj.params, `${where}.params`);
const blocks = obj.blocks === undefined
? undefined
: (Array.isArray(obj.blocks)
? obj.blocks.map((child, idx) => validateBlueprint(child, `${where}.blocks[${idx}]`))
: (() => { throw new BlkPatchError(`${where}.blocks: must be an array`); })());
return {
...(name !== undefined ? { name } : {}),
...(params !== undefined ? { params } : {}),
...(blocks !== undefined ? { blocks } : {}),
};
}
function expectParamList(raw: unknown, where: string): Array<{ readonly name: string; readonly value: BlkPatchValueInput }> {
if (!Array.isArray(raw)) throw new BlkPatchError(`${where}: must be an array`);
return raw.map((item, idx) => {
if (!item || typeof item !== 'object' || Array.isArray(item)) {
throw new BlkPatchError(`${where}[${idx}]: expected { name, value }`);
}
const entry = item as Record<string, unknown>;
return {
name: expectNonEmptyString(entry.name, `${where}[${idx}].name`),
value: entry.value as BlkPatchValueInput,
};
});
}
function expectStringArray(raw: unknown, where: string): string[] {
if (!Array.isArray(raw) || raw.some((item) => typeof item !== 'string' || item.length === 0)) {
throw new BlkPatchError(`${where}: must be an array of non-empty strings`);
}
return raw as string[];
}
function expectNonEmptyString(raw: unknown, where: string): string {
if (typeof raw !== 'string' || raw.length === 0) {
throw new BlkPatchError(`${where}: must be a non-empty string`);
}
return raw;
}
+140
View File
@@ -0,0 +1,140 @@
/**
* Incremental semicolon-separated localization CSV merger for `lang.vromfs.bin` (`*.csv.patch.csv`).
*
* Keeps the stock file's column layout and quoting conventions while merging matching row keys
* (column 0) and appending new entries from each enabled mod in load order.
*/
export function mergeLocalizationCsv(baseCsv: string, patchCsv: string): string {
const hasBom = baseCsv.startsWith('\uFEFF');
const newline = baseCsv.includes('\r\n') ? '\r\n' : '\n';
const cleanBase = hasBom ? baseCsv.slice(1) : baseCsv;
const cleanPatch = patchCsv.startsWith('\uFEFF') ? patchCsv.slice(1) : patchCsv;
const baseLines = splitCsvLines(cleanBase);
const patchLines = splitCsvLines(cleanPatch);
if (baseLines.length === 0 || patchLines.length <= 1) return baseCsv;
const baseHeader = parseSemicolonRow(baseLines[0]!);
const patchHeader = parseSemicolonRow(patchLines[0]!);
const baseColIndex = new Map<string, number>();
baseHeader.forEach((name, idx) => baseColIndex.set(name.trim(), idx));
const colMapping: Array<{ readonly patchIdx: number; readonly baseIdx: number }> = [];
for (let pIdx = 1; pIdx < patchHeader.length; pIdx += 1) {
const colName = patchHeader[pIdx]!.trim();
const bIdx = baseColIndex.get(colName);
if (bIdx !== undefined) colMapping.push({ patchIdx: pIdx, baseIdx: bIdx });
}
if (colMapping.length === 0) return baseCsv;
// Map existing key -> line index in baseLines for fast in-place updates.
const rowIndexByKey = new Map<string, number>();
for (let i = 1; i < baseLines.length; i += 1) {
const line = baseLines[i]!;
if (!line.trim()) continue;
const key = firstField(line);
if (key) rowIndexByKey.set(key, i);
}
const outLines = [...baseLines];
const trailingBlank = outLines.length > 0 && outLines[outLines.length - 1] === '';
if (trailingBlank) outLines.pop();
for (let i = 1; i < patchLines.length; i += 1) {
const line = patchLines[i]!;
if (!line.trim()) continue;
const patchCols = parseSemicolonRow(line);
const key = patchCols[0] ?? '';
if (!key) continue;
const existingIdx = rowIndexByKey.get(key);
if (existingIdx !== undefined) {
const merged = parseSemicolonRow(outLines[existingIdx]!);
while (merged.length < baseHeader.length) merged.push('');
for (const { patchIdx, baseIdx } of colMapping) {
const replacement = patchCols[patchIdx];
if (replacement !== undefined && replacement !== '') merged[baseIdx] = replacement;
}
outLines[existingIdx] = formatSemicolonRow(merged);
} else {
const created = new Array<string>(baseHeader.length).fill('');
created[0] = key;
for (const { patchIdx, baseIdx } of colMapping) {
const val = patchCols[patchIdx];
if (val !== undefined) created[baseIdx] = val;
}
rowIndexByKey.set(key, outLines.length);
outLines.push(formatSemicolonRow(created));
}
}
const result = outLines.join(newline) + (trailingBlank ? newline : '');
return hasBom ? `\uFEFF${result}` : result;
}
function splitCsvLines(text: string): string[] {
// Handle quoted fields that may span multiple lines.
const lines: string[] = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < text.length; i += 1) {
const ch = text[i]!;
if (ch === '"') {
if (inQuotes && text[i + 1] === '"') {
current += '""';
i += 1;
} else {
inQuotes = !inQuotes;
current += ch;
}
continue;
}
if (!inQuotes && (ch === '\n' || (ch === '\r' && text[i + 1] === '\n'))) {
lines.push(current);
current = '';
if (ch === '\r') i += 1;
continue;
}
current += ch;
}
lines.push(current);
return lines;
}
function parseSemicolonRow(line: string): string[] {
const fields: string[] = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < line.length; i += 1) {
const ch = line[i]!;
if (ch === '"') {
if (inQuotes && line[i + 1] === '"') {
current += '"';
i += 1;
} else {
inQuotes = !inQuotes;
}
} else if (ch === ';' && !inQuotes) {
fields.push(current);
current = '';
} else {
current += ch;
}
}
fields.push(current);
return fields;
}
function firstField(line: string): string {
if (line.startsWith('"')) {
const cols = parseSemicolonRow(line);
return cols[0] ?? '';
}
const semi = line.indexOf(';');
return semi >= 0 ? line.slice(0, semi) : line;
}
function formatSemicolonRow(fields: readonly string[]): string {
return fields.map((field) => `"${field.replaceAll('"', '""')}"`).join(';');
}
+252
View File
@@ -0,0 +1,252 @@
/**
* Discover installed mods inside the global mods directory and inspect their capabilities
* (server tuning/script, client pack patches, GUI patches, declarative exe patches,
* 3D model addons, and optional companion files).
*/
import { existsSync, readdirSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
import { MOD_MANIFEST_FILE, readModManifest } from './manifest.ts';
import {
MODDABLE_CLIENT_PACKS,
type DiscoveredMod,
type ModContentSummary,
type ModDiscoveryError,
type ModDiscoveryResult,
type ModManifest,
type ModPackOperation,
type ModRiskBadge,
type ModdableClientPack,
} from './types.ts';
const DEFAULT_SERVER_ENTRIES = ['server/index.ts', 'server/index.mjs', 'server/index.js'] as const;
const DEFAULT_SERVER_TUNING_DIR = 'server/tuning';
const BLK_PATCH_SUFFIX = '.patch.jsonc';
const CSV_PATCH_SUFFIX = '.patch.csv';
const CONFIG_BLK_PATCH_PATH = 'client/config-blk.patch.jsonc';
export function discoverMods(modsRootDir: string): ModDiscoveryResult {
if (!existsSync(modsRootDir)) return { mods: [], errors: [] };
const mods: DiscoveredMod[] = [];
const errors: ModDiscoveryError[] = [];
const seenIds = new Map<string, string>();
let entries;
try {
entries = readdirSync(modsRootDir, { withFileTypes: true });
} catch (error) {
return {
mods: [],
errors: [{ folderName: '.', rootDir: modsRootDir, reason: error instanceof Error ? error.message : String(error) }],
};
}
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const rootDir = join(modsRootDir, entry.name);
if (!existsSync(join(rootDir, MOD_MANIFEST_FILE))) continue;
try {
const manifest = readModManifest(rootDir);
const duplicateFolder = seenIds.get(manifest.id);
if (duplicateFolder) {
errors.push({
folderName: entry.name,
rootDir,
reason: `duplicate mod id "${manifest.id}" (already provided by folder "${duplicateFolder}")`,
});
continue;
}
seenIds.set(manifest.id, entry.name);
const content = inspectModContent(rootDir, manifest);
mods.push({ folderName: entry.name, rootDir, manifest, content });
} catch (error) {
errors.push({
folderName: entry.name,
rootDir,
reason: error instanceof Error ? error.message : String(error),
});
}
}
mods.sort((left, right) => left.manifest.id.localeCompare(right.manifest.id));
errors.sort((left, right) => left.folderName.localeCompare(right.folderName));
return { mods, errors };
}
export function inspectModContent(rootDir: string, manifest: ModManifest): ModContentSummary {
const serverEntry = resolveServerEntry(rootDir, manifest);
const tuningDirRel = manifest.server?.tuning ?? DEFAULT_SERVER_TUNING_DIR;
const serverTuningFiles = listTuningFiles(rootDir, tuningDirRel);
const packOperations = scanClientPackOperations(rootDir);
const guiPatchDirs = scanPatchDirectories(rootDir, 'client/gui-patches');
const exePatchDirs = scanPatchDirectories(rootDir, 'client/exe-patches');
const addonDir = join(rootDir, 'client', 'addon');
const addonRelativeFiles = existsSync(addonDir) && isDirectory(addonDir)
? listRelativeFiles(addonDir)
: [];
const hasClientAddon = addonRelativeFiles.length > 0;
const addonHasGrpHdr = addonRelativeFiles.some((file) => file.toLowerCase() === 'res/grp_hdr.vromfs.bin');
const filesDir = join(rootDir, 'client', 'files');
const clientFiles = existsSync(filesDir) && isDirectory(filesDir)
? listRelativeFiles(filesDir)
: [];
const configBlkPatch = isFile(join(rootDir, ...CONFIG_BLK_PATCH_PATH.split('/')))
? CONFIG_BLK_PATCH_PATH
: undefined;
const badges = computeRiskBadges({
hasData: serverTuningFiles.length > 0 || packOperations.length > 0 || hasClientAddon || clientFiles.length > 0 || configBlkPatch !== undefined,
hasGui: guiPatchDirs.length > 0,
hasScript: serverEntry !== undefined,
hasExe: exePatchDirs.length > 0,
});
return {
...(serverEntry !== undefined ? { serverEntry } : {}),
serverTuningFiles,
packOperations,
guiPatchDirs,
exePatchDirs,
hasClientAddon,
addonHasGrpHdr,
addonRelativeFiles,
clientFiles,
...(configBlkPatch !== undefined ? { configBlkPatch } : {}),
badges,
};
}
function resolveServerEntry(rootDir: string, manifest: ModManifest): string | undefined {
if (manifest.server?.entry) {
const full = join(rootDir, ...manifest.server.entry.split('/'));
if (!isFile(full)) {
throw new Error(`declared server.entry "${manifest.server.entry}" does not exist`);
}
return manifest.server.entry;
}
for (const candidate of DEFAULT_SERVER_ENTRIES) {
if (isFile(join(rootDir, ...candidate.split('/')))) return candidate;
}
return undefined;
}
function listTuningFiles(rootDir: string, tuningDirRel: string): string[] {
const dir = join(rootDir, ...tuningDirRel.split('/'));
if (!isDirectory(dir)) return [];
return readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isFile() && entry.name.endsWith('.jsonc'))
.map((entry) => entry.name.slice(0, -'.jsonc'.length))
.sort();
}
function scanClientPackOperations(rootDir: string): ModPackOperation[] {
const packsRoot = join(rootDir, 'client', 'packs');
if (!isDirectory(packsRoot)) return [];
const ops: ModPackOperation[] = [];
for (const pack of MODDABLE_CLIENT_PACKS) {
const packDir = join(packsRoot, ...pack.split('/'));
if (!isDirectory(packDir)) continue;
for (const rel of listRelativeFiles(packDir)) {
const sourceRelativePath = `client/packs/${pack}/${rel}`;
if (rel.toLowerCase().endsWith(BLK_PATCH_SUFFIX)) {
ops.push({
pack,
targetPath: rel.slice(0, -BLK_PATCH_SUFFIX.length),
action: 'blk-patch',
sourceRelativePath,
});
} else if (rel.toLowerCase().endsWith(CSV_PATCH_SUFFIX)) {
ops.push({
pack,
targetPath: rel.slice(0, -CSV_PATCH_SUFFIX.length),
action: 'csv-patch',
sourceRelativePath,
});
} else {
ops.push({
pack,
targetPath: rel,
action: 'file',
sourceRelativePath,
});
}
}
}
return ops;
}
function scanPatchDirectories(rootDir: string, subPath: string): string[] {
const base = join(rootDir, ...subPath.split('/'));
if (!isDirectory(base)) return [];
const results: string[] = [];
const walk = (current: string) => {
for (const entry of readdirSync(current, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const full = join(current, entry.name);
if (isFile(join(full, 'patch.jsonc'))) {
results.push(relative(rootDir, full).replaceAll('\\', '/'));
} else {
walk(full);
}
}
};
walk(base);
return results.sort();
}
function listRelativeFiles(dir: string): string[] {
const out: string[] = [];
const walk = (current: string) => {
for (const entry of readdirSync(current, { withFileTypes: true })) {
const full = join(current, entry.name);
if (entry.isDirectory()) walk(full);
else if (entry.isFile()) out.push(relative(dir, full).replaceAll('\\', '/'));
}
};
walk(dir);
return out.sort();
}
function computeRiskBadges(flags: {
readonly hasData: boolean;
readonly hasGui: boolean;
readonly hasScript: boolean;
readonly hasExe: boolean;
}): ModRiskBadge[] {
const badges: ModRiskBadge[] = [];
if (flags.hasData || (!flags.hasGui && !flags.hasScript && !flags.hasExe)) badges.push('data');
if (flags.hasGui) badges.push('gui');
if (flags.hasScript) badges.push('script');
if (flags.hasExe) badges.push('exe');
return badges;
}
function isFile(path: string): boolean {
try {
return statSync(path).isFile();
} catch {
return false;
}
}
function isDirectory(path: string): boolean {
try {
return statSync(path).isDirectory();
} catch {
return false;
}
}
export function touchedClientPacks(mods: readonly DiscoveredMod[]): ModdableClientPack[] {
const set = new Set<ModdableClientPack>();
for (const mod of mods) {
for (const op of mod.content.packOperations) set.add(op.pack);
if (mod.content.guiPatchDirs.length > 0) set.add('gui.vromfs.bin');
if (mod.content.hasClientAddon) set.add('aces.vromfs.bin');
}
return MODDABLE_CLIENT_PACKS.filter((pack) => set.has(pack));
}
+81
View File
@@ -0,0 +1,81 @@
/**
* Shared additive mod system core: manifest parsing, mod discovery, load-order & conflict
* resolution, type-preserving BLK incremental patching, localization CSV merging, multi-layer
* tuning `$listOps` merging, and experimental server mod contracts.
*/
export {
MOD_API_VERSION,
MOD_FORMAT_VERSION,
MODDABLE_CLIENT_PACKS,
resolveLocalizedText,
type ClientModsConfig,
type DiscoveredMod,
type LocalizedText,
type ModContentSummary,
type ModDiscoveryError,
type ModDiscoveryResult,
type ModIssue,
type ModIssueKind,
type ModIssueSeverity,
type ModManifest,
type ModPackOperation,
type ModPreset,
type ModRiskBadge,
type ModServerConfig,
type ModdableClientPack,
type PackFileAction,
type ResolvedModLoadOrder,
} from './types.ts';
export {
MOD_MANIFEST_FILE,
ModManifestError,
expectSafeRelativePath,
parseModManifest,
readModManifest,
} from './manifest.ts';
export { discoverMods, inspectModContent, touchedClientPacks } from './discovery.ts';
export {
computeAutoSortOrder,
emptyClientModsConfig,
matchesVersionPattern,
normalizeClientModsConfig,
resolveModLoadOrder,
} from './resolve.ts';
export {
BlkPatchError,
applyBlkPatch,
parseBlkPatchDocument,
type BlkBlockBlueprint,
type BlkPatchDocument,
type BlkPatchOp,
type BlkPatchValueInput,
type BlkPathStep,
} from './blk-patch.ts';
export { mergeLocalizationCsv } from './csv-patch.ts';
export { mergeTuningLayer, type TuningListOp } from './tuning-merge.ts';
export type {
BattleFilterMissionsContext,
BattleLiveFactContext,
BattleMatchmakeContext,
BattleMissionCandidate,
BattleSettlementContext,
ModCharHandler,
ModCharRequest,
ModCharResponse,
ModCharWrapper,
ModHttpHandler,
ModHttpRequest,
ModHttpResponse,
ModLogger,
ModMatchingHandler,
ModMatchingRequest,
ModMatchingWrapper,
ModPlayerStorage,
ModStorageApi,
ServerModCataloguesView,
ServerModDatasetsView,
ServerModHooksApi,
ServerModRoutesApi,
WtoServerMod,
WtoServerModContext,
} from './server-api.ts';
+159
View File
@@ -0,0 +1,159 @@
/**
* Parse and validate `mod.jsonc` manifests.
*/
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { parseJsonc } from '@wto/jsonc';
import { MOD_FORMAT_VERSION, type LocalizedText, type ModManifest, type ModServerConfig } from './types.ts';
export const MOD_MANIFEST_FILE = 'mod.jsonc';
const MOD_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
const ALLOWED_ROOT_KEYS = new Set([
'format',
'id',
'name',
'version',
'author',
'description',
'api_version',
'game_versions',
'requires',
'conflicts',
'load_after',
'load_before',
'server',
]);
const ALLOWED_SERVER_KEYS = new Set(['entry', 'tuning']);
export class ModManifestError extends Error {
override name = 'ModManifestError';
}
export function readModManifest(modDir: string): ModManifest {
const filePath = join(modDir, MOD_MANIFEST_FILE);
let raw: unknown;
try {
raw = parseJsonc(readFileSync(filePath, 'utf8'));
} catch (error) {
throw new ModManifestError(`cannot parse ${MOD_MANIFEST_FILE}: ${error instanceof Error ? error.message : String(error)}`);
}
return parseModManifest(raw, filePath);
}
export function parseModManifest(raw: unknown, where = MOD_MANIFEST_FILE): ModManifest {
const obj = expectObject(raw, where);
rejectUnknownKeys(obj, ALLOWED_ROOT_KEYS, where);
if (obj.format !== MOD_FORMAT_VERSION) {
throw new ModManifestError(`${where}: "format" must be ${MOD_FORMAT_VERSION}`);
}
const id = expectString(obj.id, `${where} "id"`);
if (!MOD_ID_PATTERN.test(id)) {
throw new ModManifestError(`${where}: "id" must match ${MOD_ID_PATTERN.source} (got "${id}")`);
}
const name = expectLocalizedText(obj.name, `${where} "name"`);
const version = expectString(obj.version, `${where} "version"`);
const author = expectString(obj.author, `${where} "author"`);
const description = obj.description === undefined ? undefined : expectLocalizedText(obj.description, `${where} "description"`);
const apiVersion = expectString(obj.api_version, `${where} "api_version"`);
const gameVersions = optionalStringList(obj.game_versions, `${where} "game_versions"`);
const requires = optionalIdList(obj.requires, `${where} "requires"`, id);
const conflicts = optionalIdList(obj.conflicts, `${where} "conflicts"`, id);
const loadAfter = optionalIdList(obj.load_after, `${where} "load_after"`, id);
const loadBefore = optionalIdList(obj.load_before, `${where} "load_before"`, id);
const server = obj.server === undefined ? undefined : parseServerConfig(obj.server, `${where} "server"`);
return {
format: MOD_FORMAT_VERSION,
id,
name,
version,
author,
...(description !== undefined ? { description } : {}),
apiVersion,
gameVersions,
requires,
conflicts,
loadAfter,
loadBefore,
...(server !== undefined ? { server } : {}),
};
}
function parseServerConfig(raw: unknown, where: string): ModServerConfig {
const obj = expectObject(raw, where);
rejectUnknownKeys(obj, ALLOWED_SERVER_KEYS, where);
const entry = obj.entry === undefined ? undefined : expectSafeRelativePath(obj.entry, `${where} "entry"`);
const tuning = obj.tuning === undefined ? undefined : expectSafeRelativePath(obj.tuning, `${where} "tuning"`);
return {
...(entry !== undefined ? { entry } : {}),
...(tuning !== undefined ? { tuning } : {}),
};
}
export function expectSafeRelativePath(raw: unknown, where: string): string {
const text = expectString(raw, where).replaceAll('\\', '/');
if (text.startsWith('/') || /^[A-Za-z]:/.test(text)) {
throw new ModManifestError(`${where}: path must be relative to the mod folder (got "${text}")`);
}
const segments = text.split('/').filter((segment) => segment.length > 0);
if (segments.length === 0 || segments.some((segment) => segment === '.' || segment === '..')) {
throw new ModManifestError(`${where}: path must not contain "." or ".." segments (got "${text}")`);
}
return segments.join('/');
}
function expectObject(value: unknown, where: string): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new ModManifestError(`${where}: expected an object`);
}
return value as Record<string, unknown>;
}
function rejectUnknownKeys(obj: Record<string, unknown>, allowed: ReadonlySet<string>, where: string): void {
const unknown = Object.keys(obj).filter((key) => !allowed.has(key));
if (unknown.length > 0) {
throw new ModManifestError(`${where}: unknown field(s): ${unknown.join(', ')}`);
}
}
function expectString(value: unknown, where: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new ModManifestError(`${where}: must be a non-empty string`);
}
return value.trim();
}
function expectLocalizedText(value: unknown, where: string): LocalizedText {
if (typeof value === 'string') {
if (value.trim().length === 0) throw new ModManifestError(`${where}: must not be empty`);
return value.trim();
}
const obj = expectObject(value, where);
const entries = Object.entries(obj);
if (entries.length === 0) throw new ModManifestError(`${where}: localized map must not be empty`);
const out: Record<string, string> = {};
for (const [lang, text] of entries) {
out[lang] = expectString(text, `${where}.${lang}`);
}
return out;
}
function optionalStringList(value: unknown, where: string): readonly string[] {
if (value === undefined) return [];
if (!Array.isArray(value)) throw new ModManifestError(`${where}: must be an array of strings`);
return value.map((item, index) => expectString(item, `${where}[${index}]`));
}
function optionalIdList(value: unknown, where: string, selfId: string): readonly string[] {
const ids = optionalStringList(value, where);
const seen = new Set<string>();
for (const id of ids) {
if (!MOD_ID_PATTERN.test(id)) throw new ModManifestError(`${where}: invalid mod id "${id}"`);
if (id === selfId) throw new ModManifestError(`${where}: mod cannot reference itself ("${id}")`);
if (seen.has(id)) throw new ModManifestError(`${where}: duplicate mod id "${id}"`);
seen.add(id);
}
return ids;
}
+333
View File
@@ -0,0 +1,333 @@
/**
* Resolve effective mod load order, check dependencies/conflicts/version compatibility,
* detect overlapping pack or companion file targets, and offer topological auto-sorting.
*/
import {
MOD_API_VERSION,
type ClientModsConfig,
type DiscoveredMod,
type ModIssue,
type ResolvedModLoadOrder,
} from './types.ts';
export function emptyClientModsConfig(): ClientModsConfig {
return {
format: 1,
order: [],
enabled: {},
activePresetId: null,
presets: [],
};
}
/**
* Reconcile a saved client config with the currently discovered mods:
* keep saved order for known mods, append newly discovered mods alphabetically (disabled by default),
* and drop removed mod ids from the active ordering without destroying saved presets.
*/
export function normalizeClientModsConfig(
config: ClientModsConfig,
discovered: readonly DiscoveredMod[],
): ClientModsConfig {
const knownIds = new Set(discovered.map((mod) => mod.manifest.id));
const seen = new Set<string>();
const order: string[] = [];
for (const id of config.order) {
if (knownIds.has(id) && !seen.has(id)) {
seen.add(id);
order.push(id);
}
}
for (const mod of discovered) {
if (!seen.has(mod.manifest.id)) {
seen.add(mod.manifest.id);
order.push(mod.manifest.id);
}
}
const enabled: Record<string, boolean> = {};
for (const id of order) {
enabled[id] = config.enabled[id] === true;
}
return {
format: 1,
order,
enabled,
activePresetId: config.activePresetId,
presets: config.presets,
};
}
export function resolveModLoadOrder(
discovered: readonly DiscoveredMod[],
config: Pick<ClientModsConfig, 'order' | 'enabled'>,
gameVersion?: string | null,
): ResolvedModLoadOrder {
const byId = new Map(discovered.map((mod) => [mod.manifest.id, mod]));
const orderedIds: string[] = [];
const seen = new Set<string>();
for (const id of config.order) {
if (byId.has(id) && !seen.has(id)) {
seen.add(id);
orderedIds.push(id);
}
}
for (const mod of discovered) {
if (!seen.has(mod.manifest.id)) {
seen.add(mod.manifest.id);
orderedIds.push(mod.manifest.id);
}
}
const enabledMods = orderedIds
.filter((id) => config.enabled[id] === true)
.map((id) => byId.get(id)!);
const enabledIndex = new Map(enabledMods.map((mod, index) => [mod.manifest.id, index]));
const issues: ModIssue[] = [];
for (const mod of enabledMods) {
const id = mod.manifest.id;
const pos = enabledIndex.get(id)!;
if (mod.manifest.apiVersion !== MOD_API_VERSION) {
issues.push({
severity: 'warning',
kind: 'api-version-mismatch',
modId: id,
detail: `mod targets api_version "${mod.manifest.apiVersion}", current experimental API is "${MOD_API_VERSION}"`,
});
}
if (gameVersion && mod.manifest.gameVersions.length > 0 && !matchesAnyVersionPattern(gameVersion, mod.manifest.gameVersions)) {
issues.push({
severity: 'warning',
kind: 'game-version-mismatch',
modId: id,
detail: `mod lists game_versions [${mod.manifest.gameVersions.join(', ')}], client is ${gameVersion}`,
});
}
for (const reqId of mod.manifest.requires) {
if (!byId.has(reqId)) {
issues.push({
severity: 'error',
kind: 'missing-dependency',
modId: id,
otherModId: reqId,
detail: `requires missing mod "${reqId}"`,
});
} else if (!enabledIndex.has(reqId)) {
issues.push({
severity: 'error',
kind: 'dependency-disabled',
modId: id,
otherModId: reqId,
detail: `requires disabled mod "${reqId}"`,
});
} else if (enabledIndex.get(reqId)! > pos) {
issues.push({
severity: 'warning',
kind: 'dependency-order',
modId: id,
otherModId: reqId,
detail: `loaded before required dependency "${reqId}"`,
});
}
}
for (const conflictId of mod.manifest.conflicts) {
if (enabledIndex.has(conflictId) && id < conflictId) {
issues.push({
severity: 'error',
kind: 'declared-conflict',
modId: id,
otherModId: conflictId,
detail: `declares incompatibility with "${conflictId}"`,
});
}
}
for (const afterId of mod.manifest.loadAfter) {
const otherPos = enabledIndex.get(afterId);
if (otherPos !== undefined && otherPos > pos) {
issues.push({
severity: 'warning',
kind: 'load-order-hint',
modId: id,
otherModId: afterId,
detail: `recommends loading after "${afterId}"`,
});
}
}
for (const beforeId of mod.manifest.loadBefore) {
const otherPos = enabledIndex.get(beforeId);
if (otherPos !== undefined && otherPos < pos) {
issues.push({
severity: 'warning',
kind: 'load-order-hint',
modId: id,
otherModId: beforeId,
detail: `recommends loading before "${beforeId}"`,
});
}
}
}
detectTargetOverlaps(enabledMods, issues);
return {
enabledMods,
issues,
hasBlockingErrors: issues.some((issue) => issue.severity === 'error'),
};
}
/**
* Topologically sort mods using `requires`, `load_after`, and `load_before` constraints.
* Falls back gracefully to existing relative order when cycles exist.
*/
export function computeAutoSortOrder(
discovered: readonly DiscoveredMod[],
currentOrder: readonly string[],
): string[] {
const rank = new Map<string, number>();
currentOrder.forEach((id, index) => rank.set(id, index));
const ids = discovered.map((mod) => mod.manifest.id);
const idSet = new Set(ids);
const edges = new Map<string, Set<string>>(ids.map((id) => [id, new Set()]));
const inDegree = new Map<string, number>(ids.map((id) => [id, 0]));
const addEdge = (before: string, after: string) => {
if (!idSet.has(before) || !idSet.has(after) || before === after) return;
const outgoing = edges.get(before)!;
if (!outgoing.has(after)) {
outgoing.add(after);
inDegree.set(after, (inDegree.get(after) ?? 0) + 1);
}
};
for (const mod of discovered) {
const id = mod.manifest.id;
for (const req of mod.manifest.requires) addEdge(req, id);
for (const after of mod.manifest.loadAfter) addEdge(after, id);
for (const before of mod.manifest.loadBefore) addEdge(id, before);
}
const comparePriority = (a: string, b: string) => {
const ra = rank.get(a) ?? Number.MAX_SAFE_INTEGER;
const rb = rank.get(b) ?? Number.MAX_SAFE_INTEGER;
return ra !== rb ? ra - rb : a.localeCompare(b);
};
const ready = ids.filter((id) => (inDegree.get(id) ?? 0) === 0).sort(comparePriority);
const result: string[] = [];
while (ready.length > 0) {
const next = ready.shift()!;
result.push(next);
for (const target of edges.get(next)!) {
const deg = (inDegree.get(target) ?? 1) - 1;
inDegree.set(target, deg);
if (deg === 0) {
ready.push(target);
ready.sort(comparePriority);
}
}
}
if (result.length < ids.length) {
const placed = new Set(result);
const remaining = ids.filter((id) => !placed.has(id)).sort(comparePriority);
result.push(...remaining);
}
return result;
}
function detectTargetOverlaps(enabledMods: readonly DiscoveredMod[], issues: ModIssue[]): void {
const packFiles = new Map<string, string>();
const packPatches = new Map<string, string>();
const companionFiles = new Map<string, string>();
const tuningFiles = new Map<string, string>();
for (const mod of enabledMods) {
const id = mod.manifest.id;
for (const op of mod.content.packOperations) {
const key = `${op.pack}:${op.targetPath.toLowerCase()}`;
if (op.action === 'file') {
const previous = packFiles.get(key) ?? packPatches.get(key);
if (previous && previous !== id) {
issues.push({
severity: 'warning',
kind: 'pack-file-override',
modId: id,
otherModId: previous,
detail: `replaces "${op.pack}/${op.targetPath}" already modified by "${previous}"`,
});
}
packFiles.set(key, id);
} else {
const previousFile = packFiles.get(key);
const previousPatch = packPatches.get(key);
if (previousFile && previousFile !== id) {
issues.push({
severity: 'info',
kind: 'pack-blk-shared-target',
modId: id,
otherModId: previousFile,
detail: `patches "${op.pack}/${op.targetPath}" after "${previousFile}"`,
});
} else if (previousPatch && previousPatch !== id) {
issues.push({
severity: 'info',
kind: 'pack-blk-shared-target',
modId: id,
otherModId: previousPatch,
detail: `merges into "${op.pack}/${op.targetPath}" after "${previousPatch}"`,
});
}
packPatches.set(key, id);
}
}
for (const file of mod.content.clientFiles) {
const key = file.toLowerCase();
const previous = companionFiles.get(key);
if (previous && previous !== id) {
issues.push({
severity: 'warning',
kind: 'client-file-conflict',
modId: id,
otherModId: previous,
detail: `companion file "${file}" overrides "${previous}"`,
});
}
companionFiles.set(key, id);
}
for (const tuning of mod.content.serverTuningFiles) {
const key = tuning.toLowerCase();
const previous = tuningFiles.get(key);
if (previous && previous !== id) {
issues.push({
severity: 'info',
kind: 'tuning-file-shared',
modId: id,
otherModId: previous,
detail: `merges server tuning "${tuning}.jsonc" after "${previous}"`,
});
}
tuningFiles.set(key, id);
}
}
}
export function matchesVersionPattern(version: string, pattern: string): boolean {
if (pattern === '*') return true;
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replaceAll('*', '.*');
return new RegExp(`^${escaped}$`).test(version);
}
function matchesAnyVersionPattern(version: string, patterns: readonly string[]): boolean {
return patterns.some((pattern) => matchesVersionPattern(version, pattern));
}
+205
View File
@@ -0,0 +1,205 @@
/**
* Public TypeScript contract for WTOffline server-side JS/TS mods.
*
* EXPERIMENTAL / UNSTABLE:
* WTOffline is in early development. Internal server types, dataset shapes, hook signatures,
* and route contracts may change without backwards compatibility across releases. Mod authors
* using server scripts should expect breaking changes and maintain compatibility with updates.
*/
import type { BlkBlock } from '@wto/blk';
import type { ModManifest } from './types.ts';
export interface ModLogger {
info(message: string): void;
warn(message: string): void;
error(message: string): void;
}
/** Per-account JSON storage isolated under `<dataFolder>/saves/<userId>/mods/<modId>.json`. */
export interface ModPlayerStorage {
read<T = unknown>(): T | undefined;
write(value: unknown): void;
remove(): void;
}
export interface ModStorageApi {
/** Storage scoped to one local player account (never mutates stock `profile.blk`). */
forPlayer(userId: string): ModPlayerStorage;
/** Shared mod storage under `<dataFolder>/mods-data/<modId>.json`. */
shared(): ModPlayerStorage;
}
/** Mutable snapshot of extracted static datasets exposed before domain catalogues are built. */
export interface ServerModDatasetsView {
readonly vehicles: unknown[];
readonly battleEconomy: Record<string, unknown>;
readonly battleSpawnRules: unknown;
readonly multiplayerMissions: Record<string, unknown>;
readonly uiLabels: Record<string, unknown>;
readonly unitNames: Record<string, unknown>;
/** Escape hatch: read or replace any dataset object by its dataset id. */
get<T = unknown>(datasetId: string): T | undefined;
set(datasetId: string, value: unknown): void;
}
/** Exposed domain catalogues and services after server initialization. */
export interface ServerModCataloguesView {
readonly tuning: Readonly<Record<string, unknown>>;
readonly gameModes: unknown;
readonly profiles: unknown;
readonly accounts: unknown;
readonly research: unknown;
readonly equipment: unknown;
readonly repair: unknown;
readonly store: unknown;
readonly inventory: unknown;
readonly trophies: unknown;
readonly items: unknown;
readonly crew: unknown;
readonly decor: unknown;
readonly unlocks: unknown;
readonly clans: unknown;
readonly battleMatchmaker: unknown;
readonly battleEconomy: unknown;
readonly battleStreaks: unknown;
readonly notifyInventoryChanged: () => void;
readonly notifyUser: (userId: string, eventName: string, payload: Record<string, unknown>) => void;
}
export interface BattleMatchmakeContext {
readonly userId: string;
readonly eventName: string;
/** Mutable room / matchmake request parameters or generated launch plan. */
readonly request: Record<string, unknown>;
}
export interface BattleMissionCandidate {
readonly name: string;
readonly path: string;
readonly level?: string;
readonly type?: string;
readonly locName?: string;
readonly postfix?: string;
}
export interface BattleFilterMissionsContext {
readonly userId: string;
readonly modeId: number;
readonly modeName: string;
readonly economicName: string;
readonly minMrank: number;
readonly maxMrank: number;
readonly missions: readonly BattleMissionCandidate[];
}
export interface BattleLiveFactContext {
readonly userId: string;
readonly roomId: string;
readonly fact: Record<string, unknown>;
}
export interface BattleSettlementContext {
readonly userId: string;
readonly roomId: string;
/** Mutable settlement payload before final rewards are committed to the profile. */
readonly summary: Record<string, unknown>;
}
export interface ModCharRequest {
readonly action: string;
readonly userId: string;
readonly headers: Readonly<Record<string, string | undefined>>;
readonly body: Buffer;
readonly query: Readonly<Record<string, string>>;
}
export interface ModCharResponse {
readonly status?: number;
readonly contentType?: string;
readonly headers?: Readonly<Record<string, string>>;
readonly body: Buffer | Uint8Array | string;
}
export type ModCharHandler = (request: ModCharRequest) => ModCharResponse | Promise<ModCharResponse>;
export type ModCharWrapper = (
request: ModCharRequest,
next: (request: ModCharRequest) => Promise<ModCharResponse>,
) => ModCharResponse | Promise<ModCharResponse>;
export interface ModMatchingRequest {
readonly method: string;
readonly params: Readonly<Record<string, unknown>>;
readonly userId: string | undefined;
}
export type ModMatchingHandler = (request: ModMatchingRequest) => Record<string, unknown>;
export type ModMatchingWrapper = (
request: ModMatchingRequest,
next: (request: ModMatchingRequest) => Record<string, unknown>,
) => Record<string, unknown>;
export interface ModHttpRequest {
readonly method: string;
readonly path: string;
readonly query: Readonly<Record<string, string>>;
readonly headers: Readonly<Record<string, string | undefined>>;
readonly body: Buffer;
}
export interface ModHttpResponse {
readonly status?: number;
readonly contentType?: string;
readonly headers?: Readonly<Record<string, string>>;
readonly body: Buffer | Uint8Array | string;
}
export type ModHttpHandler = (request: ModHttpRequest) => ModHttpResponse | Promise<ModHttpResponse>;
export interface ServerModHooksApi {
onDatasetsLoaded(handler: (datasets: ServerModDatasetsView) => void | Promise<void>): void;
onCataloguesReady(handler: (catalogues: ServerModCataloguesView) => void | Promise<void>): void;
onServerListening(handler: (info: { readonly port: number }) => void | Promise<void>): void;
onServerClosing(handler: () => void | Promise<void>): void;
readonly profile: {
onRefresh(handler: (profile: BlkBlock, userId: string) => void): void;
};
readonly battle: {
onBeforeMatchmake(handler: (ctx: BattleMatchmakeContext) => void): void;
/** Filter or reorder candidate missions before matchmaking picks one; return the desired subset. */
onFilterMissions(handler: (ctx: BattleFilterMissionsContext) => readonly BattleMissionCandidate[] | void): void;
onLiveFact(handler: (ctx: BattleLiveFactContext) => void): void;
onAfterSettle(handler: (ctx: BattleSettlementContext) => void): void;
};
}
export interface ServerModRoutesApi {
readonly char: {
register(action: string, handler: ModCharHandler): void;
wrap(action: string, wrapper: ModCharWrapper): void;
};
readonly matching: {
register(method: string, handler: ModMatchingHandler): void;
wrap(method: string, wrapper: ModMatchingWrapper): void;
};
readonly http: {
/** Register a route under `/mods/<modId>/...` (automatically namespaced to this mod). */
register(subPath: string, handler: ModHttpHandler): void;
};
}
export interface WtoServerModContext {
readonly apiVersion: string;
readonly manifest: ModManifest;
readonly modDir: string;
readonly gameFolder: string;
readonly dataFolder: string;
readonly port: number;
readonly logger: ModLogger;
readonly storage: ModStorageApi;
readonly hooks: ServerModHooksApi;
readonly routes: ServerModRoutesApi;
}
export interface WtoServerMod {
setup(ctx: WtoServerModContext): void | Promise<void>;
}
+77
View File
@@ -0,0 +1,77 @@
/**
* Multi-layer tuning merge helper with additive list operations (`$listOps`).
*
* Objects merge key-by-key. Plain arrays replace the base value (preserving existing player
* override behaviour). An object containing only `{ "$listOps": [...] }` applies incremental
* append/prepend/upsertBy/removeBy operations to the base array so multiple mods can add
* store packs, redeem codes, trophies, or preset clans without clobbering one another.
*/
export type TuningListOp =
| { readonly op: 'append'; readonly items: readonly unknown[] }
| { readonly op: 'prepend'; readonly items: readonly unknown[] }
| { readonly op: 'upsertBy'; readonly key: string; readonly item: Record<string, unknown> }
| { readonly op: 'removeBy'; readonly key: string; readonly value: unknown };
export function mergeTuningLayer(base: unknown, override: unknown): unknown {
if (isListOpsEnvelope(override)) {
const list = Array.isArray(base) ? [...base] : [];
return applyListOps(list, override.$listOps);
}
if (!isPlainObject(base) || !isPlainObject(override)) return override;
const merged: Record<string, unknown> = { ...base };
for (const [key, value] of Object.entries(override)) {
merged[key] = key in base ? mergeTuningLayer(base[key], value) : value;
}
return merged;
}
function applyListOps(base: unknown[], ops: readonly unknown[]): unknown[] {
const result = [...base];
for (const rawOp of ops) {
if (!isPlainObject(rawOp) || typeof rawOp.op !== 'string') {
throw new Error('invalid $listOps entry: expected object with string "op"');
}
switch (rawOp.op) {
case 'append':
if (!Array.isArray(rawOp.items)) throw new Error('$listOps append requires an "items" array');
result.push(...rawOp.items);
break;
case 'prepend':
if (!Array.isArray(rawOp.items)) throw new Error('$listOps prepend requires an "items" array');
result.unshift(...rawOp.items);
break;
case 'upsertBy': {
if (typeof rawOp.key !== 'string' || !isPlainObject(rawOp.item)) {
throw new Error('$listOps upsertBy requires string "key" and object "item"');
}
const matchValue = rawOp.item[rawOp.key];
const idx = result.findIndex((entry) => isPlainObject(entry) && entry[rawOp.key as string] === matchValue);
if (idx >= 0) result[idx] = mergeTuningLayer(result[idx], rawOp.item);
else result.push(rawOp.item);
break;
}
case 'removeBy': {
if (typeof rawOp.key !== 'string') throw new Error('$listOps removeBy requires string "key"');
for (let i = result.length - 1; i >= 0; i -= 1) {
const entry = result[i];
if (isPlainObject(entry) && entry[rawOp.key] === rawOp.value) result.splice(i, 1);
}
break;
}
default:
throw new Error(`unsupported $listOps operation "${rawOp.op}"`);
}
}
return result;
}
function isListOpsEnvelope(value: unknown): value is { readonly $listOps: readonly unknown[] } {
if (!isPlainObject(value)) return false;
const keys = Object.keys(value);
return keys.length === 1 && keys[0] === '$listOps' && Array.isArray(value.$listOps);
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+154
View File
@@ -0,0 +1,154 @@
/**
* Shared types for the additive mod system.
*
* EXPERIMENTAL: Mod manifest fields, conflict structures, and runtime contracts are under active
* early development and may change without backwards compatibility.
*/
export const MOD_FORMAT_VERSION = 1;
export const MOD_API_VERSION = '0.1-experimental';
/** Supported client .vromfs.bin packs that mods may patch or add files to. */
export const MODDABLE_CLIENT_PACKS = [
'char.vromfs.bin',
'aces.vromfs.bin',
'gui.vromfs.bin',
'lang.vromfs.bin',
'mis.vromfs.bin',
'game.vromfs.bin',
'ui/atlases.vromfs.bin',
'ui/images.vromfs.bin',
] as const;
export type ModdableClientPack = (typeof MODDABLE_CLIENT_PACKS)[number];
export type LocalizedText = string | Readonly<Record<string, string>>;
export type ModRiskBadge = 'data' | 'gui' | 'script' | 'exe';
export interface ModServerConfig {
/** Relative path to the server script entry (.ts, .mjs, or .js), when present. */
readonly entry?: string;
/** Relative path to the server tuning override directory (defaults to "server/tuning"). */
readonly tuning?: string;
}
export interface ModManifest {
readonly format: 1;
readonly id: string;
readonly name: LocalizedText;
readonly version: string;
readonly author: string;
readonly description?: LocalizedText;
readonly apiVersion: string;
readonly gameVersions: readonly string[];
readonly requires: readonly string[];
readonly conflicts: readonly string[];
readonly loadAfter: readonly string[];
readonly loadBefore: readonly string[];
readonly server?: ModServerConfig;
}
export type PackFileAction = 'blk-patch' | 'csv-patch' | 'file';
export interface ModPackOperation {
readonly pack: ModdableClientPack;
/** Target path inside the pack (without .patch.jsonc / .patch.csv suffix). */
readonly targetPath: string;
readonly action: PackFileAction;
/** Path relative to the mod root folder. */
readonly sourceRelativePath: string;
}
export interface ModContentSummary {
readonly serverEntry?: string;
readonly serverTuningFiles: readonly string[];
readonly packOperations: readonly ModPackOperation[];
readonly guiPatchDirs: readonly string[];
readonly exePatchDirs: readonly string[];
readonly hasClientAddon: boolean;
/** True when client/addon includes a compiled res/grp_hdr.vromfs.bin index. */
readonly addonHasGrpHdr: boolean;
readonly addonRelativeFiles: readonly string[];
/** Relative paths under client/files (mapped into the game copy root). */
readonly clientFiles: readonly string[];
/** Optional relative path to client/config-blk.patch.jsonc. */
readonly configBlkPatch?: string;
readonly badges: readonly ModRiskBadge[];
}
export interface DiscoveredMod {
readonly folderName: string;
readonly rootDir: string;
readonly manifest: ModManifest;
readonly content: ModContentSummary;
}
export interface ModDiscoveryError {
readonly folderName: string;
readonly rootDir: string;
readonly reason: string;
}
export interface ModDiscoveryResult {
readonly mods: readonly DiscoveredMod[];
readonly errors: readonly ModDiscoveryError[];
}
export interface ModPreset {
readonly id: string;
readonly name: string;
readonly order: readonly string[];
readonly enabled: Readonly<Record<string, boolean>>;
readonly updatedAt: string;
}
export interface ClientModsConfig {
readonly format: 1;
readonly order: readonly string[];
readonly enabled: Readonly<Record<string, boolean>>;
readonly activePresetId: string | null;
readonly presets: readonly ModPreset[];
}
export type ModIssueSeverity = 'error' | 'warning' | 'info';
export type ModIssueKind =
| 'missing-dependency'
| 'dependency-disabled'
| 'dependency-order'
| 'declared-conflict'
| 'load-order-hint'
| 'game-version-mismatch'
| 'api-version-mismatch'
| 'pack-file-override'
| 'pack-blk-shared-target'
| 'client-file-conflict'
| 'tuning-file-shared';
export interface ModIssue {
readonly severity: ModIssueSeverity;
readonly kind: ModIssueKind;
readonly modId: string;
readonly otherModId?: string;
readonly detail: string;
}
export interface ResolvedModLoadOrder {
readonly enabledMods: readonly DiscoveredMod[];
readonly issues: readonly ModIssue[];
readonly hasBlockingErrors: boolean;
}
/** Pick the best localized display string for a mod field. */
export function resolveLocalizedText(value: LocalizedText, language: string): string {
if (typeof value === 'string') return value;
const exact = value[language];
if (exact) return exact;
const prefix = language.split('-')[0];
if (prefix) {
const partial = Object.entries(value).find(([key]) => key === prefix || key.startsWith(`${prefix}-`));
if (partial?.[1]) return partial[1];
}
return value.en ?? value['en-US'] ?? Object.values(value)[0] ?? '';
}
+1
View File
@@ -10,6 +10,7 @@
"@wto/blk": "*",
"@wto/exepatch": "*",
"@wto/jsonc": "*",
"@wto/mods": "*",
"@wto/vromfs": "*",
"fflate": "^0.8.2"
}
+85 -17
View File
@@ -1,21 +1,27 @@
/**
* Build the files of the game copy in memory: the three rebuilt data packs,
* the patched executable, the network hook library and its settings. Nothing is written here
* Build the files of the game copy in memory: the rebuilt data packs (with optional additive mod
* overlays), the patched executable (with protected core patches + optional declarative mod exe
* patches), the network hook library and its settings. Nothing is written here
* (write-game-copy.ts does that), so a caller can show the report first and let the player decide.
*
* Everything the build needs from outside comes in as an input: the stock files, the patch set
* (patch-set.ts), the hook library, and the multi-vehicle pack ids the local server will sell from its
* data folder.
* (patch-set.ts), the hook library, the multi-vehicle pack ids the local server will sell, and
* optionally the ordered list of enabled mods with any additional stock packs they touch.
*/
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { PeImage, type PatchFailure } from '@wto/exepatch';
import { touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods';
import { rebuildCharPack, type CharPackResult } from './char-pack.ts';
import { blockingFailures } from './essential-features.ts';
import { patchExecutable } from './executable.ts';
import { patchExecutableWithMods, type ModExePatchFailure } from './executable.ts';
import { GAME_FILES } from './game-copy.ts';
import { rebuildGuiPack } from './gui-pack.ts';
import { rebuildMainPack } from './main-pack.ts';
import { collectModAddonMounts, type ModAddonMount } from './mods/addon-register.ts';
import { CORE_BUILD_PACKS } from './mods/deploy-external.ts';
import { applyModGuiPatches } from './mods/gui-overlay.ts';
import { applyModPackOverlays, type PackOverlayReport } from './mods/pack-overlay.ts';
import type { AddressChange } from './network/address-rewrite.ts';
import { localEndpoint, type LocalEndpoint } from './network/local-endpoint.ts';
import { NETWORK_HOOK_LIBRARY, networkHookSettings } from './network/network-hook.ts';
@@ -49,6 +55,10 @@ export interface GameCopyInputs {
readonly decalIndexFiles?: readonly AddedFile[];
/** Whether wto_ws.dll writes win64/wto_ws.log; defaults to true. */
readonly hookLogging?: boolean;
/** Ordered list of enabled additive mods to overlay onto this build. */
readonly mods?: readonly DiscoveredMod[];
/** Stock bytes of optional packs (lang/mis/game/ui/*) touched by enabled mods. */
readonly extraStockPacks?: Partial<Record<ModdableClientPack, Uint8Array>>;
}
/** One file of the game copy, by its path relative to the copy folder. */
@@ -57,6 +67,20 @@ export interface GameCopyFile {
readonly content: Uint8Array;
}
export interface ModBuildReport {
readonly enabledModIds: readonly string[];
readonly packOverlays: readonly PackOverlayReport[];
readonly addonMounts: readonly ModAddonMount[];
readonly guiPatches: {
readonly applied: readonly { readonly modId: string; readonly patchId: string }[];
readonly failures: readonly (PatchFailure & { readonly modId: string })[];
};
readonly exePatches: {
readonly applied: readonly { readonly modId: string; readonly patchId: string; readonly rva: number }[];
readonly failures: readonly ModExePatchFailure[];
};
}
export interface GameCopyBuild {
/** Every file to write, with unavailable patches left out. */
readonly files: readonly GameCopyFile[];
@@ -72,6 +96,8 @@ export interface GameCopyBuild {
readonly engineAddresses: readonly AddressChange[];
/** Store bundle GUIDs registered in config/gui.blk. */
readonly bundleGuids: number;
/** Details of additive mod overlays applied during this build. */
readonly mods: ModBuildReport;
}
export function readStockGameFiles(folder: string): StockGameFiles {
@@ -86,44 +112,86 @@ export function readStockGameFiles(folder: string): StockGameFiles {
export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild {
const endpoint = localEndpoint(inputs.port);
const folders = patchSetFolders(inputs.patches);
const executable = patchExecutable(inputs.stock.executable, folders.exe);
const enabledMods = inputs.mods ?? [];
const packOverlays: PackOverlayReport[] = [];
const executable = patchExecutableWithMods(inputs.stock.executable, folders.exe, enabledMods);
const stockImage = new PeImage(inputs.stock.executable);
const native = resolveNativeModules(stockImage, loadNativeModules(folders.native));
const guiPack = rebuildGuiPack(inputs.stock.guiPack, endpoint, folders.gui);
const appliedGuiPatches = guiPack.applied.map((item) => item.patch.id);
const coreGuiPack = rebuildGuiPack(inputs.stock.guiPack, endpoint, folders.gui);
const appliedGuiPatches = coreGuiPack.applied.map((item) => item.patch.id);
const guiPackFileOverlay = applyModPackOverlays(coreGuiPack.pack, 'gui.vromfs.bin', enabledMods);
if (guiPackFileOverlay.report.operationsApplied > 0) packOverlays.push(guiPackFileOverlay.report);
const modGuiResult = applyModGuiPatches(guiPackFileOverlay.pack, endpoint, enabledMods);
const localRegistration = appliedGuiPatches.includes('registration/open-local-page') &&
appliedGuiPatches.includes('registration/keep-local-page-embedded');
const { pack: charPack, ...charReport } = rebuildCharPack(inputs.stock.charPack, endpoint, {
const { pack: coreCharPack, ...charReport } = rebuildCharPack(inputs.stock.charPack, endpoint, {
placeholderDecals: inputs.placeholderDecals,
...(inputs.decalIndexFiles ? { decalIndexFiles: inputs.decalIndexFiles } : {}),
localRegistration,
});
const bundles = offlinePackBundleGuids(inputs.stock.charPack, inputs.multiVehiclePackIds);
const mainPack = rebuildMainPack(inputs.stock.mainPack, endpoint, bundles);
const charOverlay = applyModPackOverlays(coreCharPack, 'char.vromfs.bin', enabledMods);
if (charOverlay.report.operationsApplied > 0) packOverlays.push(charOverlay.report);
// Derive store bundle GUIDs from the mod-overlaid charPack so newly added mod gift vehicles
// automatically receive deterministic offline store bundle GUIDs.
const bundles = offlinePackBundleGuids(charOverlay.pack, inputs.multiVehiclePackIds);
const addonMounts = collectModAddonMounts(enabledMods);
const coreMainPack = rebuildMainPack(
inputs.stock.mainPack,
endpoint,
bundles,
addonMounts.map((mount) => mount.mountFolder),
);
const mainOverlay = applyModPackOverlays(coreMainPack.pack, 'aces.vromfs.bin', enabledMods);
if (mainOverlay.report.operationsApplied > 0) packOverlays.push(mainOverlay.report);
const executableFolder = dirname(GAME_FILES.executable);
const hookSettings = networkHookSettings(endpoint, stockImage, native.values, {
loggingEnabled: inputs.hookLogging ?? true,
});
const files: GameCopyFile[] = [
{ path: GAME_FILES.charPack, content: charPack },
{ path: GAME_FILES.mainPack, content: mainPack.pack },
{ path: GAME_FILES.guiPack, content: guiPack.pack },
{ path: GAME_FILES.charPack, content: charOverlay.pack },
{ path: GAME_FILES.mainPack, content: mainOverlay.pack },
{ path: GAME_FILES.guiPack, content: modGuiResult.pack },
{ path: GAME_FILES.executable, content: executable.executable },
{ path: join(executableFolder, NETWORK_HOOK_LIBRARY), content: inputs.networkHookLibrary },
{ path: join(executableFolder, hookSettings.name), content: hookSettings.content },
];
const failures = [...executable.plan.failures, ...guiPack.failures, ...native.failures];
// Rebuild any optional client packs (lang, mis, game, ui/atlases, ui/images) touched by enabled mods.
for (const pack of touchedClientPacks(enabledMods)) {
if (CORE_BUILD_PACKS.has(pack)) continue;
const stockBytes = inputs.extraStockPacks?.[pack];
if (!stockBytes) {
throw new Error(`mod overlay requires stock pack "${pack}" in extraStockPacks`);
}
const overlay = applyModPackOverlays(stockBytes, pack, enabledMods);
if (overlay.report.operationsApplied > 0) {
packOverlays.push(overlay.report);
files.push({ path: join(...pack.split('/')), content: overlay.pack });
}
}
const failures = [...executable.plan.failures, ...coreGuiPack.failures, ...native.failures];
return {
files,
endpoint,
exePatches: { applied: executable.plan.writes.map((write) => ({ patchId: write.patchId, rva: write.rva })), failures: executable.plan.failures },
guiPatches: { applied: appliedGuiPatches, failures: guiPack.failures },
guiPatches: { applied: appliedGuiPatches, failures: coreGuiPack.failures },
nativeModules: { available: [...native.available.keys()], failures: native.failures },
blocking: blockingFailures(failures),
charPack: charReport,
engineAddresses: mainPack.addresses,
engineAddresses: coreMainPack.addresses,
bundleGuids: bundles.length,
mods: {
enabledModIds: enabledMods.map((mod) => mod.manifest.id),
packOverlays,
addonMounts,
guiPatches: { applied: modGuiResult.applied, failures: modGuiResult.failures },
exePatches: { applied: executable.modApplied, failures: executable.modFailures },
},
};
}
+94 -5
View File
@@ -1,10 +1,21 @@
/**
* Patch a copy of aces.exe with every definition under the exe patch folder. A patch that cannot
* be applied (site missing or ambiguous, original bytes differ, or a patch it requires failed) is
* left out and listed with the features it covers; whether a copy with
* patches missing may be installed is the caller's decision (essential-features.ts).
* Patch a copy of aces.exe with every definition under the core exe patch folder, and optionally
* apply declarative mod exe patches on top while keeping every core patch byte range locked.
*/
import { applyWrites, describePlan, loadPatches, PeImage, planPatches, type PatchPlan } from '@wto/exepatch';
import { join } from 'node:path';
import {
applyWrites,
describePlan,
loadPatches,
PeImage,
planAdditionalPatches,
planPatches,
type PatchDefinition,
type PatchFailure,
type PatchPlan,
type PlannedWrite,
} from '@wto/exepatch';
import type { DiscoveredMod } from '@wto/mods';
export interface ExecutableResult {
/** The executable with every available patch written. */
@@ -13,7 +24,85 @@ export interface ExecutableResult {
readonly description: string;
}
export interface ModExePatchFailure extends PatchFailure {
readonly modId: string;
}
export interface ModExecutableResult extends ExecutableResult {
readonly modApplied: readonly { readonly modId: string; readonly patchId: string; readonly rva: number }[];
readonly modFailures: readonly ModExePatchFailure[];
}
export function patchExecutable(stockExecutable: Uint8Array, patchesRoot: string): ExecutableResult {
const plan = planPatches(new PeImage(stockExecutable), loadPatches(patchesRoot));
return { executable: applyWrites(stockExecutable, plan.writes), plan, description: describePlan(plan) };
}
export function patchExecutableWithMods(
stockExecutable: Uint8Array,
corePatchesRoot: string,
mods: readonly DiscoveredMod[],
): ModExecutableResult {
const image = new PeImage(stockExecutable);
const corePlan = planPatches(image, loadPatches(corePatchesRoot));
const modsWithExe = mods.filter((mod) => mod.content.exePatchDirs.length > 0);
if (modsWithExe.length === 0) {
return {
executable: applyWrites(stockExecutable, corePlan.writes),
plan: corePlan,
description: describePlan(corePlan),
modApplied: [],
modFailures: [],
};
}
const allModDefs: PatchDefinition[] = [];
const ownerById = new Map<string, string>();
const loadFailures: ModExePatchFailure[] = [];
for (const mod of modsWithExe) {
const exeRoot = join(mod.rootDir, 'client', 'exe-patches');
try {
const defs = loadPatches(exeRoot);
for (const def of defs) {
const namespacedId = `${mod.manifest.id}/${def.id}`;
ownerById.set(namespacedId, mod.manifest.id);
allModDefs.push({
...def,
id: namespacedId,
requires: def.requires.map((req) => (req.includes('/') ? req : `${mod.manifest.id}/${req}`)),
});
}
} catch (error) {
loadFailures.push({
modId: mod.manifest.id,
patchId: `${mod.manifest.id}:exe-patches`,
features: [],
reason: error instanceof Error ? error.message : String(error),
});
}
}
const modPlan = planAdditionalPatches(image, allModDefs, corePlan.writes);
const combinedWrites: readonly PlannedWrite[] = [...corePlan.writes, ...modPlan.writes];
const modApplied = modPlan.writes.map((write) => ({
modId: ownerById.get(write.patchId) ?? 'unknown',
patchId: write.patchId,
rva: write.rva,
}));
const modFailures: ModExePatchFailure[] = [
...loadFailures,
...modPlan.failures.map((failure) => ({
...failure,
modId: ownerById.get(failure.patchId) ?? 'unknown',
})),
];
return {
executable: applyWrites(stockExecutable, combinedWrites),
plan: corePlan,
description: describePlan(corePlan),
modApplied,
modFailures,
};
}
+30 -1
View File
@@ -10,6 +10,7 @@ export {
type GameCopyBuild,
type GameCopyFile,
type GameCopyInputs,
type ModBuildReport,
type StockGameFiles,
} from './build-game-copy.ts';
export { NETWORK_CONFIG_PATH, rebuildCharPack, type CharPackResult } from './char-pack.ts';
@@ -21,7 +22,35 @@ export {
writeDecalCacheIndexSnapshot,
} from './decals/player-decal-cache.ts';
export { blockingFailures, ESSENTIAL_FEATURES } from './essential-features.ts';
export { patchExecutable, type ExecutableResult } from './executable.ts';
export {
patchExecutable,
patchExecutableWithMods,
type ExecutableResult,
type ModExecutableResult,
type ModExePatchFailure,
} from './executable.ts';
export {
addonMountFolderForMod,
collectModAddonMounts,
registerModAddonsInSettings,
type ModAddonMount,
} from './mods/addon-register.ts';
export {
computeModsBuildFingerprint,
CORE_BUILD_PACKS,
MODS_STATE_FILE,
prepareOptionalStockPacks,
readModsDeployState,
syncExternalModFiles,
writeModsDeployState,
type DeployedModEntry,
type DeployEntryKind,
type ModDeployWarning,
type ModExternalDeployResult,
type ModsDeployState,
} from './mods/deploy-external.ts';
export { applyModGuiPatches, type ModGuiPatchResult } from './mods/gui-overlay.ts';
export { applyModPackOverlays, type PackOverlayReport } from './mods/pack-overlay.ts';
export { assertWritableCopy, GAME_FILES, isInSteamLibrary, type WritableCopyOptions } from './game-copy.ts';
export { executableVersion } from './game-version.ts';
export {
+3
View File
@@ -13,6 +13,7 @@
* server addresses.
*/
import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
import { registerModAddonsInSettings } from './mods/addon-register.ts';
import { redirectAddresses, type AddressChange } from './network/address-rewrite.ts';
import type { LocalEndpoint } from './network/local-endpoint.ts';
import { editPackBlks } from './pack-edit.ts';
@@ -42,6 +43,7 @@ export function rebuildMainPack(
stockPack: Uint8Array,
endpoint: LocalEndpoint,
extraBundles: ReadonlyArray<readonly [string, string]> = [],
extraAddonFolders: readonly string[] = [],
): MainPackResult {
let addresses: AddressChange[] = [];
const pack = editPackBlks(stockPack, [
@@ -51,6 +53,7 @@ export function rebuildMainPack(
const network = findBlock(root, NETWORK_BLOCK);
if (!network) throw new Error(`${ENGINE_SETTINGS_PATH} has no "${NETWORK_BLOCK}" block; this game build differs from the verified ones`);
addresses = redirectAddresses(network, endpoint, [NETWORK_BLOCK]);
registerModAddonsInSettings(root, extraAddonFolders);
},
},
{
@@ -0,0 +1,57 @@
/**
* Compute engine addon mount paths for mods shipping 3D models/textures (`client/addon/`)
* and register them into `aces.vromfs.bin` `config/settings.blk`.
*
* Engine behaviour verified in 2.61.0.x aces.exe (0xc90932..0xc92754):
* - Paths containing `/pkg_user/` skip the mandatory `res/grp_hdr.vromfs.bin` check and
* directly scan `%s/res/` for all `.grp` and `.dxp.bin` archives.
* - Addons that ship a compiled `res/grp_hdr.vromfs.bin` use a dedicated `content/pkg_wto_<id>`
* folder so the native grp_hdr loader handles them.
*/
import { appendParam, ensureBlock, type BlkBlock } from '@wto/blk';
import type { DiscoveredMod } from '@wto/mods';
export interface ModAddonMount {
readonly modId: string;
/** Relative folder inside the game copy, e.g. `content/pkg_user/example_mod`. */
readonly mountFolder: string;
/** Absolute source folder `<modRoot>/client/addon`. */
readonly sourceDir: string;
}
export function addonMountFolderForMod(mod: DiscoveredMod): string {
const safeName = mod.manifest.id.replace(/[^a-z0-9_-]/g, '_');
return mod.content.addonHasGrpHdr
? `content/pkg_wto_${safeName}`
: `content/pkg_user/${safeName}`;
}
export function collectModAddonMounts(mods: readonly DiscoveredMod[]): ModAddonMount[] {
const mounts: ModAddonMount[] = [];
for (const mod of mods) {
if (!mod.content.hasClientAddon) continue;
mounts.push({
modId: mod.manifest.id,
mountFolder: addonMountFolderForMod(mod),
sourceDir: `${mod.rootDir}/client/addon`,
});
}
return mounts;
}
export function registerModAddonsInSettings(settingsRoot: BlkBlock, mountFolders: readonly string[]): void {
if (mountFolders.length === 0) return;
for (const blockName of ['addons', 'addons_no_check', 'addonsWithBasePath'] as const) {
const block = ensureBlock(settingsRoot, blockName);
const existing = new Set(
block.params
.filter((param) => param.name === 'folder' && param.value.type === 'string')
.map((param) => (param.value as { readonly type: 'string'; readonly value: string }).value.toLowerCase()),
);
for (const folder of mountFolders) {
if (existing.has(folder.toLowerCase())) continue;
appendParam(block, 'folder', { type: 'string', value: folder });
existing.add(folder.toLowerCase());
}
}
}
@@ -0,0 +1,541 @@
/**
* Deploy and cleanly roll back external mod assets (3D model addons, optional companion files,
* on-demand stock pack backups, and `config.blk` patches) in the game copy.
*
* Cross-drive zero-copy strategy (Option A):
* 1. Dedicated folders (`content/pkg_user/<modId>` and exclusive subdirectories under `client/files`,
* such as `UserSkins/<skin>`) use NTFS Directory Junctions — works across drives, needs no admin
* privileges, uses 0 extra bytes, and mounts/unmounts in ~1 ms.
* 2. Shared flat files (such as `sound/mod/*.bank`) try file symlink (works across drives when
* Windows Developer Mode is on) -> NTFS hardlink (same drive) -> size/mtime cached copy.
* 3. Player-owned native files (e.g. manually installed UserSkins/UserSights) are never overwritten;
* conflicts are reported and skipped.
* 4. Hard-linked stock files are unlinked before replacing so online client files are never mutated.
*/
import { createHash } from 'node:crypto';
import {
copyFileSync,
existsSync,
linkSync,
lstatSync,
mkdirSync,
readdirSync,
readFileSync,
rmdirSync,
rmSync,
statSync,
symlinkSync,
unlinkSync,
writeFileSync,
} from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { formatBlkText, parseBlkText } from '@wto/blk';
import {
applyBlkPatch,
parseBlkPatchDocument,
type DiscoveredMod,
type ModdableClientPack,
} from '@wto/mods';
import { addonMountFolderForMod } from './addon-register.ts';
export const MODS_STATE_FILE = join('wtoffline', 'mods-state.json');
export const CORE_BUILD_PACKS: ReadonlySet<ModdableClientPack> = new Set([
'char.vromfs.bin',
'aces.vromfs.bin',
'gui.vromfs.bin',
]);
export type DeployEntryKind = 'junction' | 'symlink' | 'hardlink' | 'copy';
export interface DeployedModEntry {
readonly modId: string;
/** Copy-relative path with forward slashes. */
readonly targetRelPath: string;
readonly sourcePath: string;
readonly kind: DeployEntryKind;
readonly size?: number;
readonly mtimeMs?: number;
}
export interface ModsDeployState {
readonly format: 1;
readonly entries: readonly DeployedModEntry[];
/** Optional stock packs backed up on demand under `wtoffline/stock/`. */
readonly optionalPacksModified: readonly ModdableClientPack[];
readonly configBlkModified: boolean;
readonly fingerprint?: string;
}
export interface ModDeployWarning {
readonly modId: string;
readonly targetRelPath: string;
readonly reason: string;
}
export interface ModExternalDeployResult {
readonly deployed: readonly DeployedModEntry[];
readonly warnings: readonly ModDeployWarning[];
readonly restoredOptionalPacks: readonly ModdableClientPack[];
readonly configBlkPatched: boolean;
}
export function readModsDeployState(copyFolder: string): ModsDeployState {
const path = join(copyFolder, MODS_STATE_FILE);
if (!existsSync(path)) {
return { format: 1, entries: [], optionalPacksModified: [], configBlkModified: false };
}
try {
const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<ModsDeployState>;
return {
format: 1,
entries: Array.isArray(parsed.entries) ? parsed.entries : [],
optionalPacksModified: Array.isArray(parsed.optionalPacksModified) ? parsed.optionalPacksModified : [],
configBlkModified: parsed.configBlkModified === true,
...(typeof parsed.fingerprint === 'string' ? { fingerprint: parsed.fingerprint } : {}),
};
} catch {
return { format: 1, entries: [], optionalPacksModified: [], configBlkModified: false };
}
}
export function writeModsDeployState(copyFolder: string, state: ModsDeployState): void {
const path = join(copyFolder, MODS_STATE_FILE);
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(state, null, 2), 'utf8');
}
/**
* Ensure stock copies exist under `<stockBackupFolder>` for any optional .vromfs.bin pack
* touched by enabled mods, then read and return their stock bytes for overlay building.
*/
export function prepareOptionalStockPacks(
copyFolder: string,
stockBackupFolder: string,
touchedPacks: readonly ModdableClientPack[],
): Partial<Record<ModdableClientPack, Uint8Array>> {
const result: Partial<Record<ModdableClientPack, Uint8Array>> = {};
for (const pack of touchedPacks) {
if (CORE_BUILD_PACKS.has(pack)) continue;
const backupPath = join(stockBackupFolder, ...pack.split('/'));
if (!existsSync(backupPath)) {
const livePath = join(copyFolder, ...pack.split('/'));
if (!existsSync(livePath)) {
throw new Error(`optional game pack "${pack}" does not exist in copy folder ${copyFolder}`);
}
mkdirSync(dirname(backupPath), { recursive: true });
copyFileSync(livePath, backupPath);
}
result[pack] = readFileSync(backupPath);
}
return result;
}
/**
* Synchronize external mod mounts (`client/addon/`, `client/files/`, `config.blk` patches)
* and restore any previously modified optional packs that are no longer touched.
*/
export function syncExternalModFiles(
copyFolder: string,
stockBackupFolder: string,
mods: readonly DiscoveredMod[],
optionalPacksInBuild: readonly ModdableClientPack[],
fingerprint?: string,
): ModExternalDeployResult {
const previous = readModsDeployState(copyFolder);
const warnings: ModDeployWarning[] = [];
// Plan desired external mounts for this launch.
const desired = planExternalEntries(mods);
const desiredByTarget = new Map(desired.map((item) => [item.targetRelPath.toLowerCase(), item]));
const previousByTarget = new Map(previous.entries.map((item) => [item.targetRelPath.toLowerCase(), item]));
// 1. Remove previous entries that are no longer wanted or changed source/mode.
for (const oldEntry of previous.entries) {
const key = oldEntry.targetRelPath.toLowerCase();
const next = desiredByTarget.get(key);
const keepUnchanged = next !== undefined
&& next.sourcePath === oldEntry.sourcePath
&& isEntryStillValid(copyFolder, oldEntry);
if (!keepUnchanged) {
removeDeployedEntry(copyFolder, oldEntry);
}
}
// 2. Restore optional packs that were modified previously but are no longer touched.
const activeOptionalSet = new Set(optionalPacksInBuild.filter((pack) => !CORE_BUILD_PACKS.has(pack)));
const restoredOptionalPacks: ModdableClientPack[] = [];
for (const oldPack of previous.optionalPacksModified) {
if (activeOptionalSet.has(oldPack)) continue;
const backupPath = join(stockBackupFolder, ...oldPack.split('/'));
const livePath = join(copyFolder, ...oldPack.split('/'));
if (existsSync(backupPath)) {
unlinkIfExists(livePath);
mkdirSync(dirname(livePath), { recursive: true });
copyFileSync(backupPath, livePath);
restoredOptionalPacks.push(oldPack);
}
}
// 3. Deploy desired mounts (skipping already-valid unchanged mounts and protecting native player files).
const deployed: DeployedModEntry[] = [];
for (const plan of desired) {
const key = plan.targetRelPath.toLowerCase();
const prev = previousByTarget.get(key);
if (prev && prev.sourcePath === plan.sourcePath && isEntryStillValid(copyFolder, prev)) {
deployed.push(prev);
continue;
}
const targetAbs = join(copyFolder, ...plan.targetRelPath.split('/'));
// Protect player-managed native files (e.g. manually installed UserSkins/UserSights).
if (existsSyncSafe(targetAbs) && !previousByTarget.has(key)) {
warnings.push({
modId: plan.modId,
targetRelPath: plan.targetRelPath,
reason: 'target already exists as a native/player file; skipped to avoid overwriting player content',
});
continue;
}
const mounted = mountPlannedEntry(copyFolder, plan);
deployed.push(mounted);
}
// 4. Apply or restore config.blk patches.
const configBlkPatched = syncConfigBlkPatches(copyFolder, stockBackupFolder, mods, previous.configBlkModified);
writeModsDeployState(copyFolder, {
format: 1,
entries: deployed,
optionalPacksModified: [...activeOptionalSet],
configBlkModified: configBlkPatched,
...(fingerprint !== undefined ? { fingerprint } : {}),
});
return { deployed, warnings, restoredOptionalPacks, configBlkPatched };
}
/** Compute a deterministic fingerprint of enabled mods and their source file stamps. */
export function computeModsBuildFingerprint(
mods: readonly DiscoveredMod[],
port: number,
extraSalt = '',
): string {
const hash = createHash('sha256');
hash.update(`port=${port};salt=${extraSalt}\n`);
for (const mod of mods) {
hash.update(`mod=${mod.manifest.id}@${mod.manifest.version}\n`);
const filesToStamp = [
...mod.content.packOperations.map((op) => op.sourceRelativePath),
...mod.content.guiPatchDirs,
...mod.content.exePatchDirs,
...(mod.content.configBlkPatch ? [mod.content.configBlkPatch] : []),
];
for (const rel of filesToStamp) {
const abs = join(mod.rootDir, ...rel.split('/'));
try {
const st = statSync(abs);
hash.update(`${rel}:${st.size}:${Math.trunc(st.mtimeMs)}\n`);
} catch {
hash.update(`${rel}:missing\n`);
}
}
}
return hash.digest('hex');
}
interface PlannedMount {
readonly modId: string;
readonly targetRelPath: string;
readonly sourcePath: string;
readonly isDirectory: boolean;
}
function planExternalEntries(mods: readonly DiscoveredMod[]): PlannedMount[] {
const plans: PlannedMount[] = [];
const seenTargets = new Map<string, number>();
const register = (plan: PlannedMount) => {
const key = plan.targetRelPath.toLowerCase();
const existingIdx = seenTargets.get(key);
if (existingIdx !== undefined) {
plans[existingIdx] = plan;
} else {
seenTargets.set(key, plans.length);
plans.push(plan);
}
};
// Addons are always mod-exclusive directories -> ideal for cross-drive Junctions.
for (const mod of mods) {
if (!mod.content.hasClientAddon) continue;
register({
modId: mod.manifest.id,
targetRelPath: addonMountFolderForMod(mod),
sourcePath: join(mod.rootDir, 'client', 'addon'),
isDirectory: true,
});
}
// Companion files under `client/files`: group exclusive leaf directories (e.g. `UserSkins/my_skin`)
// as cross-drive Junctions whenever only one mod touches that subdirectory.
const folderOwners = new Map<string, Set<string>>();
for (const mod of mods) {
for (const rel of mod.content.clientFiles) {
const topSub = exclusiveSubdirCandidate(rel);
if (!topSub) continue;
const key = topSub.toLowerCase();
let set = folderOwners.get(key);
if (!set) {
set = new Set();
folderOwners.set(key, set);
}
set.add(mod.manifest.id);
}
}
for (const mod of mods) {
const claimedDirs = new Set<string>();
for (const rel of mod.content.clientFiles) {
const topSub = exclusiveSubdirCandidate(rel);
if (topSub && folderOwners.get(topSub.toLowerCase())?.size === 1) {
const key = topSub.toLowerCase();
if (!claimedDirs.has(key)) {
claimedDirs.add(key);
register({
modId: mod.manifest.id,
targetRelPath: topSub,
sourcePath: join(mod.rootDir, 'client', 'files', ...topSub.split('/')),
isDirectory: true,
});
}
continue;
}
register({
modId: mod.manifest.id,
targetRelPath: rel,
sourcePath: join(mod.rootDir, 'client', 'files', ...rel.split('/')),
isDirectory: false,
});
}
}
return plans;
}
/**
* Return a safe exclusive subdirectory candidate (e.g. `UserSkins/foo`, `UserSights/bar`,
* `UserMissions/baz`) that can be mounted as one cross-drive Junction instead of linking
* every file inside it. Flat shared folders like `sound/mod/*.bank` return undefined.
*/
function exclusiveSubdirCandidate(relPath: string): string | undefined {
const parts = relPath.split('/');
if (parts.length < 3) return undefined;
const root = parts[0]!.toLowerCase();
if (root === 'userskins' || root === 'usersights' || root === 'usermissions') {
return `${parts[0]!}/${parts[1]!}`;
}
return undefined;
}
function mountPlannedEntry(copyFolder: string, plan: PlannedMount): DeployedModEntry {
const targetAbs = join(copyFolder, ...plan.targetRelPath.split('/'));
mkdirSync(dirname(targetAbs), { recursive: true });
if (plan.isDirectory) {
try {
symlinkSync(plan.sourcePath, targetAbs, 'junction');
return {
modId: plan.modId,
targetRelPath: plan.targetRelPath,
sourcePath: plan.sourcePath,
kind: 'junction',
};
} catch {
// Fallback for non-NTFS volumes (e.g. exFAT): incremental directory copy.
copyDirectoryIncremental(plan.sourcePath, targetAbs);
return {
modId: plan.modId,
targetRelPath: plan.targetRelPath,
sourcePath: plan.sourcePath,
kind: 'copy',
};
}
}
// Flat single file: try file symlink (cross-drive when Developer Mode is enabled),
// then same-drive NTFS hardlink, then cached copy.
unlinkIfExists(targetAbs);
try {
symlinkSync(plan.sourcePath, targetAbs, 'file');
return {
modId: plan.modId,
targetRelPath: plan.targetRelPath,
sourcePath: plan.sourcePath,
kind: 'symlink',
};
} catch { /* fall through */ }
try {
linkSync(plan.sourcePath, targetAbs);
return {
modId: plan.modId,
targetRelPath: plan.targetRelPath,
sourcePath: plan.sourcePath,
kind: 'hardlink',
};
} catch { /* fall through */ }
const st = statSync(plan.sourcePath);
copyFileSync(plan.sourcePath, targetAbs);
return {
modId: plan.modId,
targetRelPath: plan.targetRelPath,
sourcePath: plan.sourcePath,
kind: 'copy',
size: st.size,
mtimeMs: st.mtimeMs,
};
}
function isEntryStillValid(copyFolder: string, entry: DeployedModEntry): boolean {
const targetAbs = join(copyFolder, ...entry.targetRelPath.split('/'));
if (!existsSyncSafe(targetAbs)) return false;
if (entry.kind === 'junction' || entry.kind === 'symlink') {
try {
return lstatSync(targetAbs).isSymbolicLink() && existsSync(entry.sourcePath);
} catch {
return false;
}
}
if (entry.kind === 'hardlink') {
try {
const a = statSync(targetAbs);
const b = statSync(entry.sourcePath);
return a.ino !== 0 && a.ino === b.ino && a.dev === b.dev;
} catch {
return false;
}
}
// Cached copy check.
if (entry.size !== undefined && entry.mtimeMs !== undefined) {
try {
const src = statSync(entry.sourcePath);
const dst = statSync(targetAbs);
return src.size === entry.size && Math.abs(src.mtimeMs - entry.mtimeMs) < 2 && dst.size === src.size;
} catch {
return false;
}
}
return false;
}
function removeDeployedEntry(copyFolder: string, entry: DeployedModEntry): void {
const targetAbs = join(copyFolder, ...entry.targetRelPath.split('/'));
if (!existsSyncSafe(targetAbs)) return;
try {
const stat = lstatSync(targetAbs);
if (entry.kind === 'junction' || stat.isSymbolicLink()) {
// Remove only the reparse point / symlink, never descending into the source mod folder.
try {
unlinkSync(targetAbs);
} catch {
rmdirSync(targetAbs);
}
} else if (stat.isDirectory()) {
rmSync(targetAbs, { recursive: true, force: true });
} else {
unlinkSync(targetAbs);
}
} catch { /* ignore */ }
pruneEmptyParents(dirname(targetAbs), copyFolder);
}
function copyDirectoryIncremental(srcDir: string, dstDir: string): void {
mkdirSync(dstDir, { recursive: true });
for (const entry of readdirSync(srcDir, { withFileTypes: true })) {
const src = join(srcDir, entry.name);
const dst = join(dstDir, entry.name);
if (entry.isDirectory()) {
copyDirectoryIncremental(src, dst);
} else if (entry.isFile()) {
const st = statSync(src);
let same = false;
try {
const dstStat = statSync(dst);
same = dstStat.size === st.size && Math.abs(dstStat.mtimeMs - st.mtimeMs) < 2;
} catch { /* missing */ }
if (!same) {
unlinkIfExists(dst);
copyFileSync(src, dst);
}
}
}
}
function syncConfigBlkPatches(
copyFolder: string,
stockBackupFolder: string,
mods: readonly DiscoveredMod[],
previouslyModified: boolean,
): boolean {
const patchingMods = mods.filter((mod) => mod.content.configBlkPatch !== undefined);
const liveConfig = join(copyFolder, 'config.blk');
const backupConfig = join(stockBackupFolder, 'config.blk');
if (patchingMods.length === 0) {
if (previouslyModified && existsSync(backupConfig)) {
unlinkIfExists(liveConfig);
copyFileSync(backupConfig, liveConfig);
}
return false;
}
if (!existsSync(backupConfig) && existsSync(liveConfig)) {
mkdirSync(dirname(backupConfig), { recursive: true });
copyFileSync(liveConfig, backupConfig);
}
const sourceText = existsSync(backupConfig)
? readFileSync(backupConfig, 'utf8')
: existsSync(liveConfig) ? readFileSync(liveConfig, 'utf8') : '';
const root = parseBlkText(sourceText);
for (const mod of patchingMods) {
const patchPath = join(mod.rootDir, ...mod.content.configBlkPatch!.split('/'));
const patch = parseBlkPatchDocument(readFileSync(patchPath, 'utf8'), `mod "${mod.manifest.id}" config.blk patch`);
applyBlkPatch(root, patch, `mod "${mod.manifest.id}" config.blk patch`);
}
unlinkIfExists(liveConfig);
writeFileSync(liveConfig, formatBlkText(root), 'utf8');
return true;
}
function pruneEmptyParents(dir: string, stopAt: string): void {
let current = dir;
while (relative(stopAt, current) !== '' && !relative(stopAt, current).startsWith('..')) {
try {
if (readdirSync(current).length > 0) return;
rmdirSync(current);
current = dirname(current);
} catch {
return;
}
}
}
function existsSyncSafe(path: string): boolean {
try {
lstatSync(path);
return true;
} catch {
return false;
}
}
function unlinkIfExists(path: string): void {
if (!existsSyncSafe(path)) return;
try {
unlinkSync(path);
} catch { /* ignore */ }
}
+112
View File
@@ -0,0 +1,112 @@
/**
* Apply mod GUI script patches (`client/gui-patches/<name>/patch.jsonc`) on top of an already
* core-patched gui.vromfs.bin archive. Failures are collected per mod rather than breaking core
* offline GUI patches.
*/
import { join } from 'node:path';
import { chooseVariant, PatchError, type PatchFailure } from '@wto/exepatch';
import type { DiscoveredMod } from '@wto/mods';
import { getFile, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs';
import { loadGuiPatches, type GuiScriptVariant } from '../gui-patch-definition.ts';
import type { LocalEndpoint } from '../network/local-endpoint.ts';
const ENDPOINT_PLACEHOLDER = '{{LOCAL_ENDPOINT}}';
export interface ModGuiPatchResult {
readonly pack: Uint8Array;
readonly applied: readonly { readonly modId: string; readonly patchId: string }[];
readonly failures: readonly (PatchFailure & { readonly modId: string })[];
}
class ModGuiPatchMismatch extends PatchError {
override name = 'ModGuiPatchMismatch';
}
export function applyModGuiPatches(
baseGuiPack: Uint8Array,
endpoint: LocalEndpoint,
mods: readonly DiscoveredMod[],
): ModGuiPatchResult {
const modsWithGui = mods.filter((mod) => mod.content.guiPatchDirs.length > 0);
if (modsWithGui.length === 0) {
return { pack: baseGuiPack, applied: [], failures: [] };
}
const archive = readArchive(baseGuiPack);
const hostPortText = `${endpoint.host}:${endpoint.port}`;
const applied: { readonly modId: string; readonly patchId: string }[] = [];
const failures: (PatchFailure & { readonly modId: string })[] = [];
for (const mod of modsWithGui) {
const patchesRoot = join(mod.rootDir, 'client', 'gui-patches');
let patches;
try {
patches = loadGuiPatches(patchesRoot);
} catch (error) {
failures.push({
modId: mod.manifest.id,
patchId: `${mod.manifest.id}:gui-patches`,
features: [],
reason: error instanceof Error ? error.message : String(error),
});
continue;
}
for (const patch of patches) {
try {
const chosen = chooseVariant(patch.variants, (variant) => patchedScript(archive, variant, hostPortText));
putFile(archive, chosen.variant.file, Buffer.from(chosen.value, 'utf8'));
applied.push({ modId: mod.manifest.id, patchId: patch.id });
} catch (error) {
if (!(error instanceof PatchError)) throw error;
failures.push({
modId: mod.manifest.id,
patchId: patch.id,
features: patch.features,
reason: error.message,
});
}
}
}
return { pack: writeArchive(archive), applied, failures };
}
function patchedScript(archive: Archive, variant: GuiScriptVariant, hostPortText: string): string {
if (!archive.files.has(variant.file)) throw new ModGuiPatchMismatch(`the data pack has no script ${variant.file}`);
let current = Buffer.from(getFile(archive, variant.file)).toString('utf8');
const newline = current.includes('\r\n') ? '\r\n' : '\n';
for (const [index, edit] of variant.edits.entries()) {
const replace = edit.replace.replaceAll('\n', newline).replaceAll(ENDPOINT_PLACEHOLDER, hostPortText);
current = replaceUnique(current, edit.find, replace, `edit ${index + 1} in ${variant.file}`);
}
return current;
}
function replaceUnique(text: string, find: string, replace: string, label: string): string {
const { normalized, original } = withoutCarriageReturns(text);
const first = normalized.indexOf(find);
if (first === -1) throw new ModGuiPatchMismatch(`${label}: target text not found`);
if (normalized.indexOf(find, first + find.length) !== -1) {
throw new ModGuiPatchMismatch(`${label}: target text appears more than once`);
}
return text.slice(0, original[first]!) + replace + text.slice(original[first + find.length]!);
}
function withoutCarriageReturns(text: string): { readonly normalized: string; readonly original: readonly number[] } {
const kept: string[] = [];
const original: number[] = [];
let index = 0;
while (index < text.length) {
original.push(index);
if (text[index] === '\r' && text[index + 1] === '\n') {
kept.push('\n');
index += 2;
} else {
kept.push(text[index]!);
index += 1;
}
}
original.push(text.length);
return { normalized: kept.join(''), original };
}
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more