Ab-Integro / tools /validate.mjs
Ame
feat(tools): 翻译清单改为 v3 紧凑格式并增量校验
20cc92a
Raw
History Blame Contribute Delete
31 kB
#!/usr/bin/env node
// Unified validation command: one parse pass, all findings.
//
// Merges the four former tools into a single `node tools/validate.mjs` run:
// 1. tools/eu4_clausewitz/bin/validate.mjs (refs, encoding, loc, unowned-land, ambiguities)
// 2. tools/bin/audit.mjs (duplicate definitions in common/ and events/)
// 3. tools/build_variants.mjs check (English overlay + manifest consistency)
// 4. tools/localisation.ps1 check (localisation source vs built output)
//
// New: province/area/region/trade-node scope refs in events/decisions/missions.
//
// Output: findings grouped by category, file:line:col format, summary count
// per level (error/warn/info). Exit non-zero only on errors.
import { createHash } from 'node:crypto';
import { readdir, readFile, stat } from 'node:fs/promises';
import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import process from 'node:process';
import { load } from './eu4_clausewitz/src/index.mjs';
import { readGameText } from './eu4_clausewitz/src/codec.mjs';
import { tokenize } from './eu4_clausewitz/src/lexer.mjs';
import { parse } from './eu4_clausewitz/src/ast.mjs';
import { isDateKey } from './eu4_clausewitz/src/node.mjs';
import { buildDefinedSets, buildRefGraph } from './eu4_clausewitz/src/refs.mjs';
import { runRules, summarize } from './eu4_clausewitz/src/validate.mjs';
import { loadDir } from './eu4_clausewitz/src/overlay.mjs';
import provincesRegistry from './eu4_clausewitz/registry/provinces.mjs';
import countriesRegistry from './eu4_clausewitz/registry/countries.mjs';
import provinceRules, { provinceRefRules } from './eu4_clausewitz/registry/provinces.rules.mjs';
import countryRules, { countryRefRules } from './eu4_clausewitz/registry/countries.rules.mjs';
import encodingRules from './eu4_clausewitz/registry/encoding.rules.mjs';
import { loadManifest, validateManifestAgainstRoot } from './history_language_manifest.mjs';
import { hasUtf8Bom, encodeBuffer } from './eu4_han_convert/src/codec.js';
// --- paths ------------------------------------------------------------------
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const MOD_ROOT = root;
const VANILLA_ROOT = 'C:/Program Files (x86)/Steam/steamapps/common/Europa Universalis IV';
const GAME_LOCALISATION = join(VANILLA_ROOT, 'localisation');
const REGISTRIES = [provincesRegistry, countriesRegistry];
const MANIFEST_PATH = join(root, 'history_language_manifest.json');
const LOC_MANIFEST_PATH = join(root, 'localisation_manifest.json');
const CODEC_PATH = join(root, 'tools', 'eu4_han_convert', 'src', 'codec.js');
const LOC_SOURCE_ROOT = join(root, 'localisation_source');
const LOC_ENCODED_ROOT = join(root, 'localisation');
const ENGLISH_SOURCE = join(root, 'localisation_english_source');
const ENGLISH_PROVENANCE = join(root, 'localisation_english_provenance.json');
const CHINESE_SOURCE = join(root, 'localisation_source');
// --- helpers ----------------------------------------------------------------
async function walkTxtFiles(dir, out = []) {
let entries;
try {
entries = await readdir(dir, { withFileTypes: true });
} catch {
return out;
}
for (const entry of entries) {
const path = join(dir, entry.name);
if (entry.isDirectory()) await walkTxtFiles(path, out);
else if (entry.isFile() && entry.name.toLowerCase().endsWith('.txt')) out.push(path);
}
return out;
}
async function walkYmlFiles(dir, out = []) {
let entries;
try {
entries = await readdir(dir, { withFileTypes: true });
} catch {
return out;
}
for (const entry of entries) {
const path = join(dir, entry.name);
if (entry.isDirectory()) await walkYmlFiles(path, out);
else if (entry.isFile() && entry.name.toLowerCase().endsWith('.yml')) out.push(path);
}
return out;
}
function rel(path) {
return relative(MOD_ROOT, path).replace(/\\/g, '/');
}
async function parseFile(path) {
const { text } = await readGameText(path);
return { text, tree: parse(tokenize(text)) };
}
async function exists(path) {
try {
await stat(path);
return true;
} catch (error) {
if (error.code === 'ENOENT') return false;
throw error;
}
}
// ===========================================================================
// Phase 1: Build defined sets + map-level valid ID sets
// ===========================================================================
async function buildMapSets() {
// Province IDs from definition.csv: "province;red;green;blue;x;x" per line
const defPath = join(MOD_ROOT, 'map', 'definition.csv');
const provinces = new Set();
try {
const content = await readFile(defPath, 'utf8');
for (const line of content.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const id = trimmed.split(';')[0];
if (/^\d+$/.test(id)) provinces.add(Number(id));
}
} catch { /* definition.csv missing - leave empty */ }
// Areas from area.txt: top-level "<name>_area = { ... }" blocks
const areas = new Set();
try {
const { tree } = await parseFile(join(MOD_ROOT, 'map', 'area.txt'));
for (const item of tree.items) {
if (item.kind === 'pair' && item.value.type === 'block') {
areas.add(item.keyToken.value);
}
}
} catch { /* missing - leave empty */ }
// Regions from region.txt: top-level "<name>_region = { ... }" blocks
const regions = new Set();
try {
const { tree } = await parseFile(join(MOD_ROOT, 'map', 'region.txt'));
for (const item of tree.items) {
if (item.kind === 'pair' && item.value.type === 'block') {
regions.add(item.keyToken.value);
}
}
} catch { /* missing - leave empty */ }
// Trade nodes from common/tradenodes/: top-level "<name> = { ... }" blocks
const tradeNodes = new Set();
const tradeNodeFiles = await walkTxtFiles(join(MOD_ROOT, 'common', 'tradenodes'));
for (const path of tradeNodeFiles) {
const { tree } = await parseFile(path);
for (const item of tree.items) {
if (item.kind === 'pair' && item.value.type === 'block') {
tradeNodes.add(item.keyToken.value);
}
}
}
return { provinces, areas, regions, tradeNodes };
}
// ===========================================================================
// Phase 2: Ref integrity (from old validate.mjs runRefs)
// ===========================================================================
async function runRefs(eu4, ctx) {
const graph = await buildRefGraph(eu4, { gameRoot: VANILLA_ROOT, modRoot: MOD_ROOT }, REGISTRIES, ctx.definedSets);
const rules = [...provinceRefRules, ...countryRefRules];
return runRules(rules, graph.forward, ctx);
}
// ===========================================================================
// Phase 3: Province/country warnings (from old validate.mjs)
// ===========================================================================
async function collectRecords(eu4, registry) {
const { entries } = await loadDir({ gameRoot: VANILLA_ROOT, modRoot: MOD_ROOT, relPath: registry.path });
const collection = await eu4.dir(registry.path);
const records = [];
for (const id of entries.keys()) {
records.push({ id, node: await collection.get(id) });
}
return records;
}
async function runProvinceCountryWarnings(eu4, ctx) {
const provinceRecords = await collectRecords(eu4, provincesRegistry);
const countryRecords = await collectRecords(eu4, countriesRegistry);
return [
...runRules(provinceRules, provinceRecords, ctx),
...runRules(countryRules, countryRecords, ctx),
];
}
// ===========================================================================
// Phase 4: Encoding (from old validate.mjs runEncoding)
// ===========================================================================
async function runEncoding() {
const dirs = [
join(VANILLA_ROOT, 'history'),
join(VANILLA_ROOT, 'common'),
join(MOD_ROOT, 'history'),
join(MOD_ROOT, 'common'),
];
const files = [];
for (const dir of dirs) await walkTxtFiles(dir, files);
const records = [];
for (const path of files) {
const { text, bom } = await readGameText(path);
records.push({ path, text, bom });
}
return runRules(encodingRules, records, {});
}
// ===========================================================================
// Phase 5: Overlay ambiguities (from old validate.mjs)
// ===========================================================================
function runAmbiguities(eu4) {
return eu4.ambiguities
.filter((a) => !(a.key === 'SOF' && a.layer === 'vanilla'))
.map((a) => ({
id: 'overlay-ambiguity',
level: 'info',
message: `${a.dir}: key "${a.key}" (${a.layer} layer) is ambiguous between ${a.paths.map((p) => rel(p)).join(', ')}`,
}));
}
// ===========================================================================
// Phase 6: Duplicate definitions (from audit.mjs)
// ===========================================================================
const AUDIT_SKIP_DIRS = new Set(['common/defines', 'common/custom_gui']);
const AUDIT_SKIP_PREFIXES = ['common/countries'];
function noteKey(buckets, bucket, key, file, line) {
let byKey = buckets.get(bucket);
if (!byKey) {
byKey = new Map();
buckets.set(bucket, byKey);
}
let occ = byKey.get(key);
if (!occ) {
occ = [];
byKey.set(key, occ);
}
occ.push({ file, line });
}
function dupFindings(id, level, bucket, key, occ) {
const sorted = [...occ].sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
return [{
id,
level,
file: sorted[0].file,
line: sorted[0].line,
message: `duplicate "${key}" in ${bucket}: ${sorted.map((s) => `${s.file}:${s.line}`).join(', ')}`,
}];
}
async function runDuplicateDefinitions() {
const findings = [];
// --- common/ ---
const commonBuckets = new Map(); // bucket -> Map<key, Array<{file, line}>>
const commonFiles = await walkTxtFiles(join(MOD_ROOT, 'common'));
for (const path of commonFiles) {
const bucket = rel(join(path, '..'));
if (AUDIT_SKIP_DIRS.has(bucket) || AUDIT_SKIP_PREFIXES.some((p) => bucket === p || bucket.startsWith(p + '/'))) continue;
const { tree } = await parseFile(path);
let keyBucket = bucket;
if (bucket === 'common/province_names') {
const stem = rel(path).split('/').pop().replace(/\.txt$/i, '').replace(/_new$/i, '');
keyBucket = `${bucket}/${stem}`;
}
for (const item of tree.items) {
if (item.kind !== 'pair') continue;
noteKey(commonBuckets, keyBucket, item.keyToken.value, rel(path), item.keyToken.line);
}
}
for (const [bucket, byKey] of [...commonBuckets.entries()].sort()) {
for (const [key, occ] of byKey) {
const files = new Set(occ.map((o) => o.file));
if (occ.length > 1 && files.size > 1) {
findings.push(...dupFindings('dup-common-cross-file', 'warn', bucket, key, occ));
} else if (occ.length > 1) {
findings.push(...dupFindings('dup-common-in-file', 'warn', bucket, key, occ));
}
}
}
// --- events/ ---
const eventIds = new Map(); // id -> Array<{file, line}>
const eventFiles = await walkTxtFiles(join(MOD_ROOT, 'events'));
for (const path of eventFiles) {
const { tree } = await parseFile(path);
let namespace = null;
for (const item of tree.items) {
if (item.kind === 'pair' && item.keyToken.value === 'namespace'
&& item.value.type === 'scalar' && item.value.token) {
namespace = item.value.token.value;
continue;
}
if (item.kind !== 'pair' || !item.keyToken.value.endsWith('_event')
|| item.value.type !== 'block') continue;
for (const inner of item.value.items) {
if (inner.kind === 'pair' && inner.keyToken.value === 'id'
&& inner.value.type === 'scalar' && inner.value.token) {
let id = inner.value.token.value;
if (!id.includes('.') && namespace) id = `${namespace}.${id}`;
let occ = eventIds.get(id);
if (!occ) {
occ = [];
eventIds.set(id, occ);
}
occ.push({ file: rel(path), line: inner.keyToken.line });
break;
}
}
}
}
for (const [id, occ] of [...eventIds.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
if (occ.length > 1) {
findings.push(...dupFindings('dup-event-id', 'error', 'events', id, occ));
}
}
// --- common/scripted_effects/ and common/scripted_triggers/ ---
for (const subdir of ['common/scripted_effects', 'common/scripted_triggers']) {
const files = await walkTxtFiles(join(MOD_ROOT, subdir));
const names = new Map(); // name -> Array<{file, line}>
for (const path of files) {
const { tree } = await parseFile(path);
for (const item of tree.items) {
if (item.kind === 'pair') {
let occ = names.get(item.keyToken.value);
if (!occ) {
occ = [];
names.set(item.keyToken.value, occ);
}
occ.push({ file: rel(path), line: item.keyToken.line });
}
}
}
const id = subdir === 'common/scripted_effects' ? 'dup-scripted-effect' : 'dup-scripted-trigger';
for (const [name, occ] of names) {
if (occ.length > 1) {
findings.push(...dupFindings(id, 'warn', subdir, name, occ));
}
}
}
return findings;
}
// ===========================================================================
// Phase 7: Province/area/region/trade-node refs in events/decisions/missions (NEW)
// ===========================================================================
const ENGINE_AREA_KEYWORDS = new Set([
'random_owned_area', 'random_enemy_area', 'random_neighboring_area',
'random_area', 'any_owned_area', 'any_area', 'every_owned_area',
'every_area', 'any_neighbor_area', 'every_neighbor_area',
'random_neighbor_area', 'has_trade_company_investment_in_area',
]);
const ENGINE_REGION_KEYWORDS = new Set([
'random_owned_region', 'random_region', 'any_owned_region', 'any_region',
'every_owned_region', 'every_region', 'random_new_world_region',
'any_neighbor_region', 'every_neighbor_region', 'random_neighbor_region',
]);
// Trade-node iterator scopes and trigger/effect names that end in _node but
// are NOT trade-node-name scopes. A real trade node scope is just
// "<node_name> = { ... }" where node_name is a lowercase identifier from
// 00_tradenodes.txt.
const ENGINE_TRADE_NODE_KEYWORDS = new Set([
'any_active_trade_node', 'home_trade_node', 'any_trade_node',
'every_trade_node', 'random_trade_node', 'any_neighbor_trade_node',
'every_neighbor_trade_node', 'random_neighbor_trade_node',
'capital_trade_node', 'random_active_trade_node',
'every_active_trade_node', 'any_core_trade_node', 'every_core_trade_node',
'random_core_trade_node', 'all_trade_node',
'has_privateer_share_in_trade_node', 'has_trade_power_in_trade_node',
'has_missionary_in_trade_node',
]);
// Prefixes/patterns that indicate a key is a trigger, effect, event_target,
// or variable rather than a named scope. These never represent area/region/
// trade-node definitions.
const NON_SCOPE_PREFIXES = ['has_', 'event_target:', '@', 'set_', 'change_',
'add_', 'remove_', 'is_', 'can_', 'does_'];
function isNonScopeKey(key) {
return NON_SCOPE_PREFIXES.some((p) => key.startsWith(p)) || key.includes(':');
}
// Fields whose scalar value should be a province ID
const PROVINCE_ID_FIELDS = new Set([
'province_id', 'owns_core_province', 'capital', 'capital_province',
'province', 'target_province', 'hidden_province',
'fleet_size_province', 'missionary_province', 'reformation_center',
]);
const DATE_LIKE = /^\d{1,4}\.\d{1,2}\.\d{1,2}$/;
const PURE_NUMBER = /^\d+$/;
function walkItems(items, fn) {
for (const item of items) {
fn(item);
if (item.kind === 'pair' && item.value.type === 'block') {
walkItems(item.value.items, fn);
}
}
}
async function runScopeRefs(mapSets) {
const findings = [];
const dirs = ['events', 'decisions', 'missions'];
for (const dirName of dirs) {
const files = await walkTxtFiles(join(MOD_ROOT, dirName));
for (const path of files) {
const { tree } = await parseFile(path);
const fileRel = rel(path);
walkItems(tree.items, (item) => {
if (item.kind !== 'pair') return;
const key = item.keyToken.value;
const line = item.keyToken.line;
// Check province-id fields with scalar numeric values
if (PROVINCE_ID_FIELDS.has(key) && item.value.type === 'scalar' && item.value.token) {
const val = item.value.token.value;
if (PURE_NUMBER.test(val)) {
const id = Number(val);
if (!mapSets.provinces.has(id)) {
findings.push({
id: 'scope-province-ref', level: 'warn', file: fileRel, line,
message: `province_id ${val} (field "${key}") is not a valid province in definition.csv`,
});
}
}
}
// Check bare-number scopes: "1234 = { ... }" - verify it's a valid province
if (item.value.type === 'block' && PURE_NUMBER.test(key) && !DATE_LIKE.test(key)) {
const id = Number(key);
if (!mapSets.provinces.has(id)) {
findings.push({
id: 'scope-province-scope', level: 'warn', file: fileRel, line,
message: `province scope "${key}" is not a valid province in definition.csv`,
});
}
}
// Check _area scopes
if (item.value.type === 'block' && key.endsWith('_area') && !ENGINE_AREA_KEYWORDS.has(key) && !isNonScopeKey(key)) {
if (!mapSets.areas.has(key)) {
findings.push({
id: 'scope-area-ref', level: 'warn', file: fileRel, line,
message: `area "${key}" is not defined in map/area.txt`,
});
}
}
// Check _region scopes
if (item.value.type === 'block' && key.endsWith('_region') && !ENGINE_REGION_KEYWORDS.has(key) && !isNonScopeKey(key)) {
if (!mapSets.regions.has(key)) {
findings.push({
id: 'scope-region-ref', level: 'warn', file: fileRel, line,
message: `region "${key}" is not defined in map/region.txt`,
});
}
}
// Check _node scopes
if (item.value.type === 'block' && key.endsWith('_node') && !ENGINE_TRADE_NODE_KEYWORDS.has(key) && !isNonScopeKey(key) && key === key.toLowerCase() && !key.includes('_best_')) {
if (!mapSets.tradeNodes.has(key)) {
findings.push({
id: 'scope-tradenode-ref', level: 'warn', file: fileRel, line,
message: `trade node "${key}" is not defined in common/tradenodes/`,
});
}
}
});
}
}
return findings;
}
// ===========================================================================
// Phase 8: Manifest consistency (from build_history_english.mjs check)
// ===========================================================================
async function runManifestCheck() {
const findings = [];
const started = Date.now();
try {
const manifest = await loadManifest(MANIFEST_PATH);
const summary = await validateManifestAgainstRoot(manifest, root);
if (summary.stale.length) {
const sample = summary.stale.slice(0, 5).join(', ');
findings.push({
id: 'manifest-stale', level: 'error',
message: `${summary.stale.length} file(s) changed since last manifest stamp (e.g. ${sample}${summary.stale.length > 5 ? ', ...' : ''}); run: node tools/history_language_manifest.mjs stamp`,
});
}
} catch (error) {
findings.push({
id: 'manifest-consistency', level: 'error',
message: error.message,
});
}
console.log(`Manifest check took ${((Date.now() - started) / 1000).toFixed(1)}s`);
return findings;
}
// ===========================================================================
// Phase 9: Localisation source vs built (from localisation.mjs check)
// ===========================================================================
function sha256(buffer) {
return createHash('sha256').update(buffer).digest('hex');
}
async function listLocalisationFiles(dirRoot) {
const files = [];
async function visit(directory) {
const entries = await readdir(directory, { withFileTypes: true });
for (const entry of entries) {
const path = join(directory, entry.name);
if (entry.isDirectory()) await visit(path);
else if (entry.isFile() && entry.name.endsWith('.yml')) {
files.push(relative(dirRoot, path).replaceAll('\\', '/'));
}
}
}
await visit(dirRoot);
return files.sort();
}
async function runLocalisationCheck() {
const findings = [];
const [sourceFiles, encodedFiles] = await Promise.all([
listLocalisationFiles(LOC_SOURCE_ROOT),
listLocalisationFiles(LOC_ENCODED_ROOT),
]);
const sourceSet = new Set(sourceFiles);
const encodedSet = new Set(encodedFiles);
for (const path of sourceFiles) {
if (!encodedSet.has(path)) {
findings.push({ id: 'loc-file-set', level: 'error', message: `missing encoded file: ${path}` });
}
}
for (const path of encodedFiles) {
if (!sourceSet.has(path)) {
findings.push({ id: 'loc-file-set', level: 'error', message: `missing source file: ${path}` });
}
}
// Check manifest currency + hash comparison
let manifest = null;
try {
manifest = JSON.parse(await readFile(LOC_MANIFEST_PATH, 'utf8'));
} catch {
// no manifest - will fall through to re-encode check
}
const codecSha256 = sha256(await readFile(CODEC_PATH));
const manifestCurrent = manifest
&& manifest.version === 1
&& manifest.profile === 'compatible'
&& manifest.codecSha256 === codecSha256;
let outOfDate = false;
for (const path of sourceFiles) {
if (!encodedSet.has(path)) continue;
const sourceBuffer = await readFile(join(LOC_SOURCE_ROOT, path));
const encodedBuffer = await readFile(join(LOC_ENCODED_ROOT, path));
if (!hasUtf8Bom(encodedBuffer)) {
findings.push({ id: 'loc-bom', level: 'error', message: `missing UTF-8 BOM: ${path}` });
}
const sourceSha256 = sha256(sourceBuffer);
const encodedSha256 = sha256(encodedBuffer);
const entry = manifestCurrent ? manifest.files?.[path] : null;
if (entry && entry.sourceSha256 === sourceSha256 && entry.encodedSha256 === encodedSha256) {
continue; // verified via manifest
}
// Fall back to re-encode-and-compare
let expected;
try {
expected = encodeBuffer(new TextDecoder('utf-8', { fatal: true }).decode(
sourceBuffer.subarray(0, 3).equals(Buffer.from([0xef, 0xbb, 0xbf])) ? sourceBuffer.subarray(3) : sourceBuffer,
), { profile: 'compatible' });
} catch (error) {
findings.push({ id: 'loc-encode', level: 'error', message: `failed to encode ${path}: ${error.message}` });
outOfDate = true;
continue;
}
if (!encodedBuffer.equals(expected)) {
findings.push({ id: 'loc-stale', level: 'error', message: `encoded localisation is out of date: ${path}` });
outOfDate = true;
}
}
if (!manifestCurrent || outOfDate) {
findings.push({ id: 'loc-manifest', level: 'error', message: 'localisation_manifest.json is out of date; run the build command' });
}
return findings;
}
// ===========================================================================
// Phase 10: English overlay (from build_variants.mjs validateEnglishOverlay)
// ===========================================================================
async function listEnglishFiles(directory, englishOnly = false) {
const files = [];
async function visit(current) {
for (const entry of await readdir(current, { withFileTypes: true })) {
const path = join(current, entry.name);
if (entry.isDirectory()) await visit(path);
else if (entry.isFile() && entry.name.endsWith('.yml') && (!englishOnly || entry.name.endsWith('_l_english.yml'))) {
files.push(relative(directory, path).replaceAll('\\', '/'));
}
}
}
await visit(directory);
return files.sort();
}
function parseLocEntries(content) {
return [...content.split(/\r?\n/)].flatMap((line) => {
const match = line.match(/^\s*([^\s:#]+):(?:\d+)?\s+".*"/);
return match ? [[match[1], line.trimEnd()]] : [];
});
}
async function readKeyLineIndex(directory, rejectDuplicates = false, englishOnly = false) {
const index = new Map();
for (const file of await listEnglishFiles(directory, englishOnly)) {
const content = await readFile(join(directory, file), 'utf8');
for (const [key, line] of parseLocEntries(content)) {
if (rejectDuplicates && index.has(key)) {
throw new Error('duplicate localisation key ' + key + ' in ' + index.get(key).file + ' and ' + file);
}
index.set(key, { file, line });
}
}
return index;
}
async function runEnglishOverlay() {
const findings = [];
if (!await exists(ENGLISH_SOURCE)) {
findings.push({ id: 'english-overlay', level: 'error', message: 'missing localisation_english_source' });
return findings;
}
let provenance;
try {
provenance = JSON.parse(await readFile(ENGLISH_PROVENANCE, 'utf8'));
} catch (error) {
findings.push({ id: 'english-overlay', level: 'error', message: `cannot read provenance: ${error.message}` });
return findings;
}
let chineseKeys, vanillaKeys, customKeys;
try {
[chineseKeys, vanillaKeys, customKeys] = await Promise.all([
readKeyLineIndex(CHINESE_SOURCE),
readKeyLineIndex(GAME_LOCALISATION, false, true),
readKeyLineIndex(ENGLISH_SOURCE, true),
]);
} catch (error) {
findings.push({ id: 'english-overlay', level: 'error', message: error.message });
return findings;
}
// No vanilla override without allowVanillaOverride
for (const [key, entry] of customKeys) {
if (vanillaKeys.has(key)) {
const filePolicy = provenance.files?.[entry.file];
if (!filePolicy?.allowVanillaOverride) {
findings.push({
id: 'english-vanilla-override', level: 'error', file: entry.file,
message: `English source must not override vanilla key ${key}`,
});
}
}
}
// Every Chinese key must have English coverage
const missing = [...chineseKeys.keys()].filter((key) => !vanillaKeys.has(key) && !customKeys.has(key));
if (missing.length) {
const grouped = new Map();
for (const key of missing) {
const file = chineseKeys.get(key).file;
grouped.set(file, (grouped.get(file) ?? 0) + 1);
}
findings.push({
id: 'english-incomplete', level: 'error',
message: 'English source is incomplete:\n' + [...grouped].map(([file, count]) => file + ': ' + count).join('\n'),
});
}
// No unused English keys
const unused = [...customKeys.keys()].filter((key) => !chineseKeys.has(key));
if (unused.length) {
findings.push({
id: 'english-unused', level: 'error',
message: `English source contains keys absent from the Chinese base: ${unused.slice(0, 20).join(', ')}`,
});
}
// Provenance files match source files
const files = await listEnglishFiles(ENGLISH_SOURCE);
for (const file of files) {
if (!provenance.files?.[file]) {
findings.push({ id: 'english-provenance', level: 'error', message: `missing provenance record: ${file}` });
}
}
for (const file of Object.keys(provenance.files ?? {})) {
if (!files.includes(file)) {
findings.push({ id: 'english-provenance', level: 'error', message: `provenance record has no source file: ${file}` });
}
}
return findings;
}
// ===========================================================================
// Output
// ===========================================================================
function printCategory(label, findings) {
if (findings.length === 0) {
console.log(`\n[${label}] (no findings)`);
return;
}
console.log(`\n[${label}] (${findings.length})`);
const byId = new Map();
for (const f of findings) {
if (!byId.has(f.id)) byId.set(f.id, []);
byId.get(f.id).push(f);
}
for (const [id, list] of byId) {
console.log(`\n [${list[0].level}] ${id} (${list.length})`);
for (const f of list) {
const position = f.file ? `${f.file}:${f.line ?? '?'}:${f.col ?? '?'}: ` : '';
console.log(` ${position}${f.message}`);
}
}
}
// ===========================================================================
// Main
// ===========================================================================
async function main() {
console.log('Loading EU4 + mod tree...');
const eu4 = await load({ game: VANILLA_ROOT, mod: MOD_ROOT });
const definedSets = await buildDefinedSets({ gameRoot: VANILLA_ROOT, modRoot: MOD_ROOT });
const mapSets = await buildMapSets();
const ctx = { definedSets };
console.log('Running ref integrity...');
const refFindings = await runRefs(eu4, ctx);
console.log('Running province/country warnings...');
const pcFindings = await runProvinceCountryWarnings(eu4, ctx);
console.log('Running encoding checks...');
const encodingFindings = await runEncoding();
console.log('Running overlay ambiguity checks...');
const ambiguityFindings = runAmbiguities(eu4);
console.log('Running duplicate definition checks...');
const dupFindings = await runDuplicateDefinitions();
console.log('Running scope reference checks (events/decisions/missions)...');
const scopeFindings = await runScopeRefs(mapSets);
console.log('Running manifest consistency checks...');
const manifestFindings = await runManifestCheck();
console.log('Running localisation source vs built checks...');
const locFindings = await runLocalisationCheck();
console.log('Running English overlay checks...');
const englishFindings = await runEnglishOverlay();
const allFindings = [
...refFindings,
...pcFindings,
...encodingFindings,
...ambiguityFindings,
...dupFindings,
...scopeFindings,
...manifestFindings,
...locFindings,
...englishFindings,
];
printCategory('Ref Integrity', refFindings);
printCategory('Province/Country Warnings', pcFindings);
printCategory('Encoding', encodingFindings);
printCategory('Overlay Ambiguities', ambiguityFindings);
printCategory('Duplicate Definitions', dupFindings);
printCategory('Scope References', scopeFindings);
printCategory('Manifest Consistency', manifestFindings);
printCategory('Localisation Source vs Built', locFindings);
printCategory('English Overlay', englishFindings);
const summary = summarize(allFindings);
console.log(`\n${summary.error} errors, ${summary.warn} warnings, ${summary.info} infos`);
process.exitCode = summary.error > 0 ? 1 : 0;
}
main().catch((err) => {
console.error(err);
process.exitCode = 1;
});