From 12f0ec04329dcfcf7856b2a2e0a28c61659b18f0 Mon Sep 17 00:00:00 2001 From: BlackGownQ <110607665+BlackGownQ@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:20:24 +0800 Subject: [PATCH] test(i18n): validate catalogs and locale behavior --- web/scripts/check-i18n.mjs | 57 +++++++++++------------ web/scripts/i18n.test.mjs | 93 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+), 30 deletions(-) create mode 100644 web/scripts/i18n.test.mjs diff --git a/web/scripts/check-i18n.mjs b/web/scripts/check-i18n.mjs index 149308b..9150d28 100644 --- a/web/scripts/check-i18n.mjs +++ b/web/scripts/check-i18n.mjs @@ -2,11 +2,14 @@ import { readFileSync, readdirSync, statSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -// Every literal t("...") / t('...') key must exist in the locale dictionary -// with the same {placeholders}. Dynamic keys (variables, template literals -// with ${}) are skipped: there is nothing to compare them against. +// English source text is the key. Check every shipped dictionary, including +// dynamic entries, while retaining the existing literal-call coverage check. const root = join(dirname(fileURLToPath(import.meta.url)), ".."); -const dict = JSON.parse(readFileSync(join(root, "src/i18n/locales/tr.json"), "utf8")); +const localeDir = join(root, "src/i18n/locales"); +const dictionaries = readdirSync(localeDir) + .filter((name) => name.endsWith(".json")) + .sort() + .map((name) => [name, JSON.parse(readFileSync(join(localeDir, name), "utf8"))]); const files = []; function walk(dir) { @@ -19,7 +22,7 @@ function walk(dir) { } walk(join(root, "src")); -const calls = new Map(); // key -> first file that uses it +const calls = new Map(); const literalCall = /(?:^|[^\w$.])t\(\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')/gm; for (const file of files) { const src = readFileSync(file, "utf8"); @@ -31,34 +34,28 @@ for (const file of files) { } function placeholders(s) { - return [...s.matchAll(/\{(\w+)\}/g)] - .map((m) => m[1]) - .sort() - .join(","); + return [...s.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort().join(","); } -const missing = []; -const mismatch = []; -for (const [key, file] of calls) { - if (!Object.prototype.hasOwnProperty.call(dict, key)) { - missing.push(`${file}: ${JSON.stringify(key)}`); - continue; - } - if (placeholders(dict[key]) !== placeholders(key)) { - mismatch.push(`${JSON.stringify(key)}: source {${placeholders(key)}} dict {${placeholders(dict[key])}}`); +const allKeys = new Set(dictionaries.flatMap(([, dict]) => Object.keys(dict))); +const errors = []; +if (!dictionaries.length) errors.push("No locale dictionaries found"); +for (const [name, dict] of dictionaries) { + for (const key of new Set([...allKeys, ...calls.keys()])) { + if (!Object.prototype.hasOwnProperty.call(dict, key)) { + errors.push(`${name}: missing ${JSON.stringify(key)} (${calls.get(key) ?? "dictionary parity"})`); + continue; + } + const value = dict[key]; + if (typeof value !== "string" || !value.trim()) { + errors.push(`${name}: empty or non-string value for ${JSON.stringify(key)}`); + } else if (placeholders(value) !== placeholders(key)) { + errors.push(`${name}: placeholder mismatch for ${JSON.stringify(key)}`); + } } + console.log(`i18n: ${calls.size} literal keys checked against ${Object.keys(dict).length} ${name} entries`); } - -if (missing.length || mismatch.length) { - if (missing.length) { - console.error(`Missing tr.json entries (${missing.length}):\n${missing.join("\n")}`); - } - if (mismatch.length) { - console.error(`Placeholder mismatches (${mismatch.length}):\n${mismatch.join("\n")}`); - } +if (errors.length) { + console.error(errors.join("\n")); process.exit(1); } - -console.log( - `i18n: ${calls.size} literal keys checked against ${Object.keys(dict).length} tr.json entries`, -); diff --git a/web/scripts/i18n.test.mjs b/web/scripts/i18n.test.mjs new file mode 100644 index 0000000..0b7e17b --- /dev/null +++ b/web/scripts/i18n.test.mjs @@ -0,0 +1,93 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import test from "node:test"; +import vm from "node:vm"; +import ts from "typescript"; + +const sourceURL = new URL("../src/i18n/index.ts", import.meta.url); +const require = createRequire(sourceURL); +const code = ts.transpileModule(readFileSync(sourceURL, "utf8"), { + compilerOptions: { module: ts.ModuleKind.CommonJS, esModuleInterop: true }, +}).outputText; + +function load({ saved = null, languages = ["en-US"], language = "en-US", blocked = false, server = false } = {}) { + const writes = []; + let reloads = 0; + const context = { exports: {}, require }; + if (!server) { + context.document = { documentElement: { lang: "en" } }; + context.window = { + localStorage: { + getItem(key) { + assert.equal(key, "artex.locale"); + if (blocked) throw new Error("Storage blocked"); + return saved; + }, + setItem(key, value) { + if (blocked) throw new Error("Storage blocked"); + writes.push([key, value]); + }, + }, + navigator: { languages, language }, + location: { reload: () => { reloads++; } }, + }; + } + vm.runInNewContext(code, context, { filename: "i18n/index.js" }); + return { api: context.exports, document: context.document, writes, reloads: () => reloads }; +} + +test("static export remains English and unknown keys fall back safely", () => { + const { api } = load({ server: true }); + assert.equal(api.locale, "en"); + assert.equal(api.intlLocale, "en-US"); + assert.equal(api.t("Unknown {value}", { value: 3 }), "Unknown 3"); +}); + +test("saved Chinese preference wins and sets the document and Intl locale", () => { + const { api, document } = load({ saved: "zh-CN", languages: ["tr-TR"] }); + assert.equal(api.locale, "zh-CN"); + assert.equal(api.intlLocale, "zh-CN"); + assert.equal(document.documentElement.lang, "zh-CN"); + assert.equal(api.t("Language"), "语言"); + assert.equal(api.t("{count} tasks", { count: 3 }), "3 个任务"); + assert.equal(api.t("Task #{id}"), "任务 #{id}"); + assert.equal(api.t("constructor"), "constructor"); + assert.equal(api.t("toString"), "toString"); + assert.equal(api.t("__proto__"), "__proto__"); + assert.equal(api.t("{count} tasks", Object.create({ count: 3 })), "{count} 个任务"); +}); + +test("Chinese browser tags, fallback languages, invalid preferences and blocked storage", () => { + for (const tag of ["zh", "zh-CN", "zh-SG", "zh-Hans-CN", "ZH-cn"]) { + assert.equal(load({ languages: [tag] }).api.locale, "zh-CN"); + } + assert.equal(load({ saved: "invalid", languages: ["fr-FR", "zh-CN"] }).api.locale, "zh-CN"); + assert.equal(load({ blocked: true, languages: ["zh-CN"] }).api.locale, "zh-CN"); + assert.equal(load({ languages: null, language: "zh-CN" }).api.locale, "zh-CN"); + assert.equal(load({ languages: [], language: "zh-CN" }).api.locale, "en"); + assert.equal(load({ languages: ["fr-FR"] }).api.locale, "en"); +}); + +test("existing English and Turkish preferences and formatting are preserved", () => { + const english = load({ saved: "en", languages: ["zh-CN"] }).api; + const turkish = load({ saved: "tr", languages: ["zh-CN"] }).api; + assert.equal(english.locale, "en"); + assert.equal(english.t("Language"), "Language"); + assert.equal(turkish.locale, "tr"); + assert.equal(turkish.intlLocale, "tr-TR"); + assert.equal(turkish.t("Language"), "Dil"); + assert.equal(load({ languages: ["tr-TR"] }).api.locale, "tr"); +}); + +test("switching persists the existing storage key and reloads once", () => { + const state = load(); + state.api.setLocale("en"); + assert.equal(state.reloads(), 0); + state.api.setLocale("zh-CN"); + assert.deepEqual(state.writes, [["artex.locale", "zh-CN"]]); + assert.equal(state.reloads(), 1); + const blocked = load({ blocked: true }); + assert.doesNotThrow(() => blocked.api.setLocale("zh-CN")); + assert.equal(blocked.reloads(), 1); +});