feat(patcher): support additive mod pack overlays, addon mounts, and protected exe patches

This commit is contained in:
N0VAN0M4LY committed 2026-12-02 23:48:34 +08:00
1 parent 8fbaeb4228
commit fd9d25d346
11 files changed
+1088 -24

No files matched your search

+1 -1
View File
@@ -13,6 +13,6 @@ export { DefinitionError, LocateError, PatchError, PeFormatError, VerifyError }
export { asObject, readJsonObject, rejectUnknownKeys, requiredString, stringList, variantObjects } from './json-fields.ts';
export { NO_CONTEXT, type LocateContext } from './locate/index.ts';
export { PeImage, type FunctionRange, type Section } from './pe-image.ts';
export { describePlan, planPatches, type PatchFailure, type PatchPlan, type PlannedWrite } from './plan.ts';
export { describePlan, planAdditionalPatches, planPatches, type PatchFailure, type PatchPlan, type PlannedWrite } from './plan.ts';
export { findSite, readSiteSpec, type FoundSite, type SiteSpec } from './site.ts';
export { chooseVariant, type Chosen, type Variant } from './variants.ts';
+61
View File
@@ -58,6 +58,67 @@ export function planPatches(image: PeImage, definitions: readonly PatchDefinitio
return { writes, failures };
}
/**
* Plan additive patches (such as declarative mod exe patches) on top of locked core writes.
* Any patch that fails to locate/verify, depends on a failed patch, overlaps a protected core
* write, or overlaps an earlier accepted additive write is recorded in `failures` rather than
* throwing, so core offline isolation patches are never overwritten or broken.
*/
export function planAdditionalPatches(
image: PeImage,
definitions: readonly PatchDefinition[],
protectedWrites: readonly PlannedWrite[],
): PatchPlan {
const planned = new Map<string, PlannedWrite>();
const failed = new Map<string, string>();
for (const definition of definitions) {
try {
const chosen = chooseVariant(definition.variants, (variant) => planVariant(image, variant));
planned.set(definition.id, { patchId: definition.id, variant: chosen.variant.writtenFor, ...chosen.value });
} catch (error) {
if (!(error instanceof PatchError)) throw error;
failed.set(definition.id, error.message);
}
}
propagateFailures(definitions, failed);
const accepted: PlannedWrite[] = [];
for (const definition of definitions) {
if (failed.has(definition.id)) continue;
const candidate = planned.get(definition.id)!;
const coreConflict = findOverlappingWrite(candidate, protectedWrites);
if (coreConflict) {
failed.set(definition.id, `overlaps protected core patch "${coreConflict.patchId}" at ${hex(candidate.rva)}`);
continue;
}
const earlierConflict = findOverlappingWrite(candidate, accepted);
if (earlierConflict) {
failed.set(definition.id, `overlaps earlier patch "${earlierConflict.patchId}" at ${hex(candidate.rva)}`);
continue;
}
accepted.push(candidate);
}
// Re-propagate if an overlap rejection broke a downstream dependency.
const beforeSecondPass = failed.size;
propagateFailures(definitions, failed);
const writes = failed.size === beforeSecondPass
? accepted
: accepted.filter((write) => !failed.has(write.patchId));
const failures = definitions.filter((item) => failed.has(item.id))
.map((item) => ({ patchId: item.id, features: item.features, reason: failed.get(item.id)! }));
return { writes, failures };
}
function findOverlappingWrite(candidate: PlannedWrite, existing: readonly PlannedWrite[]): PlannedWrite | undefined {
const cStart = candidate.fileOffset;
const cEnd = cStart + candidate.payload.length;
return existing.find((write) => {
const wStart = write.fileOffset;
const wEnd = wStart + write.payload.length;
return cStart < wEnd && wStart < cEnd;
});
}
export function describePlan(plan: PatchPlan): string {
const lines = [`${plan.writes.length} patch(es) ready, ${plan.failures.length} unavailable`];
for (const write of plan.writes) lines.push(` ready ${write.patchId} at ${hex(write.rva)} (variant ${write.variant})`);
+1
View File
@@ -10,6 +10,7 @@
"@wto/blk": "*",
"@wto/exepatch": "*",
"@wto/jsonc": "*",
"@wto/mods": "*",
"@wto/vromfs": "*",
"fflate": "^0.8.2"
}
+85 -17
View File
@@ -1,21 +1,27 @@
/**
* Build the files of the game copy in memory: the three rebuilt data packs,
* the patched executable, the network hook library and its settings. Nothing is written here
* Build the files of the game copy in memory: the rebuilt data packs (with optional additive mod
* overlays), the patched executable (with protected core patches + optional declarative mod exe
* patches), the network hook library and its settings. Nothing is written here
* (write-game-copy.ts does that), so a caller can show the report first and let the player decide.
*
* Everything the build needs from outside comes in as an input: the stock files, the patch set
* (patch-set.ts), the hook library, and the multi-vehicle pack ids the local server will sell from its
* data folder.
* (patch-set.ts), the hook library, the multi-vehicle pack ids the local server will sell, and
* optionally the ordered list of enabled mods with any additional stock packs they touch.
*/
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { PeImage, type PatchFailure } from '@wto/exepatch';
import { touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods';
import { rebuildCharPack, type CharPackResult } from './char-pack.ts';
import { blockingFailures } from './essential-features.ts';
import { patchExecutable } from './executable.ts';
import { patchExecutableWithMods, type ModExePatchFailure } from './executable.ts';
import { GAME_FILES } from './game-copy.ts';
import { rebuildGuiPack } from './gui-pack.ts';
import { rebuildMainPack } from './main-pack.ts';
import { collectModAddonMounts, type ModAddonMount } from './mods/addon-register.ts';
import { CORE_BUILD_PACKS } from './mods/deploy-external.ts';
import { applyModGuiPatches } from './mods/gui-overlay.ts';
import { applyModPackOverlays, type PackOverlayReport } from './mods/pack-overlay.ts';
import type { AddressChange } from './network/address-rewrite.ts';
import { localEndpoint, type LocalEndpoint } from './network/local-endpoint.ts';
import { NETWORK_HOOK_LIBRARY, networkHookSettings } from './network/network-hook.ts';
@@ -46,6 +52,10 @@ export interface GameCopyInputs {
readonly placeholderDecals: boolean;
/** Whether wto_ws.dll writes win64/wto_ws.log; defaults to true. */
readonly hookLogging?: boolean;
/** Ordered list of enabled additive mods to overlay onto this build. */
readonly mods?: readonly DiscoveredMod[];
/** Stock bytes of optional packs (lang/mis/game/ui/*) touched by enabled mods. */
readonly extraStockPacks?: Partial<Record<ModdableClientPack, Uint8Array>>;
}
/** One file of the game copy, by its path relative to the copy folder. */
@@ -54,6 +64,20 @@ export interface GameCopyFile {
readonly content: Uint8Array;
}
export interface ModBuildReport {
readonly enabledModIds: readonly string[];
readonly packOverlays: readonly PackOverlayReport[];
readonly addonMounts: readonly ModAddonMount[];
readonly guiPatches: {
readonly applied: readonly { readonly modId: string; readonly patchId: string }[];
readonly failures: readonly (PatchFailure & { readonly modId: string })[];
};
readonly exePatches: {
readonly applied: readonly { readonly modId: string; readonly patchId: string; readonly rva: number }[];
readonly failures: readonly ModExePatchFailure[];
};
}
export interface GameCopyBuild {
/** Every file to write, with unavailable patches left out. */
readonly files: readonly GameCopyFile[];
@@ -69,6 +93,8 @@ export interface GameCopyBuild {
readonly engineAddresses: readonly AddressChange[];
/** Store bundle GUIDs registered in config/gui.blk. */
readonly bundleGuids: number;
/** Details of additive mod overlays applied during this build. */
readonly mods: ModBuildReport;
}
export function readStockGameFiles(folder: string): StockGameFiles {
@@ -83,43 +109,85 @@ export function readStockGameFiles(folder: string): StockGameFiles {
export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild {
const endpoint = localEndpoint(inputs.port);
const folders = patchSetFolders(inputs.patches);
const executable = patchExecutable(inputs.stock.executable, folders.exe);
const enabledMods = inputs.mods ?? [];
const packOverlays: PackOverlayReport[] = [];
const executable = patchExecutableWithMods(inputs.stock.executable, folders.exe, enabledMods);
const stockImage = new PeImage(inputs.stock.executable);
const native = resolveNativeModules(stockImage, loadNativeModules(folders.native));
const guiPack = rebuildGuiPack(inputs.stock.guiPack, endpoint, folders.gui);
const appliedGuiPatches = guiPack.applied.map((item) => item.patch.id);
const coreGuiPack = rebuildGuiPack(inputs.stock.guiPack, endpoint, folders.gui);
const appliedGuiPatches = coreGuiPack.applied.map((item) => item.patch.id);
const guiPackFileOverlay = applyModPackOverlays(coreGuiPack.pack, 'gui.vromfs.bin', enabledMods);
if (guiPackFileOverlay.report.operationsApplied > 0) packOverlays.push(guiPackFileOverlay.report);
const modGuiResult = applyModGuiPatches(guiPackFileOverlay.pack, endpoint, enabledMods);
const localRegistration = appliedGuiPatches.includes('registration/open-local-page') &&
appliedGuiPatches.includes('registration/keep-local-page-embedded');
const { pack: charPack, ...charReport } = rebuildCharPack(inputs.stock.charPack, endpoint, {
const { pack: coreCharPack, ...charReport } = rebuildCharPack(inputs.stock.charPack, endpoint, {
placeholderDecals: inputs.placeholderDecals,
localRegistration,
});
const bundles = offlinePackBundleGuids(inputs.stock.charPack, inputs.multiVehiclePackIds);
const mainPack = rebuildMainPack(inputs.stock.mainPack, endpoint, bundles);
const charOverlay = applyModPackOverlays(coreCharPack, 'char.vromfs.bin', enabledMods);
if (charOverlay.report.operationsApplied > 0) packOverlays.push(charOverlay.report);
// Derive store bundle GUIDs from the mod-overlaid charPack so newly added mod gift vehicles
// automatically receive deterministic offline store bundle GUIDs.
const bundles = offlinePackBundleGuids(charOverlay.pack, inputs.multiVehiclePackIds);
const addonMounts = collectModAddonMounts(enabledMods);
const coreMainPack = rebuildMainPack(
inputs.stock.mainPack,
endpoint,
bundles,
addonMounts.map((mount) => mount.mountFolder),
);
const mainOverlay = applyModPackOverlays(coreMainPack.pack, 'aces.vromfs.bin', enabledMods);
if (mainOverlay.report.operationsApplied > 0) packOverlays.push(mainOverlay.report);
const executableFolder = dirname(GAME_FILES.executable);
const hookSettings = networkHookSettings(endpoint, stockImage, native.values, {
loggingEnabled: inputs.hookLogging ?? true,
});
const files: GameCopyFile[] = [
{ path: GAME_FILES.charPack, content: charPack },
{ path: GAME_FILES.mainPack, content: mainPack.pack },
{ path: GAME_FILES.guiPack, content: guiPack.pack },
{ path: GAME_FILES.charPack, content: charOverlay.pack },
{ path: GAME_FILES.mainPack, content: mainOverlay.pack },
{ path: GAME_FILES.guiPack, content: modGuiResult.pack },
{ path: GAME_FILES.executable, content: executable.executable },
{ path: join(executableFolder, NETWORK_HOOK_LIBRARY), content: inputs.networkHookLibrary },
{ path: join(executableFolder, hookSettings.name), content: hookSettings.content },
];
const failures = [...executable.plan.failures, ...guiPack.failures, ...native.failures];
// Rebuild any optional client packs (lang, mis, game, ui/atlases, ui/images) touched by enabled mods.
for (const pack of touchedClientPacks(enabledMods)) {
if (CORE_BUILD_PACKS.has(pack)) continue;
const stockBytes = inputs.extraStockPacks?.[pack];
if (!stockBytes) {
throw new Error(`mod overlay requires stock pack "${pack}" in extraStockPacks`);
}
const overlay = applyModPackOverlays(stockBytes, pack, enabledMods);
if (overlay.report.operationsApplied > 0) {
packOverlays.push(overlay.report);
files.push({ path: join(...pack.split('/')), content: overlay.pack });
}
}
const failures = [...executable.plan.failures, ...coreGuiPack.failures, ...native.failures];
return {
files,
endpoint,
exePatches: { applied: executable.plan.writes.map((write) => ({ patchId: write.patchId, rva: write.rva })), failures: executable.plan.failures },
guiPatches: { applied: appliedGuiPatches, failures: guiPack.failures },
guiPatches: { applied: appliedGuiPatches, failures: coreGuiPack.failures },
nativeModules: { available: [...native.available.keys()], failures: native.failures },
blocking: blockingFailures(failures),
charPack: charReport,
engineAddresses: mainPack.addresses,
engineAddresses: coreMainPack.addresses,
bundleGuids: bundles.length,
mods: {
enabledModIds: enabledMods.map((mod) => mod.manifest.id),
packOverlays,
addonMounts,
guiPatches: { applied: modGuiResult.applied, failures: modGuiResult.failures },
exePatches: { applied: executable.modApplied, failures: executable.modFailures },
},
};
}
+94 -5
View File
@@ -1,10 +1,21 @@
/**
* Patch a copy of aces.exe with every definition under the exe patch folder. A patch that cannot
* be applied (site missing or ambiguous, original bytes differ, or a patch it requires failed) is
* left out and listed with the features it covers; whether a copy with
* patches missing may be installed is the caller's decision (essential-features.ts).
* Patch a copy of aces.exe with every definition under the core exe patch folder, and optionally
* apply declarative mod exe patches on top while keeping every core patch byte range locked.
*/
import { applyWrites, describePlan, loadPatches, PeImage, planPatches, type PatchPlan } from '@wto/exepatch';
import { join } from 'node:path';
import {
applyWrites,
describePlan,
loadPatches,
PeImage,
planAdditionalPatches,
planPatches,
type PatchDefinition,
type PatchFailure,
type PatchPlan,
type PlannedWrite,
} from '@wto/exepatch';
import type { DiscoveredMod } from '@wto/mods';
export interface ExecutableResult {
/** The executable with every available patch written. */
@@ -13,7 +24,85 @@ export interface ExecutableResult {
readonly description: string;
}
export interface ModExePatchFailure extends PatchFailure {
readonly modId: string;
}
export interface ModExecutableResult extends ExecutableResult {
readonly modApplied: readonly { readonly modId: string; readonly patchId: string; readonly rva: number }[];
readonly modFailures: readonly ModExePatchFailure[];
}
export function patchExecutable(stockExecutable: Uint8Array, patchesRoot: string): ExecutableResult {
const plan = planPatches(new PeImage(stockExecutable), loadPatches(patchesRoot));
return { executable: applyWrites(stockExecutable, plan.writes), plan, description: describePlan(plan) };
}
export function patchExecutableWithMods(
stockExecutable: Uint8Array,
corePatchesRoot: string,
mods: readonly DiscoveredMod[],
): ModExecutableResult {
const image = new PeImage(stockExecutable);
const corePlan = planPatches(image, loadPatches(corePatchesRoot));
const modsWithExe = mods.filter((mod) => mod.content.exePatchDirs.length > 0);
if (modsWithExe.length === 0) {
return {
executable: applyWrites(stockExecutable, corePlan.writes),
plan: corePlan,
description: describePlan(corePlan),
modApplied: [],
modFailures: [],
};
}
const allModDefs: PatchDefinition[] = [];
const ownerById = new Map<string, string>();
const loadFailures: ModExePatchFailure[] = [];
for (const mod of modsWithExe) {
const exeRoot = join(mod.rootDir, 'client', 'exe-patches');
try {
const defs = loadPatches(exeRoot);
for (const def of defs) {
const namespacedId = `${mod.manifest.id}/${def.id}`;
ownerById.set(namespacedId, mod.manifest.id);
allModDefs.push({
...def,
id: namespacedId,
requires: def.requires.map((req) => (req.includes('/') ? req : `${mod.manifest.id}/${req}`)),
});
}
} catch (error) {
loadFailures.push({
modId: mod.manifest.id,
patchId: `${mod.manifest.id}:exe-patches`,
features: [],
reason: error instanceof Error ? error.message : String(error),
});
}
}
const modPlan = planAdditionalPatches(image, allModDefs, corePlan.writes);
const combinedWrites: readonly PlannedWrite[] = [...corePlan.writes, ...modPlan.writes];
const modApplied = modPlan.writes.map((write) => ({
modId: ownerById.get(write.patchId) ?? 'unknown',
patchId: write.patchId,
rva: write.rva,
}));
const modFailures: ModExePatchFailure[] = [
...loadFailures,
...modPlan.failures.map((failure) => ({
...failure,
modId: ownerById.get(failure.patchId) ?? 'unknown',
})),
];
return {
executable: applyWrites(stockExecutable, combinedWrites),
plan: corePlan,
description: describePlan(corePlan),
modApplied,
modFailures,
};
}
+30 -1
View File
@@ -10,12 +10,41 @@ export {
type GameCopyBuild,
type GameCopyFile,
type GameCopyInputs,
type ModBuildReport,
type StockGameFiles,
} from './build-game-copy.ts';
export { NETWORK_CONFIG_PATH, rebuildCharPack, type CharPackResult } from './char-pack.ts';
export { copyPlayerDecalCache, playerDecalCacheProblem } from './decals/player-decal-cache.ts';
export { blockingFailures, ESSENTIAL_FEATURES } from './essential-features.ts';
export { patchExecutable, type ExecutableResult } from './executable.ts';
export {
patchExecutable,
patchExecutableWithMods,
type ExecutableResult,
type ModExecutableResult,
type ModExePatchFailure,
} from './executable.ts';
export {
addonMountFolderForMod,
collectModAddonMounts,
registerModAddonsInSettings,
type ModAddonMount,
} from './mods/addon-register.ts';
export {
computeModsBuildFingerprint,
CORE_BUILD_PACKS,
MODS_STATE_FILE,
prepareOptionalStockPacks,
readModsDeployState,
syncExternalModFiles,
writeModsDeployState,
type DeployedModEntry,
type DeployEntryKind,
type ModDeployWarning,
type ModExternalDeployResult,
type ModsDeployState,
} from './mods/deploy-external.ts';
export { applyModGuiPatches, type ModGuiPatchResult } from './mods/gui-overlay.ts';
export { applyModPackOverlays, type PackOverlayReport } from './mods/pack-overlay.ts';
export { assertWritableCopy, GAME_FILES, isInSteamLibrary, type WritableCopyOptions } from './game-copy.ts';
export { executableVersion } from './game-version.ts';
export {
+3
View File
@@ -13,6 +13,7 @@
* server addresses.
*/
import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
import { registerModAddonsInSettings } from './mods/addon-register.ts';
import { redirectAddresses, type AddressChange } from './network/address-rewrite.ts';
import type { LocalEndpoint } from './network/local-endpoint.ts';
import { editPackBlks } from './pack-edit.ts';
@@ -42,6 +43,7 @@ export function rebuildMainPack(
stockPack: Uint8Array,
endpoint: LocalEndpoint,
extraBundles: ReadonlyArray<readonly [string, string]> = [],
extraAddonFolders: readonly string[] = [],
): MainPackResult {
let addresses: AddressChange[] = [];
const pack = editPackBlks(stockPack, [
@@ -51,6 +53,7 @@ export function rebuildMainPack(
const network = findBlock(root, NETWORK_BLOCK);
if (!network) throw new Error(`${ENGINE_SETTINGS_PATH} has no "${NETWORK_BLOCK}" block; this game build differs from the verified ones`);
addresses = redirectAddresses(network, endpoint, [NETWORK_BLOCK]);
registerModAddonsInSettings(root, extraAddonFolders);
},
},
{
@@ -0,0 +1,57 @@
/**
* Compute engine addon mount paths for mods shipping 3D models/textures (`client/addon/`)
* and register them into `aces.vromfs.bin` `config/settings.blk`.
*
* Engine behaviour verified in 2.61.0.x aces.exe (0xc90932..0xc92754):
* - Paths containing `/pkg_user/` skip the mandatory `res/grp_hdr.vromfs.bin` check and
* directly scan `%s/res/` for all `.grp` and `.dxp.bin` archives.
* - Addons that ship a compiled `res/grp_hdr.vromfs.bin` use a dedicated `content/pkg_wto_<id>`
* folder so the native grp_hdr loader handles them.
*/
import { appendParam, ensureBlock, type BlkBlock } from '@wto/blk';
import type { DiscoveredMod } from '@wto/mods';
export interface ModAddonMount {
readonly modId: string;
/** Relative folder inside the game copy, e.g. `content/pkg_user/example_mod`. */
readonly mountFolder: string;
/** Absolute source folder `<modRoot>/client/addon`. */
readonly sourceDir: string;
}
export function addonMountFolderForMod(mod: DiscoveredMod): string {
const safeName = mod.manifest.id.replace(/[^a-z0-9_-]/g, '_');
return mod.content.addonHasGrpHdr
? `content/pkg_wto_${safeName}`
: `content/pkg_user/${safeName}`;
}
export function collectModAddonMounts(mods: readonly DiscoveredMod[]): ModAddonMount[] {
const mounts: ModAddonMount[] = [];
for (const mod of mods) {
if (!mod.content.hasClientAddon) continue;
mounts.push({
modId: mod.manifest.id,
mountFolder: addonMountFolderForMod(mod),
sourceDir: `${mod.rootDir}/client/addon`,
});
}
return mounts;
}
export function registerModAddonsInSettings(settingsRoot: BlkBlock, mountFolders: readonly string[]): void {
if (mountFolders.length === 0) return;
for (const blockName of ['addons', 'addons_no_check', 'addonsWithBasePath'] as const) {
const block = ensureBlock(settingsRoot, blockName);
const existing = new Set(
block.params
.filter((param) => param.name === 'folder' && param.value.type === 'string')
.map((param) => (param.value as { readonly type: 'string'; readonly value: string }).value.toLowerCase()),
);
for (const folder of mountFolders) {
if (existing.has(folder.toLowerCase())) continue;
appendParam(block, 'folder', { type: 'string', value: folder });
existing.add(folder.toLowerCase());
}
}
}
@@ -0,0 +1,541 @@
/**
* Deploy and cleanly roll back external mod assets (3D model addons, optional companion files,
* on-demand stock pack backups, and `config.blk` patches) in the game copy.
*
* Cross-drive zero-copy strategy (Option A):
* 1. Dedicated folders (`content/pkg_user/<modId>` and exclusive subdirectories under `client/files`,
* such as `UserSkins/<skin>`) use NTFS Directory Junctions — works across drives, needs no admin
* privileges, uses 0 extra bytes, and mounts/unmounts in ~1 ms.
* 2. Shared flat files (such as `sound/mod/*.bank`) try file symlink (works across drives when
* Windows Developer Mode is on) -> NTFS hardlink (same drive) -> size/mtime cached copy.
* 3. Player-owned native files (e.g. manually installed UserSkins/UserSights) are never overwritten;
* conflicts are reported and skipped.
* 4. Hard-linked stock files are unlinked before replacing so online client files are never mutated.
*/
import { createHash } from 'node:crypto';
import {
copyFileSync,
existsSync,
linkSync,
lstatSync,
mkdirSync,
readdirSync,
readFileSync,
rmdirSync,
rmSync,
statSync,
symlinkSync,
unlinkSync,
writeFileSync,
} from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { formatBlkText, parseBlkText } from '@wto/blk';
import {
applyBlkPatch,
parseBlkPatchDocument,
type DiscoveredMod,
type ModdableClientPack,
} from '@wto/mods';
import { addonMountFolderForMod } from './addon-register.ts';
export const MODS_STATE_FILE = join('wtoffline', 'mods-state.json');
export const CORE_BUILD_PACKS: ReadonlySet<ModdableClientPack> = new Set([
'char.vromfs.bin',
'aces.vromfs.bin',
'gui.vromfs.bin',
]);
export type DeployEntryKind = 'junction' | 'symlink' | 'hardlink' | 'copy';
export interface DeployedModEntry {
readonly modId: string;
/** Copy-relative path with forward slashes. */
readonly targetRelPath: string;
readonly sourcePath: string;
readonly kind: DeployEntryKind;
readonly size?: number;
readonly mtimeMs?: number;
}
export interface ModsDeployState {
readonly format: 1;
readonly entries: readonly DeployedModEntry[];
/** Optional stock packs backed up on demand under `wtoffline/stock/`. */
readonly optionalPacksModified: readonly ModdableClientPack[];
readonly configBlkModified: boolean;
readonly fingerprint?: string;
}
export interface ModDeployWarning {
readonly modId: string;
readonly targetRelPath: string;
readonly reason: string;
}
export interface ModExternalDeployResult {
readonly deployed: readonly DeployedModEntry[];
readonly warnings: readonly ModDeployWarning[];
readonly restoredOptionalPacks: readonly ModdableClientPack[];
readonly configBlkPatched: boolean;
}
export function readModsDeployState(copyFolder: string): ModsDeployState {
const path = join(copyFolder, MODS_STATE_FILE);
if (!existsSync(path)) {
return { format: 1, entries: [], optionalPacksModified: [], configBlkModified: false };
}
try {
const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<ModsDeployState>;
return {
format: 1,
entries: Array.isArray(parsed.entries) ? parsed.entries : [],
optionalPacksModified: Array.isArray(parsed.optionalPacksModified) ? parsed.optionalPacksModified : [],
configBlkModified: parsed.configBlkModified === true,
...(typeof parsed.fingerprint === 'string' ? { fingerprint: parsed.fingerprint } : {}),
};
} catch {
return { format: 1, entries: [], optionalPacksModified: [], configBlkModified: false };
}
}
export function writeModsDeployState(copyFolder: string, state: ModsDeployState): void {
const path = join(copyFolder, MODS_STATE_FILE);
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(state, null, 2), 'utf8');
}
/**
* Ensure stock copies exist under `<stockBackupFolder>` for any optional .vromfs.bin pack
* touched by enabled mods, then read and return their stock bytes for overlay building.
*/
export function prepareOptionalStockPacks(
copyFolder: string,
stockBackupFolder: string,
touchedPacks: readonly ModdableClientPack[],
): Partial<Record<ModdableClientPack, Uint8Array>> {
const result: Partial<Record<ModdableClientPack, Uint8Array>> = {};
for (const pack of touchedPacks) {
if (CORE_BUILD_PACKS.has(pack)) continue;
const backupPath = join(stockBackupFolder, ...pack.split('/'));
if (!existsSync(backupPath)) {
const livePath = join(copyFolder, ...pack.split('/'));
if (!existsSync(livePath)) {
throw new Error(`optional game pack "${pack}" does not exist in copy folder ${copyFolder}`);
}
mkdirSync(dirname(backupPath), { recursive: true });
copyFileSync(livePath, backupPath);
}
result[pack] = readFileSync(backupPath);
}
return result;
}
/**
* Synchronize external mod mounts (`client/addon/`, `client/files/`, `config.blk` patches)
* and restore any previously modified optional packs that are no longer touched.
*/
export function syncExternalModFiles(
copyFolder: string,
stockBackupFolder: string,
mods: readonly DiscoveredMod[],
optionalPacksInBuild: readonly ModdableClientPack[],
fingerprint?: string,
): ModExternalDeployResult {
const previous = readModsDeployState(copyFolder);
const warnings: ModDeployWarning[] = [];
// Plan desired external mounts for this launch.
const desired = planExternalEntries(mods);
const desiredByTarget = new Map(desired.map((item) => [item.targetRelPath.toLowerCase(), item]));
const previousByTarget = new Map(previous.entries.map((item) => [item.targetRelPath.toLowerCase(), item]));
// 1. Remove previous entries that are no longer wanted or changed source/mode.
for (const oldEntry of previous.entries) {
const key = oldEntry.targetRelPath.toLowerCase();
const next = desiredByTarget.get(key);
const keepUnchanged = next !== undefined
&& next.sourcePath === oldEntry.sourcePath
&& isEntryStillValid(copyFolder, oldEntry);
if (!keepUnchanged) {
removeDeployedEntry(copyFolder, oldEntry);
}
}
// 2. Restore optional packs that were modified previously but are no longer touched.
const activeOptionalSet = new Set(optionalPacksInBuild.filter((pack) => !CORE_BUILD_PACKS.has(pack)));
const restoredOptionalPacks: ModdableClientPack[] = [];
for (const oldPack of previous.optionalPacksModified) {
if (activeOptionalSet.has(oldPack)) continue;
const backupPath = join(stockBackupFolder, ...oldPack.split('/'));
const livePath = join(copyFolder, ...oldPack.split('/'));
if (existsSync(backupPath)) {
unlinkIfExists(livePath);
mkdirSync(dirname(livePath), { recursive: true });
copyFileSync(backupPath, livePath);
restoredOptionalPacks.push(oldPack);
}
}
// 3. Deploy desired mounts (skipping already-valid unchanged mounts and protecting native player files).
const deployed: DeployedModEntry[] = [];
for (const plan of desired) {
const key = plan.targetRelPath.toLowerCase();
const prev = previousByTarget.get(key);
if (prev && prev.sourcePath === plan.sourcePath && isEntryStillValid(copyFolder, prev)) {
deployed.push(prev);
continue;
}
const targetAbs = join(copyFolder, ...plan.targetRelPath.split('/'));
// Protect player-managed native files (e.g. manually installed UserSkins/UserSights).
if (existsSyncSafe(targetAbs) && !previousByTarget.has(key)) {
warnings.push({
modId: plan.modId,
targetRelPath: plan.targetRelPath,
reason: 'target already exists as a native/player file; skipped to avoid overwriting player content',
});
continue;
}
const mounted = mountPlannedEntry(copyFolder, plan);
deployed.push(mounted);
}
// 4. Apply or restore config.blk patches.
const configBlkPatched = syncConfigBlkPatches(copyFolder, stockBackupFolder, mods, previous.configBlkModified);
writeModsDeployState(copyFolder, {
format: 1,
entries: deployed,
optionalPacksModified: [...activeOptionalSet],
configBlkModified: configBlkPatched,
...(fingerprint !== undefined ? { fingerprint } : {}),
});
return { deployed, warnings, restoredOptionalPacks, configBlkPatched };
}
/** Compute a deterministic fingerprint of enabled mods and their source file stamps. */
export function computeModsBuildFingerprint(
mods: readonly DiscoveredMod[],
port: number,
extraSalt = '',
): string {
const hash = createHash('sha256');
hash.update(`port=${port};salt=${extraSalt}\n`);
for (const mod of mods) {
hash.update(`mod=${mod.manifest.id}@${mod.manifest.version}\n`);
const filesToStamp = [
...mod.content.packOperations.map((op) => op.sourceRelativePath),
...mod.content.guiPatchDirs,
...mod.content.exePatchDirs,
...(mod.content.configBlkPatch ? [mod.content.configBlkPatch] : []),
];
for (const rel of filesToStamp) {
const abs = join(mod.rootDir, ...rel.split('/'));
try {
const st = statSync(abs);
hash.update(`${rel}:${st.size}:${Math.trunc(st.mtimeMs)}\n`);
} catch {
hash.update(`${rel}:missing\n`);
}
}
}
return hash.digest('hex');
}
interface PlannedMount {
readonly modId: string;
readonly targetRelPath: string;
readonly sourcePath: string;
readonly isDirectory: boolean;
}
function planExternalEntries(mods: readonly DiscoveredMod[]): PlannedMount[] {
const plans: PlannedMount[] = [];
const seenTargets = new Map<string, number>();
const register = (plan: PlannedMount) => {
const key = plan.targetRelPath.toLowerCase();
const existingIdx = seenTargets.get(key);
if (existingIdx !== undefined) {
plans[existingIdx] = plan;
} else {
seenTargets.set(key, plans.length);
plans.push(plan);
}
};
// Addons are always mod-exclusive directories -> ideal for cross-drive Junctions.
for (const mod of mods) {
if (!mod.content.hasClientAddon) continue;
register({
modId: mod.manifest.id,
targetRelPath: addonMountFolderForMod(mod),
sourcePath: join(mod.rootDir, 'client', 'addon'),
isDirectory: true,
});
}
// Companion files under `client/files`: group exclusive leaf directories (e.g. `UserSkins/my_skin`)
// as cross-drive Junctions whenever only one mod touches that subdirectory.
const folderOwners = new Map<string, Set<string>>();
for (const mod of mods) {
for (const rel of mod.content.clientFiles) {
const topSub = exclusiveSubdirCandidate(rel);
if (!topSub) continue;
const key = topSub.toLowerCase();
let set = folderOwners.get(key);
if (!set) {
set = new Set();
folderOwners.set(key, set);
}
set.add(mod.manifest.id);
}
}
for (const mod of mods) {
const claimedDirs = new Set<string>();
for (const rel of mod.content.clientFiles) {
const topSub = exclusiveSubdirCandidate(rel);
if (topSub && folderOwners.get(topSub.toLowerCase())?.size === 1) {
const key = topSub.toLowerCase();
if (!claimedDirs.has(key)) {
claimedDirs.add(key);
register({
modId: mod.manifest.id,
targetRelPath: topSub,
sourcePath: join(mod.rootDir, 'client', 'files', ...topSub.split('/')),
isDirectory: true,
});
}
continue;
}
register({
modId: mod.manifest.id,
targetRelPath: rel,
sourcePath: join(mod.rootDir, 'client', 'files', ...rel.split('/')),
isDirectory: false,
});
}
}
return plans;
}
/**
* Return a safe exclusive subdirectory candidate (e.g. `UserSkins/foo`, `UserSights/bar`,
* `UserMissions/baz`) that can be mounted as one cross-drive Junction instead of linking
* every file inside it. Flat shared folders like `sound/mod/*.bank` return undefined.
*/
function exclusiveSubdirCandidate(relPath: string): string | undefined {
const parts = relPath.split('/');
if (parts.length < 3) return undefined;
const root = parts[0]!.toLowerCase();
if (root === 'userskins' || root === 'usersights' || root === 'usermissions') {
return `${parts[0]!}/${parts[1]!}`;
}
return undefined;
}
function mountPlannedEntry(copyFolder: string, plan: PlannedMount): DeployedModEntry {
const targetAbs = join(copyFolder, ...plan.targetRelPath.split('/'));
mkdirSync(dirname(targetAbs), { recursive: true });
if (plan.isDirectory) {
try {
symlinkSync(plan.sourcePath, targetAbs, 'junction');
return {
modId: plan.modId,
targetRelPath: plan.targetRelPath,
sourcePath: plan.sourcePath,
kind: 'junction',
};
} catch {
// Fallback for non-NTFS volumes (e.g. exFAT): incremental directory copy.
copyDirectoryIncremental(plan.sourcePath, targetAbs);
return {
modId: plan.modId,
targetRelPath: plan.targetRelPath,
sourcePath: plan.sourcePath,
kind: 'copy',
};
}
}
// Flat single file: try file symlink (cross-drive when Developer Mode is enabled),
// then same-drive NTFS hardlink, then cached copy.
unlinkIfExists(targetAbs);
try {
symlinkSync(plan.sourcePath, targetAbs, 'file');
return {
modId: plan.modId,
targetRelPath: plan.targetRelPath,
sourcePath: plan.sourcePath,
kind: 'symlink',
};
} catch { /* fall through */ }
try {
linkSync(plan.sourcePath, targetAbs);
return {
modId: plan.modId,
targetRelPath: plan.targetRelPath,
sourcePath: plan.sourcePath,
kind: 'hardlink',
};
} catch { /* fall through */ }
const st = statSync(plan.sourcePath);
copyFileSync(plan.sourcePath, targetAbs);
return {
modId: plan.modId,
targetRelPath: plan.targetRelPath,
sourcePath: plan.sourcePath,
kind: 'copy',
size: st.size,
mtimeMs: st.mtimeMs,
};
}
function isEntryStillValid(copyFolder: string, entry: DeployedModEntry): boolean {
const targetAbs = join(copyFolder, ...entry.targetRelPath.split('/'));
if (!existsSyncSafe(targetAbs)) return false;
if (entry.kind === 'junction' || entry.kind === 'symlink') {
try {
return lstatSync(targetAbs).isSymbolicLink() && existsSync(entry.sourcePath);
} catch {
return false;
}
}
if (entry.kind === 'hardlink') {
try {
const a = statSync(targetAbs);
const b = statSync(entry.sourcePath);
return a.ino !== 0 && a.ino === b.ino && a.dev === b.dev;
} catch {
return false;
}
}
// Cached copy check.
if (entry.size !== undefined && entry.mtimeMs !== undefined) {
try {
const src = statSync(entry.sourcePath);
const dst = statSync(targetAbs);
return src.size === entry.size && Math.abs(src.mtimeMs - entry.mtimeMs) < 2 && dst.size === src.size;
} catch {
return false;
}
}
return false;
}
function removeDeployedEntry(copyFolder: string, entry: DeployedModEntry): void {
const targetAbs = join(copyFolder, ...entry.targetRelPath.split('/'));
if (!existsSyncSafe(targetAbs)) return;
try {
const stat = lstatSync(targetAbs);
if (entry.kind === 'junction' || stat.isSymbolicLink()) {
// Remove only the reparse point / symlink, never descending into the source mod folder.
try {
unlinkSync(targetAbs);
} catch {
rmdirSync(targetAbs);
}
} else if (stat.isDirectory()) {
rmSync(targetAbs, { recursive: true, force: true });
} else {
unlinkSync(targetAbs);
}
} catch { /* ignore */ }
pruneEmptyParents(dirname(targetAbs), copyFolder);
}
function copyDirectoryIncremental(srcDir: string, dstDir: string): void {
mkdirSync(dstDir, { recursive: true });
for (const entry of readdirSync(srcDir, { withFileTypes: true })) {
const src = join(srcDir, entry.name);
const dst = join(dstDir, entry.name);
if (entry.isDirectory()) {
copyDirectoryIncremental(src, dst);
} else if (entry.isFile()) {
const st = statSync(src);
let same = false;
try {
const dstStat = statSync(dst);
same = dstStat.size === st.size && Math.abs(dstStat.mtimeMs - st.mtimeMs) < 2;
} catch { /* missing */ }
if (!same) {
unlinkIfExists(dst);
copyFileSync(src, dst);
}
}
}
}
function syncConfigBlkPatches(
copyFolder: string,
stockBackupFolder: string,
mods: readonly DiscoveredMod[],
previouslyModified: boolean,
): boolean {
const patchingMods = mods.filter((mod) => mod.content.configBlkPatch !== undefined);
const liveConfig = join(copyFolder, 'config.blk');
const backupConfig = join(stockBackupFolder, 'config.blk');
if (patchingMods.length === 0) {
if (previouslyModified && existsSync(backupConfig)) {
unlinkIfExists(liveConfig);
copyFileSync(backupConfig, liveConfig);
}
return false;
}
if (!existsSync(backupConfig) && existsSync(liveConfig)) {
mkdirSync(dirname(backupConfig), { recursive: true });
copyFileSync(liveConfig, backupConfig);
}
const sourceText = existsSync(backupConfig)
? readFileSync(backupConfig, 'utf8')
: existsSync(liveConfig) ? readFileSync(liveConfig, 'utf8') : '';
const root = parseBlkText(sourceText);
for (const mod of patchingMods) {
const patchPath = join(mod.rootDir, ...mod.content.configBlkPatch!.split('/'));
const patch = parseBlkPatchDocument(readFileSync(patchPath, 'utf8'), `mod "${mod.manifest.id}" config.blk patch`);
applyBlkPatch(root, patch, `mod "${mod.manifest.id}" config.blk patch`);
}
unlinkIfExists(liveConfig);
writeFileSync(liveConfig, formatBlkText(root), 'utf8');
return true;
}
function pruneEmptyParents(dir: string, stopAt: string): void {
let current = dir;
while (relative(stopAt, current) !== '' && !relative(stopAt, current).startsWith('..')) {
try {
if (readdirSync(current).length > 0) return;
rmdirSync(current);
current = dirname(current);
} catch {
return;
}
}
}
function existsSyncSafe(path: string): boolean {
try {
lstatSync(path);
return true;
} catch {
return false;
}
}
function unlinkIfExists(path: string): void {
if (!existsSyncSafe(path)) return;
try {
unlinkSync(path);
} catch { /* ignore */ }
}
+112
View File
@@ -0,0 +1,112 @@
/**
* Apply mod GUI script patches (`client/gui-patches/<name>/patch.jsonc`) on top of an already
* core-patched gui.vromfs.bin archive. Failures are collected per mod rather than breaking core
* offline GUI patches.
*/
import { join } from 'node:path';
import { chooseVariant, PatchError, type PatchFailure } from '@wto/exepatch';
import type { DiscoveredMod } from '@wto/mods';
import { getFile, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs';
import { loadGuiPatches, type GuiScriptVariant } from '../gui-patch-definition.ts';
import type { LocalEndpoint } from '../network/local-endpoint.ts';
const ENDPOINT_PLACEHOLDER = '{{LOCAL_ENDPOINT}}';
export interface ModGuiPatchResult {
readonly pack: Uint8Array;
readonly applied: readonly { readonly modId: string; readonly patchId: string }[];
readonly failures: readonly (PatchFailure & { readonly modId: string })[];
}
class ModGuiPatchMismatch extends PatchError {
override name = 'ModGuiPatchMismatch';
}
export function applyModGuiPatches(
baseGuiPack: Uint8Array,
endpoint: LocalEndpoint,
mods: readonly DiscoveredMod[],
): ModGuiPatchResult {
const modsWithGui = mods.filter((mod) => mod.content.guiPatchDirs.length > 0);
if (modsWithGui.length === 0) {
return { pack: baseGuiPack, applied: [], failures: [] };
}
const archive = readArchive(baseGuiPack);
const hostPortText = `${endpoint.host}:${endpoint.port}`;
const applied: { readonly modId: string; readonly patchId: string }[] = [];
const failures: (PatchFailure & { readonly modId: string })[] = [];
for (const mod of modsWithGui) {
const patchesRoot = join(mod.rootDir, 'client', 'gui-patches');
let patches;
try {
patches = loadGuiPatches(patchesRoot);
} catch (error) {
failures.push({
modId: mod.manifest.id,
patchId: `${mod.manifest.id}:gui-patches`,
features: [],
reason: error instanceof Error ? error.message : String(error),
});
continue;
}
for (const patch of patches) {
try {
const chosen = chooseVariant(patch.variants, (variant) => patchedScript(archive, variant, hostPortText));
putFile(archive, chosen.variant.file, Buffer.from(chosen.value, 'utf8'));
applied.push({ modId: mod.manifest.id, patchId: patch.id });
} catch (error) {
if (!(error instanceof PatchError)) throw error;
failures.push({
modId: mod.manifest.id,
patchId: patch.id,
features: patch.features,
reason: error.message,
});
}
}
}
return { pack: writeArchive(archive), applied, failures };
}
function patchedScript(archive: Archive, variant: GuiScriptVariant, hostPortText: string): string {
if (!archive.files.has(variant.file)) throw new ModGuiPatchMismatch(`the data pack has no script ${variant.file}`);
let current = Buffer.from(getFile(archive, variant.file)).toString('utf8');
const newline = current.includes('\r\n') ? '\r\n' : '\n';
for (const [index, edit] of variant.edits.entries()) {
const replace = edit.replace.replaceAll('\n', newline).replaceAll(ENDPOINT_PLACEHOLDER, hostPortText);
current = replaceUnique(current, edit.find, replace, `edit ${index + 1} in ${variant.file}`);
}
return current;
}
function replaceUnique(text: string, find: string, replace: string, label: string): string {
const { normalized, original } = withoutCarriageReturns(text);
const first = normalized.indexOf(find);
if (first === -1) throw new ModGuiPatchMismatch(`${label}: target text not found`);
if (normalized.indexOf(find, first + find.length) !== -1) {
throw new ModGuiPatchMismatch(`${label}: target text appears more than once`);
}
return text.slice(0, original[first]!) + replace + text.slice(original[first + find.length]!);
}
function withoutCarriageReturns(text: string): { readonly normalized: string; readonly original: readonly number[] } {
const kept: string[] = [];
const original: number[] = [];
let index = 0;
while (index < text.length) {
original.push(index);
if (text[index] === '\r' && text[index + 1] === '\n') {
kept.push('\n');
index += 2;
} else {
kept.push(text[index]!);
index += 1;
}
}
original.push(text.length);
return { normalized: kept.join(''), original };
}
+103
View File
@@ -0,0 +1,103 @@
/**
* Apply ordered mod pack operations (`blk-patch`, `csv-patch`, or added/replaced files)
* onto an in-memory .vromfs.bin archive without modifying stock backups.
*/
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { decodeBlk, encodeBlk, isBinaryBlk, parseBlkText, parseSharedNameMap } from '@wto/blk';
import {
applyBlkPatch,
mergeLocalizationCsv,
parseBlkPatchDocument,
type DiscoveredMod,
type ModdableClientPack,
} from '@wto/mods';
import { getFile, NAME_MAP_PATH, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs';
export interface PackOverlayReport {
readonly pack: ModdableClientPack;
readonly operationsApplied: number;
}
export function applyModPackOverlays(
basePack: Uint8Array,
packName: ModdableClientPack,
mods: readonly DiscoveredMod[],
): { readonly pack: Uint8Array; readonly report: PackOverlayReport } {
const relevant = mods.flatMap((mod) =>
mod.content.packOperations
.filter((op) => op.pack === packName)
.map((op) => ({ mod, op })),
);
if (relevant.length === 0) {
return { pack: basePack, report: { pack: packName, operationsApplied: 0 } };
}
const archive = readArchive(basePack);
const dictionary = findDictionary(archive);
const names = archive.files.has(NAME_MAP_PATH)
? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names
: [];
for (const { mod, op } of relevant) {
const sourcePath = join(mod.rootDir, ...op.sourceRelativePath.split('/'));
const where = `mod "${mod.manifest.id}" (${op.sourceRelativePath})`;
switch (op.action) {
case 'blk-patch': {
const resolvedPath = findArchivePath(archive, op.targetPath);
if (!resolvedPath) {
throw new Error(`${where}: target BLK "${op.targetPath}" not found in ${packName}`);
}
const raw = getFile(archive, resolvedPath);
const root = isBinaryBlk(raw)
? decodeBlk(raw, { names, dictionary })
: parseBlkText(Buffer.from(raw).toString('utf8'));
const patch = parseBlkPatchDocument(readFileSync(sourcePath, 'utf8'), where);
applyBlkPatch(root, patch, where);
putFile(archive, resolvedPath, encodeBlk(root));
break;
}
case 'csv-patch': {
const resolvedPath = findArchivePath(archive, op.targetPath);
if (!resolvedPath) {
throw new Error(`${where}: target CSV "${op.targetPath}" not found in ${packName}`);
}
const baseText = Buffer.from(getFile(archive, resolvedPath)).toString('utf8');
const patchText = readFileSync(sourcePath, 'utf8');
const merged = mergeLocalizationCsv(baseText, patchText);
putFile(archive, resolvedPath, Buffer.from(merged, 'utf8'));
break;
}
case 'file': {
const bytes = readFileSync(sourcePath);
const resolvedPath = findArchivePath(archive, op.targetPath) ?? op.targetPath;
if (op.targetPath.toLowerCase().endsWith('.blk') && !isBinaryBlk(bytes)) {
const parsed = parseBlkText(bytes.toString('utf8'));
putFile(archive, resolvedPath, encodeBlk(parsed));
} else {
putFile(archive, resolvedPath, bytes);
}
break;
}
}
}
return {
pack: writeArchive(archive),
report: { pack: packName, operationsApplied: relevant.length },
};
}
function findArchivePath(archive: Archive, wanted: string): string | undefined {
if (archive.files.has(wanted)) return wanted;
const lower = wanted.toLowerCase();
for (const key of archive.files.keys()) {
if (key.toLowerCase() === lower) return key;
}
return undefined;
}
function findDictionary(archive: Archive): Uint8Array | undefined {
const dictionaries = [...archive.files.keys()].filter((path) => path.endsWith('.dict'));
return dictionaries.length === 1 ? archive.files.get(dictionaries[0]!) : undefined;
}