Fix store.jsonc vehiclePacks nesting and gjn field name, matchingApiFunc callback argument order, and DaGui CSS @import/lowercase rules; add stock archive inspection steps, BR-to-mrank table, cloned vehicle walkthrough, tuning field reference, and official-map-selector full-stack trace while bringing en/01..07.md to full 1:1 parity with zh-CN/.
15 KiB
06 · Server JS/TS Scripting API Reference
Experimental Warning (API
0.1-experimental) All server scripting interfaces and internal catalogue objects documented here are in early active development and may change across WTOffline releases without backwards compatibility.
1. Runtime Environment, Node 24 Erasable TS Rules & VS Code Autocomplete
The local server runs inside the launcher's bundled Electron 43 / Node.js 24 runtime with native TypeScript type stripping enabled—players do not need Node.js or TypeScript installed on their PCs to run your .ts scripts directly!
- Default entry lookup order:
server/index.ts→server/index.mjs→server/index.js(or override viaserver.entryinmod.jsonc); - Third-party npm packages or non-erasable syntax: if needed, bundle your code ahead of time into a single-file
server/index.mjswithesbuildortsc.
1.1 Raw .ts Syntax Rule (erasableSyntaxOnly Do vs Don't)
Node 24's built-in TypeScript stripper erases type annotations without emitting extra runtime JS code. All interface, type, generic, and as constructs work natively, except enum, namespace, and constructor parameter properties (constructor(private x: number)):
// ❌ DON'T: Node 24 native TS stripping rejects `enum` at startup!
enum FilterMode { All = 'all', Include = 'include', Exclude = 'exclude' }
// ✅ DO: Use an `as const` object + union type (zero runtime overhead, 100% compatible!)
const FILTER_MODE = { All: 'all', Include: 'include', Exclude: 'exclude' } as const;
type FilterMode = (typeof FILTER_MODE)[keyof typeof FILTER_MODE];
1.2 How External Modders Get Full VS Code Autocomplete
Download packages/mods/src/server-api.ts (along with its sibling types.ts) from the WTOffline repository into your mod's server/ folder and import types using import type:
// ✅ DO: `import type` is completely erased by Node 24 at runtime while giving full VS Code IntelliSense!
import type { WtoServerModContext } from './server-api.ts';
// ❌ Avoid value-importing `@wto/mods` at runtime (external mod folders do not have monorepo node_modules)
// import { something } from '@wto/mods';
export default {
async setup(ctx: WtoServerModContext) {
ctx.logger.info('mod initialized');
},
};
Tip: Alongside
export default { setup(ctx) { ... } }, the runtime also acceptsexport default function (ctx) { ... }or a namedexport function setup(ctx) { ... }. You can also declare lightweight structuralinterfaceviews directly at the top ofserver/index.ts(just liketemplates/official-map-selector/server/index.ts) for a zero-dependency single file.
2. WtoServerModContext Property Reference
| Property | Type | Description |
|---|---|---|
ctx.apiVersion |
string |
Active experimental API tag ("0.1-experimental") |
ctx.manifest |
ModManifest |
Parsed mod.jsonc manifest of this mod |
ctx.modDir |
string |
Absolute path to this mod's root directory (read static mod files via node:fs) |
ctx.gameFolder |
string |
Active offline game copy root directory |
ctx.dataFolder |
string |
Active client data folder (saves, caches, logs) |
ctx.port |
number |
Bound local server port for the current session |
ctx.logger |
{ info, warn, error } |
Logger prefixed with [mod:<id>], written to launcher.log and diagnostic exports |
ctx.storage |
ModStorageApi |
Atomic JSON storage scoped per player or shared across accounts (Section 3) |
ctx.hooks |
ServerModHooksApi |
Lifecycle, profile, matchmaking, and battle settlement hooks (Section 4) |
ctx.routes |
ServerModRoutesApi |
matching, http, and char route extensions (Section 5) |
3. Isolated Mod Storage (ctx.storage)
Recommended practice: Keep custom mod data out of the player's profile.blk (non-stock keys can interfere with client serialization and remain behind after a mod is removed). Store mod state, settings, and progression in ctx.storage:
// ① Scoped per local player account: <dataFolder>/saves/<userId>/mods/<modId>.json
const playerStore = ctx.storage.forPlayer(userId);
const prev = playerStore.read<{ wins: number }>() ?? { wins: 0 };
playerStore.write({ wins: prev.wins + 1 }); // Atomic temp-file rename write
// playerStore.remove();
// ② Shared across all accounts for this mod: <dataFolder>/mods-data/<modId>.json
const sharedStore = ctx.storage.shared();
4. Lifecycle, Profile & Battle Hooks (ctx.hooks)
4.1 ctx.hooks.onDatasetsLoaded(async (datasets) => { ... })
Fires after static datasets are extracted from the overlaid .vromfs.bin packs and before domain catalogues are constructed. Inspect or mutate:
datasets.vehicles: vehicle array (CatalogueVehicle[]with prices, RP, BRs, tech-tree links)datasets.battleEconomy: battle action reward rates and per-vehicle multipliersdatasets.battleSpawnRules: spawn costs, support planes, and spawn rulesdatasets.multiplayerMissions:{ categories, missions }mission metadatadatasets.uiLabels/datasets.unitNames: localized UI strings and vehicle namesdatasets.get(datasetId)/datasets.set(datasetId, value): read or replace any raw dataset by ID
4.2 ctx.hooks.onCataloguesReady(async (catalogues) => { ... })
Fires after all domain catalogues and services are assembled, right before the server starts listening:
catalogues.tuning: merged read-onlyTuningcatalogues.gameModes:GameModesinstance (ids(),byId(id),byName(name),byEconomicName(name),countries())catalogues.profiles/accounts/research/equipment/repaircatalogues.store/inventory/trophies/items/crew/decor/unlocks/clanscatalogues.battleMatchmaker/battleEconomy/battleStreakscatalogues.notifyInventoryChanged(): push live external-inventory refresh to connected clientscatalogues.notifyUser(userId, eventName, payload): send a livemrpc.generic_notifyevent to a logged-in player
4.3 ctx.hooks.onServerListening(({ port }) => { ... }) / onServerClosing(() => { ... })
Fires once the HTTP/matching port is listening, and in reverse mod order right before shutdown (ideal for logging URLs or clearing timers).
4.4 Profile Hook: ctx.hooks.profile.onRefresh((profile, userId) => { ... })
Fires whenever a player profile is loaded or updated and finishes the native refresh pipeline (profile is an @wto/blk BlkBlock). Read profile facts here and persist derived mod state in ctx.storage.forPlayer(userId).
4.5 Matchmaking & Battle Hooks (ctx.hooks.battle)
① ctx.hooks.battle.onBeforeMatchmake(({ userId, eventName, request }) => { ... })
Fires when the player clicks To Battle! (match.enqueue) before BattleMatchmaker runs; request holds the raw client enqueue parameters.
② ctx.hooks.battle.onFilterMissions((ctx) => { ... })
Fires after BattleMatchmaker narrows candidate two-sided missions for the chosen mode and BR window, right before random map selection:
ctx:{ userId, modeId, modeName, economicName, minMrank, maxMrank, missions };- Each
missionhas{ name, path, level?, type?, locName?, postfix? }; - Return value: return your filtered subset array (or
undefinedto leave unchanged). If an empty array[]is returned, the server logs a warning and safely falls back to the previous candidate pool so matchmaking never deadlocks.
// Example: restrict matches to maps whose level path or name matches poland or berlin
ctx.hooks.battle.onFilterMissions(({ missions }) => {
const picked = missions.filter((m) => /poland|berlin/i.test(m.level ?? m.name));
return picked.length > 0 ? picked : undefined;
});
③ ctx.hooks.battle.onLiveFact(({ userId, roomId, fact }) => { ... })
Fires live during a running LocalMP battle whenever the client reports a wto_battle.fact event (roomId is the 16-character hex sessionId). fact always carries { sessionId, localPlayerId, localTeam, kind } plus fields determined by fact.kind:
fact.kind |
When It Fires | Additional fact Fields |
|---|---|---|
"event" |
Local player scores a kill, assist, capture, hit, or award event | { time, unit, code, expClass, victim, victimIsPlayer, friendly, modifier, damage } |
"life" |
Local player spawn life segment updates or ends in death | { unit, start, end, died } |
"kill" |
Any kill appears in the HUD killfeed (including AI-vs-AI kills) | { time, killer, killerTeam, victim, victimTeam } (MPlayer IDs, -1 if unit has no player) |
"strike" |
Local player's nuclear bomb detonates | { time } |
④ ctx.hooks.battle.onAfterSettle(({ userId, roomId, summary }) => { ... })
Fires at battle end right after native settleBattle applies SL/RP rewards and right before the updated profile is written to disk. summary has the exact shape { profile, report, session }:
summary.profile: the player'sBlkBlockprofile with post-battle rewards applied;summary.report: parsedBattleReport(outcome: 'win' | 'lose' | 'running',localTeam,teamAScore,teamBScore,sessionStart,sessionEnd,lives,events,feed,playersscoreboard rows,nuclearStrikes,spares);summary.session:BattleSessionmetadata (sessionId,roomId,modeId,modeName,economicName,difficulty,requiredClass,missionName,country, etc.).
Reminder: Persist any custom mod achievements, streaks, or campaign progression in
ctx.storage.forPlayer(userId)rather than mutating non-stock keys ontosummary.profile!
5. Choosing Between the 3 Route Channels & Exact matchingApiFunc Signature (ctx.routes)
5.1 Which Route API Should I Use?
| Route API | Best For | Payload Format | How the Client Calls It |
|---|---|---|---|
ctx.routes.matching (Recommended) |
Native DaGui .nut modals exchanging JSON data with your server script (settings, map rules, custom state) |
Plain JSON params in → JSON object out |
Quirrel matchingApiFunc("wto_mod.<method>", callback, params) |
ctx.routes.http |
Rich HTML/CSS/JS web dashboards, external browser panels, or REST endpoints (auto-namespaced under /mods/<modId>/...) |
Standard HTTP request / response | System browser or War Thunder's embedded browser at http://{{LOCAL_ENDPOINT}}/mods/<modId>/... |
ctx.routes.char |
Wrapping stock cln_* profile actions or adding low-level binary BLK actions |
Raw binary/text Buffer |
Low-level client char action requests |
5.2 Matching JSON RPC (ctx.routes.matching) — Mind the Client Argument Order!
Registering a custom matching RPC on the server takes just a few lines (req provides { method, params, userId } and returns any JSON object; wrap(method, (req, next) => ...) is also available):
ctx.routes.matching.register('wto_mod.my_mod.ping', ({ userId, params }) => ({
ok: true,
userId,
echo: params,
}));
P0 Gotcha: In Quirrel's
matchingApiFunc,callbackIs the 2nd Argument andparamsIs the 3rd Argument! In stockgui.vromfs.bin%scripts/matching/api.nut, the signature isfunction matchingApiFunc(name, cb, params = null). Passing(name, params, callback)in the wrong order sends empty params and skips your callback.
Correct Quirrel .nut call:
from "%scripts/matching/api.nut" import matchingApiFunc
// ✅ Arg 1: RPC method | Arg 2: Callback | Arg 3: Request params table
matchingApiFunc("wto_mod.my_mod.ping",
Callback(@(resp) this.onPingResponse(resp), this),
{
hello = "world"
})
5.3 Local HTTP & Embedded Browser Routes (ctx.routes.http)
Routes are automatically namespaced under /mods/<yourModId>/... and support both exact paths and /* wildcards:
ctx.routes.http.register('/panel', () => ({
status: 200,
contentType: 'text/html; charset=utf-8',
body: '<!doctype html><meta charset="utf-8"><h1>My Mod Control Panel</h1>',
}));
ctx.routes.http.register('/api/*', (req) => ({
status: 200,
contentType: 'application/json; charset=utf-8',
body: JSON.stringify({ method: req.method, path: req.path, query: req.query }),
}));
To open that page inside War Thunder's native embedded browser from a hangar button, use the {{LOCAL_ENDPOINT}} placeholder inside a client/gui-patches/ replacement snippet:
from "%scripts/onlineShop/url.nut" import openUrl
openUrl("http://{{LOCAL_ENDPOINT}}/mods/demo.my-mod/panel", false, false)
5.4 Char Action Interception & Custom Actions (ctx.routes.char)
ctx.routes.char.register(action, handler): register a brand-newcln_*action;ctx.routes.char.wrap(action, async (req, next) => { ... }): wrap an existingcln_*action aroundawait next(req).
6. Full-Stack Case Study: How official-map-selector Connects End to End
Open mods/official-map-selector/ (source in mod-dev-docs/templates/official-map-selector/): it is a complete reference implementation connecting native client UI, matching RPCs, isolated player storage, and server matchmaking hooks across 5 clean layers:
[1. Minimal Entry Hooks: client/gui-patches/]
├─ gui/gamemodeselect/gamemodeselect.tpl → Inserts the "Custom Map Pool" button into the footer bar
├─ scripts/gamemodes/gamemodeselect.nut → Wires button click to WtoMapSelectorModal.open({ gameMode })
└─ gui/css.css → Appends @import "missions\wtomapselector.css"
│
▼
[2. Standalone Native Modal: client/packs/gui.vromfs.bin/ + lang.vromfs.bin/]
├─ scripts/missions/wtomapselectormodal.nut → Subclasses BaseGuiHandlerWT; renders search, filter tabs & tactical map preview
├─ gui/missions/wtomapselectormodal.tpl → Modal layout & card grid template (wtomapselectorcards.tpl)
├─ gui/missions/wtomapselector.css → Selected card badge & border styling
└─ lang/menu.csv.patch.csv → Localized wto/mapSelector/* UI strings (EN / ZH)
│
▼ matchingApiFunc("wto_mod.map_selector.get" / ".set", Callback(...), { modeName, ... })
[3. Server Matching RPCs: server/index.ts -> ctx.routes.matching.register]
├─ Indexes playable two-sided map pools per PvP mode during onCataloguesReady(catalogues.gameModes)
├─ wto_mod.map_selector.get → Returns the mode's map list + the player's saved filter rule
└─ wto_mod.map_selector.set → Validates & saves the player's all / include / exclude selection
│
▼
[4. Per-Account Isolated Storage: ctx.storage.forPlayer(userId)]
└─ Atomically writes <dataFolder>/saves/<userId>/mods/official.map-selector.json (never touches profile.blk)
│
▼
[5. Matchmaking Map Filter: ctx.hooks.battle.onFilterMissions]
└─ Filters candidate missions by whitelist/blacklist on "To Battle!", falling back to the full pool with a log warning if 0 maps match at that BR
Reading templates/official-map-selector alongside this diagram gives you a production-tested blueprint for virtually any full-stack WTOffline mod!