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

+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')),