- runtime/i18n.ts: ICU-lite messages (placeholders as text, Intl.PluralRules plurals with exact
forms, selectordinal, select, number/date/time), fallback chains (pt-BR -> pt -> en, ar-x-fm ->
ar), X and legacy code aliases, RTL by locale, lazy catalogs, live onChange. Apostrophes are
literal except right before { } # or another apostrophe.
- runtime/i18nCheck.ts: rules for contributed catalogs (shape, keys, syntax, placeholder parity,
select options, markup/control characters, lengths). An argument English only uses to choose a
plural form may be dropped; missing plural forms are warnings; meta "allowEmpty" fragments.
- runtime/pluginI18n.ts: api.i18n bound per plugin (register/t/locale/dir/onChange/number/date/
relative/list); the UI kit's own words follow the app's language. pageLang.ts reports the
site's <html lang>. shell/messages.ts: shell-model words.
- waybetter-host i18n.rs: NativeStrings (validated plain text, caps, one-pass {name} fill, page
payload by prefix), system_locales via sys-locale; TabState.lang.
- JSON Schemas for catalogs and translator notes; npm exports waybetter/i18n, /i18n/check,
/i18n/plugin.
201 lines
12 KiB
TypeScript
201 lines
12 KiB
TypeScript
// Catalog checks for translators and CI (published as `waybetter/i18n/check`): every rule a
|
|
// contributed `locales/<bcp47>.json` must pass before review. Pure functions over parsed JSON, so
|
|
// an app's `scripts/i18n-check.mjs`, its tests and editors can share them.
|
|
//
|
|
// Errors fail the check: bad file shape, keys the source does not have, malformed ICU, placeholder
|
|
// names English does not have, a missing placeholder (except an argument English only uses to choose
|
|
// a plural form, which languages without that inflection may drop), select arguments missing an
|
|
// English option, markup or control characters (catalogs are data, never HTML), empty translations
|
|
// (unless the meta file allows it for a sentence fragment). Warnings do not fail: plural forms the
|
|
// language uses but the translation leaves to `other`, untranslated keys (they fall back to
|
|
// English) and translations much longer than the source.
|
|
|
|
import { argumentShapes, direction, normalizeLocale, parseMessage, placeholders, pluralCategories, type Catalog } from './i18n.ts';
|
|
|
|
export type CatalogIssue = { level: 'error' | 'warning'; locale: string; key?: string; message: string };
|
|
|
|
/** `allowEmpty`: a sentence fragment some languages leave empty (word order moves it elsewhere). */
|
|
export type MetaEntry = { description?: string; maxLength?: number; context?: string; allowEmpty?: boolean };
|
|
export type Meta = Record<string, MetaEntry | string>;
|
|
|
|
const KEY = /^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;
|
|
/** Markup or script-ish content: tags, entities that decode to markup, `javascript:` and friends. */
|
|
const MARKUP = /<\s*\/?\s*[a-z!?]|&(?:lt|gt|#0*60|#x0*3c);|javascript:|data:text\/html/i;
|
|
const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f--]/;
|
|
const STATUSES = new Set(['source', 'machine', 'reviewed']);
|
|
|
|
/** A long translation is fine up to this factor of the source length (plus some slack). */
|
|
const LENGTH_FACTOR = 1.8;
|
|
const LENGTH_SLACK = 16;
|
|
|
|
type Parts = ReturnType<typeof parseMessage>;
|
|
|
|
/**
|
|
* Whether `name` puts text in the message: a plain `{name}` / `{name, number}` somewhere, or a `#`
|
|
* (the number itself) in one of its own plural branches. A plural argument without either only
|
|
* chooses a form.
|
|
*/
|
|
function usedAsText(source: string, name: string): boolean {
|
|
const pound = (parts: Parts): boolean => parts.some(part => typeof part !== 'string' && (part.kind === 'pound'
|
|
|| (part.kind === 'select' && Object.values(part.options).some(pound))));
|
|
const walk = (parts: Parts): boolean => parts.some(part => {
|
|
if (typeof part === 'string' || part.kind === 'pound') return false;
|
|
if (part.kind === 'arg') return part.name === name;
|
|
if (part.kind === 'plural' && part.name === name && Object.values(part.options).some(pound)) return true;
|
|
return Object.values(part.options).some(walk);
|
|
});
|
|
return walk(parseMessage(source));
|
|
}
|
|
|
|
/** Checks the file envelope (locale, names, status, reviewers, messages map). */
|
|
export function checkShape(input: unknown, file = '?'): CatalogIssue[] {
|
|
const issues: CatalogIssue[] = [];
|
|
const err = (message: string) => issues.push({ level: 'error', locale: file, message });
|
|
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
|
err('a catalog is a JSON object');
|
|
return issues;
|
|
}
|
|
const catalog = input as Partial<Catalog> & Record<string, unknown>;
|
|
const allowed = new Set(['$schema', 'locale', 'name', 'englishName', 'dir', 'status', 'reviewers', 'fallback', 'messages']);
|
|
for (const key of Object.keys(catalog)) if (!allowed.has(key)) err(`unknown field "${key}"`);
|
|
if (typeof catalog.locale !== 'string' || normalizeLocale(catalog.locale) !== catalog.locale) err(`"locale" must be a canonical BCP 47 tag (got ${JSON.stringify(catalog.locale)})`);
|
|
if (typeof catalog.name !== 'string' || !catalog.name.trim()) err('"name" (the language\'s own name) is required');
|
|
if (typeof catalog.englishName !== 'string' || !catalog.englishName.trim()) err('"englishName" is required');
|
|
if (typeof catalog.status !== 'string' || !STATUSES.has(catalog.status)) err('"status" must be "source", "machine" or "reviewed"');
|
|
if (catalog.status === 'reviewed' && (!Array.isArray(catalog.reviewers) || catalog.reviewers.length === 0)) err('a "reviewed" catalog names its reviewers');
|
|
if (catalog.reviewers !== undefined && (!Array.isArray(catalog.reviewers) || catalog.reviewers.some(r => typeof r !== 'string' || !r.trim() || r.length > 80))) err('"reviewers" is a list of names or handles');
|
|
if (catalog.dir !== undefined && catalog.dir !== 'ltr' && catalog.dir !== 'rtl') err('"dir" must be "ltr" or "rtl"');
|
|
if (typeof catalog.locale === 'string' && catalog.dir && catalog.dir !== direction(catalog.locale)) err(`"dir" says ${catalog.dir} but ${catalog.locale} is written ${direction(catalog.locale)}`);
|
|
if (catalog.fallback !== undefined && (typeof catalog.fallback !== 'string' || normalizeLocale(catalog.fallback) !== catalog.fallback)) err('"fallback" must be a canonical BCP 47 tag');
|
|
if (!catalog.messages || typeof catalog.messages !== 'object' || Array.isArray(catalog.messages)) {
|
|
err('"messages" must be an object of key -> string');
|
|
} else {
|
|
for (const [key, value] of Object.entries(catalog.messages)) {
|
|
if (!KEY.test(key) || key.length > 96) err(`invalid key ${JSON.stringify(key)} (dotted camelCase, at most 96 characters)`);
|
|
if (typeof value !== 'string') err(`${key}: value must be a string`);
|
|
}
|
|
}
|
|
return issues;
|
|
}
|
|
|
|
/** Safety rules every message obeys, source included. */
|
|
export function checkMessageSafety(locale: string, key: string, value: string): CatalogIssue[] {
|
|
const issues: CatalogIssue[] = [];
|
|
if (MARKUP.test(value)) issues.push({ level: 'error', locale, key, message: 'markup is not allowed (catalogs are text, never HTML)' });
|
|
if (CONTROL.test(value)) issues.push({ level: 'error', locale, key, message: 'control or bidi-override characters are not allowed' });
|
|
if (value.length > 2000) issues.push({ level: 'error', locale, key, message: 'message is longer than 2000 characters' });
|
|
try {
|
|
parseMessage(value);
|
|
} catch (error) {
|
|
issues.push({ level: 'error', locale, key, message: `invalid message syntax: ${error instanceof Error ? error.message : String(error)}` });
|
|
}
|
|
return issues;
|
|
}
|
|
|
|
/**
|
|
* Checks one translated catalog against the source messages: extra keys, placeholder parity,
|
|
* plural categories, safety, untranslated and overlong messages.
|
|
*/
|
|
export function checkCatalog(catalog: Catalog, source: Record<string, string>, meta: Meta = {}): CatalogIssue[] {
|
|
const issues: CatalogIssue[] = [];
|
|
const locale = catalog.locale;
|
|
const push = (level: CatalogIssue['level'], key: string | undefined, message: string) => issues.push({ level, locale, key, message });
|
|
const categories = new Set(pluralCategories(locale));
|
|
const ordinals = new Set(pluralCategories(locale, true));
|
|
let missing = 0;
|
|
for (const [key, value] of Object.entries(catalog.messages)) {
|
|
const english = source[key];
|
|
if (english === undefined) {
|
|
push('error', key, 'key is not in the source catalog (removed or misspelled)');
|
|
continue;
|
|
}
|
|
const safety = checkMessageSafety(locale, key, value);
|
|
issues.push(...safety);
|
|
if (safety.some(issue => issue.level === 'error')) continue;
|
|
const entry = meta[key];
|
|
const allowEmpty = typeof entry === 'object' && entry.allowEmpty === true;
|
|
if (!value.trim() && english.trim() && !allowEmpty) push('error', key, 'empty translation (remove the key to fall back to English)');
|
|
const want = placeholders(english);
|
|
const have = placeholders(value);
|
|
const sourceShapes = argumentShapes(english);
|
|
// An argument English only uses to pick a plural form ("Download {count, plural, one {it} other
|
|
// {them}}") may be dropped by a language that does not inflect there; every other placeholder
|
|
// carries text the reader needs and is required.
|
|
const pluralOnly = (name: string) => {
|
|
const shape = sourceShapes[name];
|
|
return !!shape && shape.kind !== 'select' && !usedAsText(english, name);
|
|
};
|
|
const missingNames = want.filter(name => !have.includes(name) && !pluralOnly(name));
|
|
const extraNames = have.filter(name => !want.includes(name));
|
|
if (missingNames.length) push('error', key, `missing placeholder(s) ${missingNames.map(n => `{${n}}`).join(', ')}`);
|
|
if (extraNames.length) push('error', key, `unknown placeholder(s) ${extraNames.map(n => `{${n}}`).join(', ')}`);
|
|
const shapes = argumentShapes(value);
|
|
for (const [name, shape] of Object.entries(shapes)) {
|
|
const expected = sourceShapes[name];
|
|
if (expected && expected.kind !== shape.kind) {
|
|
push('error', key, `{${name}} is a ${expected.kind} in English but a ${shape.kind} here`);
|
|
continue;
|
|
}
|
|
if (shape.kind === 'select') {
|
|
for (const option of expected?.options ?? []) {
|
|
if (!shape.options.includes(option)) push('error', key, `{${name}, select} lacks the "${option}" option`);
|
|
}
|
|
continue;
|
|
}
|
|
// A form the translation leaves out falls back to its `other` branch, which is often right
|
|
// (an invariable word, an abbreviation, `=1` already covering "one"): a warning for review.
|
|
const needed = shape.kind === 'selectordinal' ? ordinals : categories;
|
|
for (const category of needed) {
|
|
if (!shape.options.includes(category)) push('warning', key, `{${name}, ${shape.kind}} has no "${category}" form (${locale} uses it; "other" is shown)`);
|
|
}
|
|
for (const option of shape.options) {
|
|
if (!option.startsWith('=') && !needed.has(option as Intl.LDMLPluralRule)) push('warning', key, `{${name}, ${shape.kind}} has a "${option}" form ${locale} never uses`);
|
|
}
|
|
}
|
|
const maxLength = typeof entry === 'object' ? entry.maxLength : undefined;
|
|
const limit = maxLength ?? Math.round(english.length * LENGTH_FACTOR + LENGTH_SLACK);
|
|
if (value.length > limit) push(maxLength ? 'error' : 'warning', key, `translation is ${value.length} characters (${maxLength ? 'limit' : 'English is'} ${maxLength ?? english.length})`);
|
|
}
|
|
if (catalog.status !== 'source' && !catalog.fallback) {
|
|
for (const key of Object.keys(source)) if (!(key in catalog.messages)) missing += 1;
|
|
if (missing) push('warning', undefined, `${missing} of ${Object.keys(source).length} messages untranslated (English is shown)`);
|
|
}
|
|
return issues;
|
|
}
|
|
|
|
/** Checks the source catalog itself: safety, syntax, and that every key is described in the meta file. */
|
|
export function checkSource(catalog: Catalog, meta: Meta = {}): CatalogIssue[] {
|
|
const issues: CatalogIssue[] = [];
|
|
for (const [key, value] of Object.entries(catalog.messages)) issues.push(...checkMessageSafety(catalog.locale, key, value));
|
|
for (const key of Object.keys(meta)) {
|
|
if (!(key in catalog.messages)) issues.push({ level: 'error', locale: catalog.locale, key, message: 'described in the meta file but not in the source catalog' });
|
|
}
|
|
return issues;
|
|
}
|
|
|
|
/** Share of source keys a catalog translates (0..1), following its `fallback` catalog when given. */
|
|
export function coverage(catalog: Catalog, source: Record<string, string>, fallback?: Catalog): number {
|
|
const keys = Object.keys(source);
|
|
if (!keys.length) return 1;
|
|
const done = keys.filter(key => key in catalog.messages || (fallback ? key in fallback.messages : false)).length;
|
|
return done / keys.length;
|
|
}
|
|
|
|
/** TypeScript source for a key union and per-key parameter types, generated from source messages. */
|
|
export function generateKeyTypes(source: Record<string, string>, typeName = 'MessageKey'): string {
|
|
const keys = Object.keys(source).sort();
|
|
const lines = [
|
|
'// Generated from the English source catalog. Do not edit by hand.',
|
|
`export type ${typeName} =`,
|
|
...keys.map((key, index) => ` | ${JSON.stringify(key)}${index === keys.length - 1 ? ';' : ''}`),
|
|
'',
|
|
`export type ${typeName}Params = {`,
|
|
];
|
|
for (const key of keys) {
|
|
let names: string[] = [];
|
|
try { names = placeholders(source[key]!); } catch { names = []; }
|
|
lines.push(` ${JSON.stringify(key)}: ${names.length ? `{ ${names.map(name => `${name}: string | number | Date`).join('; ')} }` : 'undefined'};`);
|
|
}
|
|
lines.push('};', '');
|
|
return lines.join('\n');
|
|
}
|