/** * 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'; import { BattleMatchmaker } from './battle/battle-matchmaker.ts'; import { BattleSessionStore } from './battle/battle-session-store.ts'; import { selectBotAircraftLoadouts } from './battle/bot-aircraft-loadouts.ts'; import { selectBotTankLoadouts } from './battle/bot-tank-loadouts.ts'; import { actionTable } from './char/actions/action-table.ts'; import { CharService } from './char/char-service.ts'; import { ClanStore } from './clans/clan-store.ts'; 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, 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'; import { battleStreaks } from './game-data/datasets/battle-streaks.ts'; import { BattleStreaks } from './battle/battle-streaks.ts'; import { BattleLiveLogs } from './battle/battle-live-log.ts'; import { supportPlaneUnits } from './battle/battle-support-planes.ts'; import { clanEconomy } from './game-data/datasets/clan-economy.ts'; import { crewSkillData } from './game-data/datasets/crew-skills.ts'; import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; 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 { tankBotAmmo } from './game-data/datasets/tank-bot-ammo.ts'; import { itemCatalogue } from './game-data/datasets/item-catalogue.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 { trainingMissions } from './game-data/datasets/training-missions.ts'; import { uiLabels, type UiLabels } from './game-data/datasets/ui-labels.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'; import { GameFiles } from './game-data/game-files.ts'; import { GameModes } from './game-modes/game-modes.ts'; import { InventoryService } from './inventory/inventory-service.ts'; import { InventoryCatalogue } from './inventory/itemdef-catalogue.ts'; import { MarketplaceService } from './inventory/marketplace-service.ts'; import { TrophyCatalogue } from './inventory/trophy-catalogue.ts'; 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'; import { loadOrCreateCredentials } from './transport/tls/tls-certificate.ts'; import { StoreCatalogue } from './store/store-catalogue.ts'; import { StoreService } from './store/store-service.ts'; import { TrainingCatalogue } from './training/training-completion.ts'; import { TrafficLog } from './traffic-log/traffic-log.ts'; import { loadTuning, type Tuning } from './tuning/tuning.ts'; import { UnlockShop } from './unlocks/unlock-purchase.ts'; import { GameArtwork } from './web-ui/game-artwork.ts'; import { WebUiService } from './web-ui/web-ui-service.ts'; export interface ServerOptions { /** The player's game folder; its data packs are read, never written. */ readonly gameFolder: string; /** Accounts, saves and logs. */ readonly dataFolder: string; readonly port: number; /** 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, 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( 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 efficiencyData = datasets.load(researchEfficiency); const streakDefinitions = datasets.load(battleStreaks); 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) ?? []), groups: storeProducts.flatMap((product) => product.artworkGroup ? [product.artworkGroup] : []), listings: catalogues.inventory.marketplaceListings(), }, report); const webUi = new WebUiService(datasets.load(webIcons), labels, options.dataFolder, artwork); const botAircraftLoadouts = selectBotAircraftLoadouts(vehicles, datasets.load(flightModelPresets), equipment); const botTankLoadouts = tuning.groundAi.mode === 'stock' ? undefined : selectBotTankLoadouts(vehicles, datasets.load(tankBotAmmo), tuning.groundAi.loadout); gameFiles.releasePacks(); let matching: MatchingService | undefined; const notifyInventoryChanged = () => 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, tuning.groundAi.mode === 'stock' ? undefined : tuning.groundAi.lineupWeights, botTankLoadouts, (ctx) => modRuntime.runBattleFilterMissions(ctx), ); const economy = new BattleEconomy( economyData, tuning.battleEconomy, { silverLions: tuning.battle.rewardMultiplierSilverLions, researchPoints: tuning.battle.rewardMultiplierResearchPoints }, new Set(vehicles.filter((vehicle) => vehicle.goldenEagles > 0 || vehicle.premiumPack).map((vehicle) => vehicle.name)), ); const streaks = new BattleStreaks(streakDefinitions, vehicles, economy); const supportPlanes = supportPlaneUnits(spawnRules); await modRuntime.runCataloguesReady({ tuning: tuning as unknown as Readonly>, 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), new MarketplaceService(accounts, profiles, catalogues.inventory, notifyInventoryChanged, tuning.marketplace), new InventoryService(accounts, profiles, catalogues.inventory), new LoginService(accounts), new CharService(actionTable({ profiles, accounts, research, equipment, repair, ...catalogues, clans: { store: clans, economy: squadronEconomy }, cloudSettings, 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, matchingTable, log, loadOrCreateCredentials(options.dataFolder), ); matching = listener.matching; await listen(listener.server, options.port); await modRuntime.runServerListening(options.port); return { logFolder: log.folder, 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, localizedUnitNames: UnitNamesMap, ) { const classicItemDefs = datasets.load(itemCatalogue); return { crew: new CrewSkillCatalogue(datasets.load(crewSkillData)), decor: new DecorShop(datasets.load(decorCatalogue)), unlocks: new UnlockShop(datasets.load(unlockPrices)), items: new ItemCatalogue(classicItemDefs, tuning.limits.itemPiecesPerPurchase), store: new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames, labels, tuning.store), inventory: new InventoryCatalogue(vehicles, localizedUnitNames, datasets.load(externalItemSources), classicItemDefs, tuning), trophies: new TrophyCatalogue(vehicles, classicItemDefs, tuning.trophies), training: new TrainingCatalogue(datasets.load(trainingMissions)), clanEconomy: datasets.load(clanEconomy), }; } function listen(server: Server, port: number): Promise { return new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, LOOPBACK, () => { server.off('error', reject); resolve(); }); }); }