refactor(patches)!: migrate definitions to JSONC and script fragments

Patch definitions under exe-patches/ and gui-patches/ move from
patch.json/locate.json to patch.jsonc/locate.jsonc. Each file now holds
only the data needed to apply the patch plus a short English comment
stating what it changes, why the local service cannot provide it, and
what happens without it. Every definition records the game versions it
was verified on (verified_on, required).

GUI patches keep their stock text and replacement in find.nut and
replace.nut next to patch.jsonc instead of escaped JSON strings, so the
script edits are readable, diffable and can carry Quirrel comments.
Matching treats CRLF and LF as the same line break because stock
scripts mix both; only the matched span is rewritten.

Loaders on both sides (packages/build, packages/exepatch, wtotools)
reject unknown keys so analysis text cannot creep back into the data.
JSONC parsing moves into a shared @wto/jsonc package; the build now
parses tuning/store.jsonc instead of scanning it with a regex.

Verified: npm run typecheck; check-patches (10/10 ready on 2.61.0.37);
check-gui (33 patches, 24 scripts compile); the TypeScript and Python
appliers produce identical scripts, byte-identical to the previous
definitions except one stock script with mixed line endings.

The 15 battle patches are migrated mechanically and still carry the
pending-review comment; they are rewritten by the LocalMP review.

BREAKING CHANGE: Patch loaders require JSONC definitions. Migrate patch.json and locate.json and move embedded GUI edits to separate Quirrel files.
This commit is contained in:
N0VAN0M4LY committed 2026-11-28 03:24:12 +08:00
1 parent b260d2899e
commit db981ab834
185 files changed
+2676 -1487

No files matched your search

+42 -48
View File
@@ -1,47 +1,23 @@
/**
* Rebuild gui.vromfs.bin by applying declarative script modification records from `gui-patches/`
*.
* Rebuild gui.vromfs.bin by applying the script patch definitions in `gui-patches/`
* (implementation notes, format in gui-patch-definition.ts).
*
* Just like `exe-patches/`, every GUI script modification lives in its own folder under
* `gui-patches/` with a `patch.json` documenting the requirement, why the local service cannot
* handle it alone, lighter options ruled out, and the exact unique text to replace.
* Every edit must find its stock text exactly once in the current script; anything else
* refuses the whole build rather than writing a half-patched archive.
*/
import { readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { getFile, putFile, readArchive, writeArchive } from '@wto/vromfs';
import { loadGuiPatches, type GuiScriptPatch } from './gui-patch-definition.ts';
import type { LocalEndpoint } from './network/local-endpoint.ts';
const DEFAULT_GUI_PATCHES_DIR = fileURLToPath(new URL('../../../gui-patches', import.meta.url));
const ENDPOINT_PLACEHOLDER = '{{LOCAL_ENDPOINT}}';
export interface GuiScriptPatch {
readonly id: string;
readonly title: string;
readonly file: string;
readonly features: readonly string[];
readonly edit: {
readonly find: string;
readonly replace: string;
};
}
export interface GuiPackResult {
readonly pack: Uint8Array;
readonly applied: readonly GuiScriptPatch[];
}
export function loadGuiPatches(patchesFolder: string = DEFAULT_GUI_PATCHES_DIR): readonly GuiScriptPatch[] {
const files = collectPatchJsonPaths(patchesFolder).sort();
return files.map((filePath) => {
const raw = JSON.parse(readFileSync(filePath, 'utf8')) as GuiScriptPatch;
if (!raw.id || !raw.file || !raw.edit?.find || typeof raw.edit.replace !== 'string') {
throw new Error(`${filePath}: invalid GUI patch record`);
}
return raw;
});
}
export function rebuildGuiPack(
stockPack: Uint8Array,
endpoint: LocalEndpoint,
@@ -52,17 +28,13 @@ export function rebuildGuiPack(
const hostPortText = `${endpoint.host}:${endpoint.port}`;
for (const patch of patches) {
const current = Buffer.from(getFile(archive, patch.file)).toString('utf8');
const firstIndex = current.indexOf(patch.edit.find);
if (firstIndex === -1) {
throw new Error(`GUI patch ${patch.id}: target snippet not found in ${patch.file}; refusing to write`);
let current = Buffer.from(getFile(archive, patch.file)).toString('utf8');
const newline = current.includes('\r\n') ? '\r\n' : '\n';
for (const [index, edit] of patch.edits.entries()) {
const replace = edit.replace.replaceAll('\n', newline).replaceAll(ENDPOINT_PLACEHOLDER, hostPortText);
current = replaceUnique(current, edit.find, replace, `GUI patch ${patch.id} edit ${index + 1} in ${patch.file}`);
}
if (current.indexOf(patch.edit.find, firstIndex + patch.edit.find.length) !== -1) {
throw new Error(`GUI patch ${patch.id}: target snippet appears more than once in ${patch.file}; refusing to write`);
}
const replacement = patch.edit.replace.replaceAll(ENDPOINT_PLACEHOLDER, hostPortText);
const updated = current.slice(0, firstIndex) + replacement + current.slice(firstIndex + patch.edit.find.length);
putFile(archive, patch.file, Buffer.from(updated, 'utf8'));
putFile(archive, patch.file, Buffer.from(current, 'utf8'));
}
return {
@@ -71,15 +43,37 @@ export function rebuildGuiPack(
};
}
function collectPatchJsonPaths(dir: string): string[] {
const out: string[] = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
out.push(...collectPatchJsonPaths(full));
} else if (entry.isFile() && entry.name === 'patch.json') {
out.push(full);
/**
* Replace the single occurrence of `find` (written with `\n` line endings) in `text`, treating
* `\r\n` and `\n` in the script as the same line break; stock scripts mix both. Only the matched
* span changes, every other byte of the script is kept.
*/
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 Error(`${label}: stock text not found; refusing to write`);
if (normalized.indexOf(find, first + find.length) !== -1) throw new Error(`${label}: stock text appears more than once; refusing to write`);
return text.slice(0, original[first]!) + replace + text.slice(original[first + find.length]!);
}
/**
* `text` with `\r\n` turned into `\n`, and for every normalized index the index in `text` where
* that character's original sequence starts (a `\r\n` maps to its `\r`).
*/
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;
}
}
return out;
original.push(text.length);
return { normalized: kept.join(''), original };
}
+140
View File
@@ -0,0 +1,140 @@
/**
* GUI script patch definitions as stored on disk, one folder per change under
* `gui-patches/<domain>/<name>/`:
*
* patch.jsonc id, title, target script, features, the game versions it was verified on,
* and the list of edits; comments explain what the change does and why the
* local service cannot provide it
* <name>.nut the edit fragments named by `edits` (stock text to find, text to put there)
*
* Fragment files hold the exact script text followed by one terminating newline, which is not
* part of the fragment. Line endings are normalised to `\n` here; applying matches regardless of
* the script's line endings (stock scripts mix `\r\n` and `\n`), so fragments survive editors
* and git newline conversion.
*/
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { parseJsonc } from '@wto/jsonc';
const PATCH_FILE = 'patch.jsonc';
const ALLOWED_KEYS = new Set(['id', 'title', 'file', 'features', 'verified_on', 'edits']);
export interface GuiScriptEdit {
/** Stock text that must occur exactly once in the target script, with `\n` line endings. */
readonly find: string;
/** Text written in its place, with `\n` line endings. */
readonly replace: string;
}
export interface GuiScriptPatch {
readonly id: string;
readonly title: string;
/** Script path inside gui.vromfs.bin. */
readonly file: string;
readonly features: readonly string[];
readonly verifiedOn: readonly string[];
readonly edits: readonly GuiScriptEdit[];
readonly directory: string;
}
/** Every definition under `root`, sorted by id. */
export function loadGuiPatches(root: string): readonly GuiScriptPatch[] {
const patches = findDefinitionDirectories(root).map(readDefinition);
rejectDuplicateIds(patches);
return patches.sort((left, right) => left.id.localeCompare(right.id));
}
function findDefinitionDirectories(root: string): string[] {
const found: string[] = [];
for (const entry of readdirSync(root, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const directory = join(root, entry.name);
if (isFile(join(directory, PATCH_FILE))) found.push(directory);
else found.push(...findDefinitionDirectories(directory));
}
return found;
}
function readDefinition(directory: string): GuiScriptPatch {
const where = join(directory, PATCH_FILE);
const raw = readObject(where);
const unknown = Object.keys(raw).filter((key) => !ALLOWED_KEYS.has(key));
if (unknown.length) {
throw new Error(`${where}: unknown key(s) ${unknown.join(', ')}; explanations belong in comments or the patch notes`);
}
return {
id: requiredString(raw.id, where, 'id'),
title: requiredString(raw.title, where, 'title'),
file: requiredString(raw.file, where, 'file'),
features: stringList(raw.features, where, 'features'),
verifiedOn: nonEmptyStringList(raw.verified_on, where, 'verified_on'),
edits: readEdits(raw.edits, directory, where),
directory,
};
}
function readEdits(value: unknown, directory: string, where: string): GuiScriptEdit[] {
if (!Array.isArray(value) || value.length === 0) throw new Error(`${where}: "edits" must be a non-empty list`);
return value.map((item, index) => {
if (!item || typeof item !== 'object') throw new Error(`${where}: edits[${index}] must be an object`);
const edit = item as Record<string, unknown>;
const find = readFragment(directory, requiredString(edit.find, where, `edits[${index}].find`));
if (find === '') throw new Error(`${where}: edits[${index}].find is empty`);
const replace = readFragment(directory, requiredString(edit.replace, where, `edits[${index}].replace`));
return { find, replace };
});
}
/** Fragment text with `\n` line endings and the file's terminating newline removed. */
export function readFragment(directory: string, name: string): string {
if (name.includes('/') || name.includes('\\')) throw new Error(`${directory}: fragment "${name}" must be a file in the patch folder`);
const text = readFileSync(join(directory, name), 'utf8').replace(/^/, '').replace(/\r\n/g, '\n');
return text.endsWith('\n') ? text.slice(0, -1) : text;
}
function readObject(path: string): Record<string, unknown> {
let data: unknown;
try {
data = parseJsonc(readFileSync(path, 'utf8'));
} catch (error) {
throw new Error(`${path}: ${(error as Error).message}`);
}
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error(`${path}: expected an object`);
return data as Record<string, unknown>;
}
function requiredString(value: unknown, where: string, key: string): string {
if (typeof value !== 'string' || value === '') throw new Error(`${where}: "${key}" must be a non-empty string`);
return value;
}
function stringList(value: unknown, where: string, key: string): string[] {
if (value === undefined) return [];
if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) {
throw new Error(`${where}: "${key}" must be a list of strings`);
}
return value;
}
function nonEmptyStringList(value: unknown, where: string, key: string): string[] {
const list = stringList(value, where, key);
if (list.length === 0) throw new Error(`${where}: "${key}" must name at least one game version`);
return list;
}
function rejectDuplicateIds(patches: readonly GuiScriptPatch[]): void {
const seen = new Map<string, string>();
for (const patch of patches) {
const previous = seen.get(patch.id);
if (previous) throw new Error(`two GUI patches use id "${patch.id}": ${previous} and ${patch.directory}`);
seen.set(patch.id, patch.directory);
}
}
function isFile(path: string): boolean {
try {
return statSync(path).isFile();
} catch {
return false;
}
}
+2 -1
View File
@@ -6,7 +6,8 @@
export { NETWORK_CONFIG_PATH, rebuildCharPack, type CharPackResult } from './char-pack.ts';
export { patchExecutable, type ExecutableResult } from './executable.ts';
export { assertWritableCopy, GAME_FILES } from './game-copy.ts';
export { loadGuiPatches, rebuildGuiPack, type GuiPackResult, type GuiScriptPatch } from './gui-pack.ts';
export { rebuildGuiPack, type GuiPackResult } from './gui-pack.ts';
export { loadGuiPatches, type GuiScriptEdit, type GuiScriptPatch } from './gui-patch-definition.ts';
export { ENGINE_SETTINGS_PATH, EXTRA_STORE_BUNDLE_GUID_MAP, EXTRA_STORE_BUNDLE_GUIDS, rebuildMainPack, type MainPackResult } from './main-pack.ts';
export { redirectAddresses, type AddressChange } from './network/address-rewrite.ts';
export { hostPort, localEndpoint, localUrl, type LocalEndpoint } from './network/local-endpoint.ts';
+12 -5
View File
@@ -10,6 +10,7 @@
*/
import { existsSync, readFileSync } from 'node:fs';
import { singleVehiclePackId, stableGuid, type BlkBlock } from '@wto/blk';
import { parseJsonc } from '@wto/jsonc';
import { readPackBlk } from '../pack-edit.ts';
export const WPCOST_PATH = 'config/wpcost.blk';
@@ -25,11 +26,17 @@ function giftVehicles(wpcost: BlkBlock): string[] {
return wpcost.blocks.filter((unit) => unit.params.some((param) => param.name === 'gift')).map((unit) => unit.name);
}
/** Pack ids of `multiVehiclePacks` in tuning/store.jsonc (a plain scan; the file is JSON with comments). */
/** Pack ids of `vehiclePacks.multiVehiclePacks` in tuning/store.jsonc. */
function multiVehiclePackIds(storeTuningPath: string): string[] {
if (!existsSync(storeTuningPath)) return [];
const text = readFileSync(storeTuningPath, 'utf8');
const start = text.indexOf('"multiVehiclePacks"');
if (start < 0) return [];
return [...text.slice(start).matchAll(/"id"\s*:\s*"([^"]+)"/g)].map((match) => match[1]!);
const tuning = parseJsonc(readFileSync(storeTuningPath, 'utf8')) as {
readonly vehiclePacks?: { readonly multiVehiclePacks?: ReadonlyArray<{ readonly id?: unknown }> };
};
const packs = tuning.vehiclePacks?.multiVehiclePacks ?? [];
return packs.map((pack, index) => {
if (typeof pack.id !== 'string' || pack.id === '') {
throw new Error(`${storeTuningPath}: vehiclePacks.multiVehiclePacks[${index}].id must be a non-empty string`);
}
return pack.id;
});
}