Files
WT-Offline/packages/local-service/src/saves/save-store.ts
T
N0VAN0M4LY 2fc28dd7a5 Grant reserve vehicles and support crew presets
Derive reserve vehicles from the stock economy data. Grant all reserves
and mark the basic takeoff and landing tutorials complete in new saves.
Apply the same grants through the format 2 migration.

Use shared crew slot rules for first-run selection, presets, training,
assignment, and removal.
2026-11-24 14:18:02 +08:00

65 lines
2.4 KiB
TypeScript

/**
* Save layer: one save per account, holding the profile in Gaijin's
* profile structure.
*
* <data>/saves/<userId>/save.json format version and bookkeeping
* <data>/saves/<userId>/profile.blk the profile, binary BLK with every value's type kept
*
* Every write reaches the disk before the caller replies to the game. A save written by an
* older format version is upgraded step by step when it is opened (save-upgrades.ts).
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import type { SaveUpgrades } from './save-upgrades.ts';
interface SaveInfo {
formatVersion: number;
created: string;
updated: string;
}
export class SaveStore {
readonly #folder: string;
readonly #upgrades: SaveUpgrades;
constructor(dataFolder: string, upgrades: SaveUpgrades) {
this.#folder = join(dataFolder, 'saves');
this.#upgrades = upgrades;
}
/** The account's profile, or undefined when the account has no save yet. */
loadProfile(userId: string): BlkBlock | undefined {
const infoPath = this.#infoPath(userId);
if (!existsSync(infoPath)) return undefined;
const info = JSON.parse(readFileSync(infoPath, 'utf8')) as SaveInfo;
const profile = decodeBlk(readFileSync(this.#profilePath(userId)));
if (info.formatVersion === this.#upgrades.currentFormat) return profile;
const upgraded = this.#upgrades.upgrade(profile, info.formatVersion);
this.saveProfile(userId, upgraded);
return upgraded;
}
saveProfile(userId: string, profile: BlkBlock): void {
const now = new Date().toISOString();
const previous = existsSync(this.#infoPath(userId)) ? (JSON.parse(readFileSync(this.#infoPath(userId), 'utf8')) as SaveInfo) : undefined;
writeFileAtomic(this.#profilePath(userId), encodeBlk(profile));
const info: SaveInfo = { formatVersion: this.#upgrades.currentFormat, created: previous?.created ?? now, updated: now };
writeFileAtomic(this.#infoPath(userId), JSON.stringify(info, null, 2));
}
#infoPath(userId: string): string {
return join(this.#folder, safeId(userId), 'save.json');
}
#profilePath(userId: string): string {
return join(this.#folder, safeId(userId), 'profile.blk');
}
}
function safeId(userId: string): string {
if (!/^\d+$/.test(userId)) throw new Error(`invalid user id: ${userId}`);
return userId;
}