outpost/scripts/check-locales.mjs

66 lines
2.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { languages } from "../packages/viewer/src/localization/runtime.js";
const directory = process.argv[2];
if (!directory) {
throw Error("Usage: node check-locales.mjs <localization directory>");
}
function placeholders(text) {
const tokens = [];
let start = -1;
let depth = 0;
let quote = "";
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (quote) {
if (char === "\\") {
i++;
} else if (char === quote) {
quote = "";
}
} else if (depth > 0 && (char === '"' || char === "'" || char === "`")) {
quote = char;
} else if (char === "{") {
if (depth++ === 0) {
start = i;
}
} else if (char === "}") {
if (depth === 0) {
tokens.push(char);
} else if (--depth === 0) {
tokens.push(text.slice(start, i + 1));
}
}
}
// Legacy extraction left unfinished expressions; preserve those verbatim too.
if (depth > 0) {
tokens.push(text.slice(start));
}
return tokens.sort();
}
async function readCatalog(locale) {
const bytes = await readFile(join(directory, `${locale}.json`));
const catalog = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
assert.ok(catalog && typeof catalog === "object" && !Array.isArray(catalog), `${locale}: expected a catalog object`);
for (const [key, text] of Object.entries(catalog)) {
assert.equal(typeof text, "string", `${locale}: non-string translation of ${key}`);
assert.ok(text.trim(), `${locale}: empty translation of ${key}`);
assert.ok(text.isWellFormed(), `${locale}: invalid Unicode in ${key}`);
assert.ok(!/[\p{Cc}\ufffd]/u.test(text.replace(/[\t\n\r]/g, "")), `${locale}: malformed text in ${key}`);
}
return catalog;
}
const source = await readCatalog("en");
const locales = Object.keys(languages);
for (const locale of locales) {
const catalog = locale === "en" ? source : await readCatalog(locale);
assert.deepEqual(Object.keys(catalog).sort(), Object.keys(source).sort(), `${locale}: missing or extra strings`);
for (const [key, text] of Object.entries(catalog)) {
assert.deepEqual(placeholders(text), placeholders(source[key]), `${locale}: changed placeholders in ${key}`);
}
}
console.log(`${locales.length} languages × ${Object.keys(source).length} messages validated`);