From aa7a6e7d02a684b88658841673a3b8c70897e8c6 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:00:36 +0800 Subject: [PATCH] feat(server): add experimental JS/TS mod runtime, hooks, tuning list ops, and isolated mod storage --- apps/server/package.json | 1 + .../server/src/char/actions/battle-actions.ts | 7 + apps/server/src/char/char-service.ts | 55 ++- .../src/matching/battle-live-requests.ts | 7 + .../src/matching/battle-queue-requests.ts | 7 + apps/server/src/mods/mod-http-service.ts | 82 +++++ apps/server/src/mods/mod-storage.ts | 55 +++ apps/server/src/mods/server-mod-runtime.ts | 334 ++++++++++++++++++ apps/server/src/profiles-setup.ts | 3 + apps/server/src/server.ts | 183 ++++++++-- apps/server/src/store/store-pack-ids.ts | 9 +- apps/server/src/tuning/tuning-loader.ts | 50 +-- apps/server/src/tuning/tuning.ts | 9 +- packages/mods/src/server-api.ts | 2 +- 14 files changed, 743 insertions(+), 61 deletions(-) create mode 100644 apps/server/src/mods/mod-http-service.ts create mode 100644 apps/server/src/mods/mod-storage.ts create mode 100644 apps/server/src/mods/server-mod-runtime.ts diff --git a/apps/server/package.json b/apps/server/package.json index 762e9d8..3d67703 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -9,6 +9,7 @@ "dependencies": { "@wto/blk": "*", "@wto/jsonc": "*", + "@wto/mods": "*", "@wto/vromfs": "*" } } \ No newline at end of file diff --git a/apps/server/src/char/actions/battle-actions.ts b/apps/server/src/char/actions/battle-actions.ts index 228a960..47f8499 100644 --- a/apps/server/src/char/actions/battle-actions.ts +++ b/apps/server/src/char/actions/battle-actions.ts @@ -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; + 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) }; diff --git a/apps/server/src/char/char-service.ts b/apps/server/src/char/char-service.ts index f5bc19a..53c65ae 100644 --- a/apps/server/src/char/char-service.ts +++ b/apps/server/src/char/char-service.ts @@ -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; + readonly #modRuntime: ServerModRuntime | undefined; - constructor(actions: ReadonlyMap) { + constructor(actions: ReadonlyMap, 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 { 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 { + const headers: Record = {}; + for (const [key, value] of Object.entries(request.headers)) { + headers[key] = Array.isArray(value) ? value[0] : value; + } + const query: Record = {}; + 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 => { + 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 = { ...(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 { diff --git a/apps/server/src/matching/battle-live-requests.ts b/apps/server/src/matching/battle-live-requests.ts index 0d0607c..66ad586 100644 --- a/apps/server/src/matching/battle-live-requests.ts +++ b/apps/server/src/matching/battle-live-requests.ts @@ -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; + 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, + }); const awarded = deps.streaks.evaluate({ ...withoutSupportPlanes({ events: log.events, lives: log.lives }, deps.supportPlanes), feed: log.feed, diff --git a/apps/server/src/matching/battle-queue-requests.ts b/apps/server/src/matching/battle-queue-requests.ts index efa424d..5ff92d2 100644 --- a/apps/server/src/matching/battle-queue-requests.ts +++ b/apps/server/src/matching/battle-queue-requests.ts @@ -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, + }); const outcome = deps.matchmaker.enqueue({ userId, mode: modes[0]!, diff --git a/apps/server/src/mods/mod-http-service.ts b/apps/server/src/mods/mod-http-service.ts new file mode 100644 index 0000000..696dbe2 --- /dev/null +++ b/apps/server/src/mods/mod-http-service.ts @@ -0,0 +1,82 @@ +/** + * HTTP router service that exposes mod-registered routes under `/mods//...` + * 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//...`. */ + 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 { + const matched = this.#match(request.path); + if (!matched) { + return { status: 404, body: 'mod route not found' }; + } + const headers: Record = {}; + for (const [key, value] of Object.entries(request.headers)) { + headers[key] = Array.isArray(value) ? value[0] : value; + } + const query: Record = {}; + 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 = { ...(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 }; +} diff --git a/apps/server/src/mods/mod-storage.ts b/apps/server/src/mods/mod-storage.ts new file mode 100644 index 0000000..838c418 --- /dev/null +++ b/apps/server/src/mods/mod-storage.ts @@ -0,0 +1,55 @@ +/** + * Isolated JSON storage for server mods: + * - per-player files under `/saves//mods/.json` + * - shared mod state under `/mods-data/.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 | 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; +} diff --git a/apps/server/src/mods/server-mod-runtime.ts b/apps/server/src/mods/server-mod-runtime.ts new file mode 100644 index 0000000..64c3ca5 --- /dev/null +++ b/apps/server/src/mods/server-mod-runtime.ts @@ -0,0 +1,334 @@ +/** + * 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//*` + * HTTP routes. + */ +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import type { BlkBlock } from '@wto/blk'; +import { + MOD_API_VERSION, + type BattleLiveFactContext, + type BattleMatchmakeContext, + 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 { + readonly modId: string; + readonly fn: T; +} + +export class ServerModRuntime { + readonly #report: (line: string) => void; + readonly #loadedModIds: string[] = []; + readonly #onDatasetsLoaded: ScopedHandler<(datasets: ServerModDatasetsView) => void | Promise>[] = []; + readonly #onCataloguesReady: ScopedHandler<(catalogues: ServerModCataloguesView) => void | Promise>[] = []; + readonly #onServerListening: ScopedHandler<(info: { readonly port: number }) => void | Promise>[] = []; + readonly #onServerClosing: ScopedHandler<() => void | Promise>[] = []; + readonly #onProfileRefresh: ScopedHandler<(profile: BlkBlock, userId: string) => void>[] = []; + readonly #onBeforeMatchmake: ScopedHandler<(ctx: BattleMatchmakeContext) => void>[] = []; + readonly #onLiveFact: ScopedHandler<(ctx: BattleLiveFactContext) => void>[] = []; + readonly #onAfterSettle: ScopedHandler<(ctx: BattleSettlementContext) => void>[] = []; + readonly #charHandlers = new Map>(); + readonly #charWrappers = new Map[]>(); + readonly #matchingHandlers = new Map>(); + readonly #matchingWrappers = new Map[]>(); + readonly #httpRoutes: RegisteredModHttpRoute[] = []; + + private constructor(report: (line: string) => void) { + this.#report = report; + } + + static async load(options: RuntimeInitOptions): Promise { + 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; + try { + loadedModule = (await import(url)) as Record; + } 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 { + 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 { + 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 { + for (const { modId, fn } of this.#onServerListening) { + try { + await fn({ port }); + } catch (error) { + this.#report(`[mod:${modId}] onServerListening error: ${formatError(error)}`); + } + } + } + + async runServerClosing(): Promise { + 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)}`); + } + } + } + + 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, + ): Promise { + const custom = this.#charHandlers.get(action); + const terminal: (req: ModCharRequest) => Promise = 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(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 => ( + 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 }); }, + 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): WtoServerMod | undefined { + const def = mod.default; + if (def && typeof def === 'object' && typeof (def as Record).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); +} diff --git a/apps/server/src/profiles-setup.ts b/apps/server/src/profiles-setup.ts index 594c133..afccb06 100644 --- a/apps/server/src/profiles-setup.ts +++ b/apps/server/src/profiles-setup.ts @@ -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 }; } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index ae8c1f6..9a2192c 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -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 `/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; } export async function startServer(options: ServerOptions): Promise { 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(); + 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, + battleSpawnRules: spawnRulesObj, + multiplayerMissions: missionsObj as unknown as Record, + uiLabels: labelsObj as unknown as Record, + unitNames: localizedUnitNamesObj as unknown as Record, + get: (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,6 +175,9 @@ export async function startServer(options: ServerOptions): Promise matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' }); + const notifyUser = (userId: string, eventName: string, payload: Record) => { + matching?.notifyUser(userId, eventName, payload); + }; const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept); const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules, botAircraftLoadouts); const economy = new BattleEconomy( @@ -124,7 +190,31 @@ export async function startServer(options: ServerOptions): Promise>, + 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 +230,69 @@ export async function startServer(options: ServerOptions): Promise 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((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)), diff --git a/apps/server/src/store/store-pack-ids.ts b/apps/server/src/store/store-pack-ids.ts index c8b17c7..df62f77 100644 --- a/apps/server/src/store/store-pack-ids.ts +++ b/apps/server/src/store/store-pack-ids.ts @@ -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); } diff --git a/apps/server/src/tuning/tuning-loader.ts b/apps/server/src/tuning/tuning-loader.ts index ed2d795..7218328 100644 --- a/apps/server/src/tuning/tuning-loader.ts +++ b/apps/server/src/tuning/tuning-loader.ts @@ -1,16 +1,21 @@ /** - * Load one tuning file: the defaults shipped in - * apps/server/tuning/.jsonc, with /tuning/.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/.jsonc`) + * -> each enabled mod's `/.jsonc` in load order + * -> player overrides (`/tuning/.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 .jsonc, ready for typed reads. */ @@ -21,19 +26,35 @@ export function tuningFiles( dataFolder: string | null, report: (line: string) => void, proposed?: ReadonlyMap>, + 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 = { ...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 { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} diff --git a/apps/server/src/tuning/tuning.ts b/apps/server/src/tuning/tuning.ts index e7e7ae8..047859c 100644 --- a/apps/server/src/tuning/tuning.ts +++ b/apps/server/src/tuning/tuning.ts @@ -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')), diff --git a/packages/mods/src/server-api.ts b/packages/mods/src/server-api.ts index 1ac4dca..91d1d99 100644 --- a/packages/mods/src/server-api.ts +++ b/packages/mods/src/server-api.ts @@ -34,7 +34,7 @@ export interface ServerModDatasetsView { readonly vehicles: unknown[]; readonly battleEconomy: Record; readonly battleSpawnRules: unknown; - readonly multiplayerMissions: unknown[]; + readonly multiplayerMissions: Record; readonly uiLabels: Record; readonly unitNames: Record; /** Escape hatch: read or replace any dataset object by its dataset id. */