seriesoftubes/scripts/lib/dict.js
Frederic Jung c64b139a86
Fewer merge conflicts: actions by area, one city per line, sorted dictionaries
- ACT is split by area into game/90-actions/*.js (const ACT in the first file,
  Object.assign in the rest)
- CITY_LL, CITY_NUDGE and LANDS_LL have one entry per line; the id-keyed ones
  are sorted
- site/i18n/*.js are sorted, one entry per line; i18n-check enforces it and
  --fix (npm run i18n:fix) restores it; scripts/i18n-add.js adds, removes
  and renames entries in place
- scripts/legacy/port-branch.js moves a branch's site/index.html edits into
  src/ during a merge with main
- perf workflow and PR template build the base page with scripts/lib/page.js
2026-10-27 10:10:16 +01:00

46 lines
2 KiB
JavaScript

// Reads and writes the translation dictionaries in site/i18n/<lang>.js.
//
// Every dictionary is kept in one canonical layout: the header comment, then one `"English":"Translation",`
// entry per line, sorted by the English text. Sorted entries spread new strings across the file instead of
// piling them up at the end, so two pull requests that each add strings rarely touch the same lines.
// `npm run i18n:check` reports a dictionary that is out of order; `npm run i18n:fix` puts it back.
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const DIR = path.join(__dirname, '..', '..', 'site', 'i18n');
const fileOf = (lang) => path.join(DIR, `${lang}.js`);
const langs = () => fs.readdirSync(DIR).filter((f) => f.endsWith('.js')).map((f) => path.basename(f, '.js')).sort();
// Plain code-unit order: the same on every machine, whatever its locale.
const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
function parse(text, lang) {
const window = {};
vm.runInNewContext(text, { window });
return (window.I18N || {})[lang] || {};
}
function read(lang) {
const text = fs.readFileSync(fileOf(lang), 'utf8');
const open = text.indexOf(`(window.I18N=window.I18N||{}).${lang}={`);
if (open < 0) throw new Error(`${lang}.js: missing the (window.I18N=window.I18N||{}).${lang}={ line`);
return { text, header: text.slice(0, open), dict: parse(text, lang) };
}
function format(lang, header, dict) {
const keys = Object.keys(dict).sort(cmp);
return `${header}(window.I18N=window.I18N||{}).${lang}={\n${keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(dict[k])},\n`).join('')}};\n`;
}
// True when the file is already in the canonical layout.
function tidy(lang) {
const { text, header, dict } = read(lang);
return text === format(lang, header, dict);
}
function write(lang, dict, header = read(lang).header) {
fs.writeFileSync(fileOf(lang), format(lang, header, dict));
}
module.exports = { DIR, fileOf, langs, read, write, format, tidy, parse, cmp };