// Checks the translations against English: same keys, every plural category // the language needs, and no placeholder lost or invented. // Run: npm run i18n:check import { readdirSync } from 'node:fs' import { fileURLToPath, pathToFileURL } from 'node:url' import { dirname, join } from 'node:path' const dir = join(dirname(fileURLToPath(import.meta.url)), '../src/i18n/locales') const load = async (f) => (await import(pathToFileURL(join(dir, f)).href)).default const en = await load('en.js') const params = (s) => new Set([...String(s).matchAll(/\{(\w+)\}/g)].map((m) => m[1])) const variants = (m) => (m && typeof m === 'object' ? Object.entries(m) : [['', m]]) let problems = 0 const report = (msg) => { problems++; console.log(' ✗ ' + msg) } for (const file of readdirSync(dir).filter((f) => f.endsWith('.js') && f !== 'en.js').sort()) { const code = file.replace('.js', '') const loc = await load(file) const before = problems console.log(code) // Categories that occur for 0…1000 (Romance "many" only applies to millions // and falls back to "other", which t() does anyway). const rules = new Intl.PluralRules(code) const needed = [...new Set(Array.from({ length: 1001 }, (_, n) => rules.select(n)))] for (const key of Object.keys(en)) if (!(key in loc)) report(`missing key ${key}`) for (const key of Object.keys(loc)) if (!(key in en)) report(`unknown key ${key}`) for (const [key, msg] of Object.entries(loc)) { if (!(key in en)) continue const enMsg = en[key] const enParams = new Set(variants(enMsg).flatMap(([, s]) => [...params(s)])) if (typeof enMsg === 'object') { if (typeof msg !== 'object') { report(`${key}: should have plural forms`); continue } for (const cat of needed) if (!(cat in msg) && !('other' in msg && cat === 'other')) report(`${key}: missing plural "${cat}"`) } for (const [cat, s] of variants(msg)) { for (const p of params(s)) if (!enParams.has(p)) report(`${key}${cat && '.' + cat}: unknown {${p}}`) // Plural forms may spell out small counts ("one file", Arabic "two"), so {count} may be absent there. for (const p of enParams) if (!params(s).has(p) && !(p === 'count' && typeof msg === 'object') && !(p === 'name' && cat && cat !== 'one')) { report(`${key}${cat && '.' + cat}: lost {${p}}`) } } } if (problems === before) console.log(` ✓ ${Object.keys(loc).length} keys, plural categories: ${needed.join(' ')}`) } if (problems) { console.log(`\n${problems} problem(s)`) process.exit(1) } console.log('\nall translations complete')