// The only module in this package allowed to know about EU4's on-disk byte // formats. Everything else (lexer, tests) works with decoded JS strings and // must never touch bytes directly. // // EU4's legacy Chinese localisation encoding stores double-byte characters // as three-character escape sequences inside an otherwise Latin-1-shaped // byte stream. That transcoding is implemented by the vendored codec at // ../../eu4_han_convert/src/codec.js (a local package under tools/, not the // global npm install) — this module wraps it and adds the file-level BOM / // CP1252 handling that existing scripts in this repo (tools/*.mjs) already // do by convention, so behavior stays consistent across the toolchain. import { readFile, writeFile } from 'node:fs/promises'; import { decodeText, encodeText } from '../../eu4_han_convert/src/codec.js'; const UTF8_BOM = Buffer.from([0xef, 0xbb, 0xbf]); // CP1252 high-byte table used throughout this project's tools. Bytes 0x80-0x9f // that aren't listed here (0x81, 0x8d, 0x8f, 0x90, 0x9d) are unassigned in // CP1252 and pass through as their own code point, same as every other byte. const CP1252_TO_UNICODE = new Map([ [0x80, 0x20ac], [0x82, 0x201a], [0x83, 0x0192], [0x84, 0x201e], [0x85, 0x2026], [0x86, 0x2020], [0x87, 0x2021], [0x88, 0x02c6], [0x89, 0x2030], [0x8a, 0x0160], [0x8b, 0x2039], [0x8c, 0x0152], [0x8e, 0x017d], [0x91, 0x2018], [0x92, 0x2019], [0x93, 0x201c], [0x94, 0x201d], [0x95, 0x2022], [0x96, 0x2013], [0x97, 0x2014], [0x98, 0x02dc], [0x99, 0x2122], [0x9a, 0x0161], [0x9b, 0x203a], [0x9c, 0x0153], [0x9e, 0x017e], [0x9f, 0x0178], ]); const UNICODE_TO_CP1252 = new Map( [...CP1252_TO_UNICODE].map(([byte, codePoint]) => [codePoint, byte]), ); /** * Read an EU4 game text file: strip a UTF-8 BOM if present, try a strict * UTF-8 decode, and fall back to a byte-preserving CP1252 map on failure — * then run the vendored double-byte decoder over the result. * * @param {string} path * @returns {Promise<{ text: string, bom: boolean, encoding: 'utf-8' | 'cp1252' }>} */ export async function readGameText(path) { const bytes = await readFile(path); const bom = bytes.subarray(0, UTF8_BOM.length).equals(UTF8_BOM); const raw = bom ? bytes.subarray(UTF8_BOM.length) : bytes; try { const decoded = new TextDecoder('utf-8', { fatal: true }).decode(raw); return { text: decodeText(decoded), bom, encoding: 'utf-8' }; } catch { const bytePreserving = Array.from( raw, (byte) => String.fromCodePoint(CP1252_TO_UNICODE.get(byte) ?? byte), ).join(''); return { text: decodeText(bytePreserving), bom, encoding: 'cp1252' }; } } // encodeText (vendored) iterates its input with `for...of`, i.e. by Unicode // code point. decodeText can legitimately emit two independent BMP code // points in sequence (each representing one half of a double-byte escape), // and when those two ordinary strings are concatenated, JS's code-point // iteration silently recombines them into a single astral character if they // happen to form a valid UTF-16 surrogate pair (this really happened with // U+20C18). encodeText then sees a code point > 0xFFFF and throws, even // though the input is entirely valid game text. // // Fix: split the text into UTF-16 *code units* before encoding, so each // call to encodeText only ever sees one unit at a time — nothing left to // recombine into an astral character. function encodeTextByCodeUnit(text, options) { let result = ''; for (let i = 0; i < text.length; i += 1) { result += encodeText(text[i], options); } return result; } function firstDivergence(a, b) { const length = Math.min(a.length, b.length); let i = 0; while (i < length && a[i] === b[i]) i += 1; return i; } /** * Write an EU4 game text file: run the vendored double-byte encoder, map the * result back through the inverse CP1252 table to raw bytes, and re-attach * the BOM only if the original file had one. Then re-reads the file and * throws if it did not round-trip exactly — this module is the single point * where a silent mis-encode could corrupt game text, so it verifies itself * on every write. * * @param {string} path * @param {string} text * @param {{ bom?: boolean }} [meta] - typically the `meta` returned by readGameText */ export async function writeGameText(path, text, meta = {}) { const encoded = encodeTextByCodeUnit(text, { profile: 'legacy' }); const bytes = Buffer.from(Array.from(encoded, (character) => { const codePoint = character.codePointAt(0); const byte = UNICODE_TO_CP1252.get(codePoint) ?? codePoint; if (byte > 0xff) { throw new RangeError( `Cannot encode U+${codePoint.toString(16).toUpperCase()} as a single byte in ${path}`, ); } return byte; })); const output = meta.bom ? Buffer.concat([UTF8_BOM, bytes]) : bytes; await writeFile(path, output); const verify = await readGameText(path); if (verify.text !== text) { const index = firstDivergence(text, verify.text); throw new Error( `writeGameText: ${path} did not round-trip (first divergent index ${index})`, ); } } export { encodeTextByCodeUnit };