/** * Patch definitions as stored on disk, one directory per change to the program's behaviour, * under exe-patches///: * * patch.jsonc id, title, features, required patches, the game versions it was verified * on, and the bytes to write; comments explain the change and why the local * service cannot provide it * locate.jsonc how to find the site * * Unknown keys are rejected so that explanations stay in comments and in the patch notes * instead of growing into data fields. */ import { readdirSync, readFileSync, statSync } from 'node:fs'; import { join } from 'node:path'; import { parseJsonc } from '@wto/jsonc'; import { DefinitionError } from './errors.ts'; const PATCH_FILE = 'patch.jsonc'; const LOCATE_FILE = 'locate.jsonc'; const PATCH_KEYS = new Set(['id', 'title', 'features', 'requires', 'verified_on', 'edit']); const EDIT_KEYS = new Set(['offset', 'asm', 'data', 'bytes', 'expect_original']); const LOCATE_KEYS = new Set(['method', 'section', 'pattern']); export interface PatchEdit { /** Distance from the located site to the first byte written. */ readonly offset: number; readonly payload: Uint8Array; readonly expectOriginal: Uint8Array; } export interface LocateSpec { readonly method: string; readonly [key: string]: unknown; } export interface PatchDefinition { readonly id: string; readonly title: string; readonly features: readonly string[]; readonly requires: readonly string[]; readonly verifiedOn: readonly string[]; readonly edit: PatchEdit; readonly locate: LocateSpec; readonly directory: string; } /** Every definition under `root`, sorted by id. */ export function loadPatches(root: string): PatchDefinition[] { const definitions = findDefinitionDirectories(root).map(readDefinition); rejectDuplicateIds(definitions); rejectUnknownRequirements(definitions); return definitions.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): PatchDefinition { const where = join(directory, PATCH_FILE); const locateWhere = join(directory, LOCATE_FILE); const patch = readJson(where); const locate = readJson(locateWhere); rejectUnknownKeys(patch, PATCH_KEYS, where); rejectUnknownKeys(locate, LOCATE_KEYS, locateWhere); if (typeof patch.id !== 'string' || typeof patch.title !== 'string') throw new DefinitionError(`${where}: needs string "id" and "title"`); if (typeof locate.method !== 'string') throw new DefinitionError(`${locateWhere}: needs a string "method"`); const verifiedOn = stringList(patch.verified_on, where, 'verified_on'); if (verifiedOn.length === 0) throw new DefinitionError(`${where}: "verified_on" must name at least one game version`); return { id: patch.id, title: patch.title, features: stringList(patch.features, where, 'features'), requires: stringList(patch.requires, where, 'requires'), verifiedOn, edit: readEdit(patch.edit, where), locate: locate as LocateSpec, directory, }; } function readEdit(raw: unknown, where: string): PatchEdit { if (!raw || typeof raw !== 'object') throw new DefinitionError(`${where}: "edit" must be an object`); const edit = raw as Record; rejectUnknownKeys(edit, EDIT_KEYS, `${where} edit`); const payload = hexBytes(edit.bytes, where, 'bytes'); const expectOriginal = hexBytes(edit.expect_original, where, 'expect_original'); if (payload.length !== expectOriginal.length) { throw new DefinitionError(`${where}: bytes is ${payload.length} bytes but expect_original is ${expectOriginal.length}`); } const offset = edit.offset ?? 0; if (typeof offset !== 'number' || !Number.isInteger(offset)) throw new DefinitionError(`${where}: edit.offset must be an integer`); return { offset, payload, expectOriginal }; } function hexBytes(value: unknown, where: string, key: string): Uint8Array { if (typeof value !== 'string' || !/^([0-9a-fA-F]{2})*$/.test(value)) throw new DefinitionError(`${where}: edit.${key} must be a hex string`); return Buffer.from(value, 'hex'); } 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 DefinitionError(`${where}: "${key}" must be a list of strings`); return value; } function readJson(path: string): Record { let data: unknown; try { data = parseJsonc(readFileSync(path, 'utf-8')); } catch (error) { throw new DefinitionError(`${path}: ${(error as Error).message}`); } if (!data || typeof data !== 'object' || Array.isArray(data)) throw new DefinitionError(`${path}: expected a JSON object`); return data as Record; } function rejectUnknownKeys(object: Record, allowed: ReadonlySet, where: string): void { const unknown = Object.keys(object).filter((key) => !allowed.has(key)); if (unknown.length) { throw new DefinitionError(`${where}: unknown key(s) ${unknown.join(', ')}; explanations belong in comments or the patch notes`); } } function isFile(path: string): boolean { try { return statSync(path).isFile(); } catch { return false; } } function rejectDuplicateIds(definitions: readonly PatchDefinition[]): void { const seen = new Map(); for (const definition of definitions) { const previous = seen.get(definition.id); if (previous) throw new DefinitionError(`two definitions use id "${definition.id}": ${previous} and ${definition.directory}`); seen.set(definition.id, definition.directory); } } function rejectUnknownRequirements(definitions: readonly PatchDefinition[]): void { const known = new Set(definitions.map((definition) => definition.id)); for (const definition of definitions) { const unknown = definition.requires.filter((id) => !known.has(id)); if (unknown.length) throw new DefinitionError(`${definition.id} requires unknown patch(es): ${unknown.join(', ')}`); } }