import { createHash } from 'node:crypto'; import { availableParallelism } from 'node:os'; import { readFile, readdir, stat, writeFile } from 'node:fs/promises'; import { dirname, join, relative, resolve } from 'node:path'; import process from 'node:process'; import { fileURLToPath } from 'node:url'; import { Worker } from 'node:worker_threads'; import { hasUtf8Bom } from './eu4_han_convert/src/codec.js'; const PROFILE = 'compatible'; const MANIFEST_VERSION = 1; const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const sourceRoot = join(repositoryRoot, 'localisation_source'); const encodedRoot = join(repositoryRoot, 'localisation'); const manifestPath = join(repositoryRoot, 'localisation_manifest.json'); const codecPath = join(repositoryRoot, 'tools', 'eu4_han_convert', 'src', 'codec.js'); function hash(buffer) { return createHash('sha256').update(buffer).digest('hex'); } async function listLocalisationFiles(root) { 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(root, path).replaceAll('\\', '/')); } } } await visit(root); return files.sort(); } async function pathExists(path) { try { await stat(path); return true; } catch (error) { if (error.code === 'ENOENT') return false; throw error; } } async function readManifest() { if (!await pathExists(manifestPath)) return null; return JSON.parse(await readFile(manifestPath, 'utf8')); } async function getPipeline() { return { version: MANIFEST_VERSION, profile: PROFILE, codecSha256: hash(await readFile(codecPath)), }; } function isCurrentManifest(manifest, pipeline) { return manifest && manifest.version === pipeline.version && manifest.profile === pipeline.profile && manifest.codecSha256 === pipeline.codecSha256; } function compareFileSets(sourceFiles, encodedFiles) { const sourceSet = new Set(sourceFiles); const encodedSet = new Set(encodedFiles); return { missing: sourceFiles.filter((path) => !encodedSet.has(path)), extra: encodedFiles.filter((path) => !sourceSet.has(path)), }; } function assertSameFileSet(sourceFiles, encodedFiles) { const { missing, extra } = compareFileSets(sourceFiles, encodedFiles); if (missing.length || extra.length) { throw new Error([ ...missing.map((path) => `missing encoded file: ${path}`), ...extra.map((path) => `missing source file: ${path}`), ].join('\n')); } } async function mapConcurrent(items, concurrency, worker) { const results = new Array(items.length); let nextIndex = 0; async function run() { while (nextIndex < items.length) { const index = nextIndex; nextIndex += 1; results[index] = await worker(items[index]); } } await Promise.all( Array.from( { length: Math.min(concurrency, Math.max(items.length, 1)) }, () => run(), ), ); return results; } class CodecPool { constructor(size) { this.queue = []; this.nextId = 0; this.workers = Array.from({ length: size }, () => { const state = { worker: new Worker(new URL('./localisation_worker.mjs', import.meta.url)), active: null, }; state.worker.on('message', (message) => { if (message.error) state.active.reject(new Error(message.error)); else state.active.resolve(Buffer.from(message.output)); state.active = null; this.dispatch(); }); state.worker.on('error', (error) => { if (state.active) state.active.reject(error); state.active = null; this.dispatch(); }); return state; }); } run(operation, input) { return new Promise((resolveJob, rejectJob) => { this.queue.push({ id: this.nextId, operation, input, resolve: resolveJob, reject: rejectJob, }); this.nextId += 1; this.dispatch(); }); } dispatch() { for (const state of this.workers) { if (state.active || !this.queue.length) continue; state.active = this.queue.shift(); state.worker.postMessage({ id: state.active.id, operation: state.active.operation, input: state.active.input, }); } } async close() { await Promise.all(this.workers.map(({ worker }) => worker.terminate())); } } async function writeManifest(pipeline, entries) { const manifest = { ...pipeline, files: Object.fromEntries( Object.entries(entries).sort(([left], [right]) => left.localeCompare(right)), ), }; await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8'); } async function build(concurrency, codecPool) { const sourceFiles = await listLocalisationFiles(sourceRoot); const encodedFiles = await listLocalisationFiles(encodedRoot); const { extra } = compareFileSets(sourceFiles, encodedFiles); if (extra.length) { throw new Error(extra.map((path) => `missing source file: ${path}`).join('\n')); } const encodedSet = new Set(encodedFiles); const pipeline = await getPipeline(); const previous = await readManifest(); const previousFiles = isCurrentManifest(previous, pipeline) ? previous.files : {}; const results = await mapConcurrent(sourceFiles, concurrency, async (path) => { const sourceBuffer = await readFile(join(sourceRoot, path)); const sourceSha256 = hash(sourceBuffer); const outputPath = join(encodedRoot, path); const outputBuffer = encodedSet.has(path) ? await readFile(outputPath) : null; const encodedSha256 = outputBuffer ? hash(outputBuffer) : null; const previousEntry = previousFiles[path]; if ( previousEntry && previousEntry.sourceSha256 === sourceSha256 && previousEntry.encodedSha256 === encodedSha256 ) { return { path, entry: previousEntry, rebuilt: false }; } const expected = await codecPool.run('encode', sourceBuffer); const rebuilt = !outputBuffer || !outputBuffer.equals(expected); if (rebuilt) await writeFile(outputPath, expected); return { path, rebuilt, entry: { sourceSha256, encodedSha256: hash(expected), }, }; }); await writeManifest( pipeline, Object.fromEntries(results.map(({ path, entry }) => [path, entry])), ); const rebuilt = results.filter((result) => result.rebuilt).length; process.stdout.write( `Localisation build complete: ${rebuilt} rebuilt, ${sourceFiles.length - rebuilt} reused, ${concurrency} workers.\n`, ); } async function check(concurrency, codecPool) { const sourceFiles = await listLocalisationFiles(sourceRoot); const encodedFiles = await listLocalisationFiles(encodedRoot); assertSameFileSet(sourceFiles, encodedFiles); const pipeline = await getPipeline(); const manifest = await readManifest(); const manifestCurrent = isCurrentManifest(manifest, pipeline); const results = await mapConcurrent(sourceFiles, concurrency, async (path) => { const sourceBuffer = await readFile(join(sourceRoot, path)); const encodedBuffer = await readFile(join(encodedRoot, path)); if (!hasUtf8Bom(encodedBuffer)) throw new Error(`missing UTF-8 BOM: ${path}`); const sourceSha256 = hash(sourceBuffer); const encodedSha256 = hash(encodedBuffer); const entry = manifestCurrent ? manifest.files[path] : null; if ( entry && entry.sourceSha256 === sourceSha256 && entry.encodedSha256 === encodedSha256 ) { return false; } const expected = await codecPool.run('encode', sourceBuffer); if (!encodedBuffer.equals(expected)) { throw new Error(`encoded localisation is out of date: ${path}`); } return true; }); if (!manifestCurrent || results.some(Boolean)) { throw new Error('localisation_manifest.json is out of date; run the build command'); } process.stdout.write( `Localisation check complete: ${sourceFiles.length} verified, 0 re-encoded, ${concurrency} workers.\n`, ); } async function source(concurrency, codecPool) { const encodedFiles = await listLocalisationFiles(encodedRoot); const sourceFiles = await listLocalisationFiles(sourceRoot); const { missing } = compareFileSets(sourceFiles, encodedFiles); if (missing.length) { throw new Error(missing.map((path) => `missing encoded file: ${path}`).join('\n')); } const sourceSet = new Set(sourceFiles); const pipeline = await getPipeline(); const previous = await readManifest(); const previousFiles = isCurrentManifest(previous, pipeline) ? previous.files : {}; const results = await mapConcurrent(encodedFiles, concurrency, async (path) => { const encodedBuffer = await readFile(join(encodedRoot, path)); if (!hasUtf8Bom(encodedBuffer)) throw new Error(`missing UTF-8 BOM: ${path}`); const encodedSha256 = hash(encodedBuffer); const outputPath = join(sourceRoot, path); const sourceBuffer = sourceSet.has(path) ? await readFile(outputPath) : null; const sourceSha256 = sourceBuffer ? hash(sourceBuffer) : null; const previousEntry = previousFiles[path]; if (previousEntry) { const sourceChanged = previousEntry.sourceSha256 !== sourceSha256; const encodedChanged = previousEntry.encodedSha256 !== encodedSha256; if (sourceChanged && encodedChanged) throw new Error(`localisation conflict: ${path}`); if (sourceChanged) throw new Error(`readable source is newer; run the build command: ${path}`); if (!encodedChanged) return { path, entry: previousEntry, decoded: false }; } const decodedBuffer = await codecPool.run('decode', encodedBuffer); await writeFile(outputPath, decodedBuffer); return { path, decoded: true, entry: { sourceSha256: hash(decodedBuffer), encodedSha256, }, }; }); await writeManifest( pipeline, Object.fromEntries(results.map(({ path, entry }) => [path, entry])), ); const decoded = results.filter((result) => result.decoded).length; process.stdout.write( `Localisation source sync complete: ${decoded} decoded, ${encodedFiles.length - decoded} reused, ${concurrency} workers.\n`, ); } function parseArguments(arguments_) { const command = arguments_[0] ?? 'build'; if (!['build', 'source'].includes(command)) { throw new TypeError(`unknown command: ${command} (use node tools/validate.mjs for checking)`); } const jobsIndex = arguments_.indexOf('--jobs'); const defaultJobs = Math.min(Math.max(availableParallelism() - 1, 1), 8); const concurrency = jobsIndex === -1 ? defaultJobs : Number(arguments_[jobsIndex + 1]); if (!Number.isInteger(concurrency) || concurrency < 1) { throw new TypeError('--jobs requires a positive integer'); } return { command, concurrency }; } const { command, concurrency } = parseArguments(process.argv.slice(2)); const codecPool = new CodecPool(concurrency); try { if (command === 'build') await build(concurrency, codecPool); else await source(concurrency, codecPool); } catch (error) { process.stderr.write(`${error.message}\n`); process.exitCode = 1; } finally { await codecPool.close(); }