Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
@@ -6,6 +6,7 @@
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./locales": "./src/locales.ts",
|
||||
"./intl": "./src/intl/index.ts",
|
||||
"./icu": "./src/icu/index.ts",
|
||||
"./useTranslate": "./src/useTranslate.ts"
|
||||
@@ -16,10 +17,14 @@
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"i18next": "^23.16.3",
|
||||
"intl-messageformat": "^10.7.16"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"i18next": "^24.2.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.0.0",
|
||||
"i18next": "24.2.3",
|
||||
"typescript": "^5.3.2",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { anredeVariants, defaultAnrede, effectiveLng, formalLngs, isAnrede, supportedLocales } from "./index.js";
|
||||
import { createInstance } from "i18next";
|
||||
import { anredeVariants, defaultAnrede, effectiveLng, fallbackLng, formalLngs, isAnrede, supportedLocales } from "./index.js";
|
||||
|
||||
// Coverage gap: the formality (Anrede) axis — `isAnrede` and `effectiveLng`
|
||||
// (index.ts) had no direct test. This is the du/sie switch that maps a tenant's
|
||||
@@ -15,7 +16,7 @@ describe("anrede axis constants", () => {
|
||||
|
||||
test("derives a formal language variant for every supported locale", () => {
|
||||
expect(formalLngs).toEqual(supportedLocales.map((locale) => `${locale}-formal`));
|
||||
expect(formalLngs).toEqual(["de-formal", "en-formal"]);
|
||||
expect(formalLngs).toEqual(["de-formal", "en-formal", "pl-formal", "ru-formal", "uk-formal", "hu-formal"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -52,3 +53,27 @@ describe("effectiveLng", () => {
|
||||
expect(effectiveLng("xx")).toBe("xx");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formal catalog fallback", () => {
|
||||
test.each(["pl", "ru", "uk", "hu"] as const)("falls back from %s-formal through its matching base locale before German", async (locale) => {
|
||||
const formalLocale = `${locale}-formal`;
|
||||
const instance = createInstance({
|
||||
fallbackLng,
|
||||
initImmediate: false,
|
||||
lng: formalLocale,
|
||||
ns: ["translations"],
|
||||
defaultNS: "translations",
|
||||
resources: {
|
||||
de: { translations: { germanOnly: "Deutsch", baseOnly: "Deutsch" } },
|
||||
[locale]: { translations: { baseOnly: `${locale}:informal` } },
|
||||
[formalLocale]: { translations: { formalOnly: `${locale}:formal` } },
|
||||
},
|
||||
});
|
||||
await instance.init();
|
||||
|
||||
expect(instance.t("formalOnly")).toBe(`${locale}:formal`);
|
||||
expect(instance.t("baseOnly")).toBe(`${locale}:informal`);
|
||||
expect(instance.t("germanOnly")).toBe("Deutsch");
|
||||
expect(instance.t("missingKey")).toBe("missingKey");
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,18 @@ describe("formatIcu (plurals)", () => {
|
||||
expect(formatIcu(message, { count: 5 }, { locale: "pl-PL" })).toBe("5 elementów");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["pl-PL", ["many", "one", "few", "many", "many", "other"]],
|
||||
["ru-RU", ["many", "one", "few", "many", "one", "other"]],
|
||||
["uk-UA", ["many", "one", "few", "many", "one", "other"]],
|
||||
["hu-HU", ["other", "one", "other", "other", "other", "other"]],
|
||||
] as const)("selects CLDR categories for %s at 0, 1, 2, 5, 21 and decimals", (locale, expected) => {
|
||||
const message = "{count, plural, one {one} few {few} many {many} other {other}}";
|
||||
const values = [0, 1, 2, 5, 21, 1.5];
|
||||
|
||||
expect(values.map((count) => formatIcu(message, { count }, { locale }))).toEqual(expected);
|
||||
});
|
||||
|
||||
test("supports select rules", () => {
|
||||
const message = "{role, select, admin {Administrator} member {Member} other {Guest}}";
|
||||
expect(formatIcu(message, { role: "admin" }, { locale: "en-US" })).toBe("Administrator");
|
||||
|
||||
@@ -3,7 +3,17 @@ import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { checkI18nParity } from "../../../scripts/i18n-check.ts";
|
||||
import { defaultLocale, getDirection, i18nConfig, i18nNamespaces, isRTL, isSupportedLocale, supportedLocales } from "./index.js";
|
||||
import {
|
||||
catalogReadyLocales,
|
||||
defaultLocale,
|
||||
fallbackLng,
|
||||
getDirection,
|
||||
i18nConfig,
|
||||
i18nNamespaces,
|
||||
isRTL,
|
||||
isSupportedLocale,
|
||||
supportedLocales,
|
||||
} from "./index.js";
|
||||
|
||||
type JsonValue = boolean | null | number | string | JsonValue[] | { [key: string]: JsonValue };
|
||||
type JsonObject = { [key: string]: JsonValue };
|
||||
@@ -24,20 +34,59 @@ function collectLeafKeys(value: JsonValue, prefix = ""): string[] {
|
||||
.sort();
|
||||
}
|
||||
|
||||
function collectStringEntries(value: JsonValue, prefix = ""): Array<readonly [string, string]> {
|
||||
if (typeof value === "string") return prefix ? [[prefix, value]] : [];
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return [];
|
||||
|
||||
return Object.entries(value)
|
||||
.flatMap(([key, nestedValue]) => collectStringEntries(nestedValue, prefix ? `${prefix}.${key}` : key))
|
||||
.sort(([left], [right]) => left.localeCompare(right));
|
||||
}
|
||||
|
||||
describe("@hivegrid/i18n", () => {
|
||||
test("keeps German as the default and fallback locale", () => {
|
||||
expect(defaultLocale).toBe("de");
|
||||
expect(i18nConfig.fallbackLng).toBe("de");
|
||||
expect(i18nConfig.fallbackLng).toEqual(fallbackLng);
|
||||
});
|
||||
|
||||
test("keeps German and English as maintained locale set", () => {
|
||||
expect(supportedLocales).toEqual(["de", "en"]);
|
||||
expect(i18nConfig.supportedLngs).toEqual(["de", "en"]);
|
||||
test("registers the six product locales", () => {
|
||||
expect(supportedLocales).toEqual(["de", "en", "pl", "ru", "uk", "hu"]);
|
||||
expect(i18nConfig.supportedLngs).toEqual(catalogReadyLocales);
|
||||
});
|
||||
|
||||
test("leaves interpolated values unescaped so React escapes them exactly once", async () => {
|
||||
// Regression guard: with i18next's default escaping a slash-bearing value
|
||||
// renders literally as `Europe/Berlin` / `https://host`.
|
||||
expect(i18nConfig.interpolation?.escapeValue).toBe(false);
|
||||
|
||||
const { createInstance } = await import("i18next");
|
||||
const instance = createInstance({
|
||||
...i18nConfig,
|
||||
lng: "de",
|
||||
initImmediate: false,
|
||||
resources: {
|
||||
de: {
|
||||
translations: {
|
||||
zone: "Aufgaben in {{timeZone}}.",
|
||||
host: "Zielhost: {{value}}",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
await instance.init();
|
||||
|
||||
expect(instance.t("zone", { timeZone: "Europe/Berlin" })).toBe("Aufgaben in Europe/Berlin.");
|
||||
expect(instance.t("host", { value: "https://staging-mcp.hivegrid.de" })).toBe("Zielhost: https://staging-mcp.hivegrid.de");
|
||||
});
|
||||
|
||||
test("checks supported locales", () => {
|
||||
expect(isSupportedLocale("de")).toBe(true);
|
||||
expect(isSupportedLocale("en")).toBe(true);
|
||||
expect(isSupportedLocale("pl")).toBe(true);
|
||||
expect(isSupportedLocale("ru")).toBe(true);
|
||||
expect(isSupportedLocale("uk")).toBe(true);
|
||||
expect(isSupportedLocale("hu")).toBe(true);
|
||||
expect(isSupportedLocale("ua")).toBe(false);
|
||||
expect(isSupportedLocale("fr")).toBe(false);
|
||||
});
|
||||
|
||||
@@ -50,6 +99,49 @@ describe("@hivegrid/i18n", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("provides labels for every selectable product locale", () => {
|
||||
for (const locale of catalogReadyLocales) {
|
||||
const translations = readLocaleNamespace(locale, "translations");
|
||||
const labels = (translations.shared as JsonObject).locales as JsonObject;
|
||||
|
||||
expect(Object.keys(labels).sort(), locale).toEqual([...supportedLocales].sort());
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["pl", "ru", "uk", "hu"] as const)("renders representative %s base and formal catalog values without raw keys or cross-language fallback", async (locale) => {
|
||||
const { createInstance } = await import("i18next");
|
||||
const formalLocale = `${locale}-formal`;
|
||||
const resources = Object.fromEntries(
|
||||
["de", "en", locale, formalLocale].map((language) => [
|
||||
language,
|
||||
Object.fromEntries(i18nNamespaces.map((namespace) => [namespace, readLocaleNamespace(language, namespace)])),
|
||||
])
|
||||
);
|
||||
const instance = createInstance({
|
||||
...i18nConfig,
|
||||
supportedLngs: [...catalogReadyLocales, formalLocale],
|
||||
initImmediate: false,
|
||||
lng: locale,
|
||||
resources,
|
||||
});
|
||||
await instance.init();
|
||||
|
||||
for (const namespace of i18nNamespaces) {
|
||||
const baseEntries = collectStringEntries(readLocaleNamespace(locale, namespace)).slice(0, 25);
|
||||
const formalEntries = new Map(collectStringEntries(readLocaleNamespace(formalLocale, namespace)));
|
||||
const baseT = instance.getFixedT(locale, namespace);
|
||||
const formalT = instance.getFixedT(formalLocale, namespace);
|
||||
|
||||
expect(baseEntries.length, `${locale}/${namespace}`).toBeGreaterThan(0);
|
||||
for (const [key, value] of baseEntries) {
|
||||
expect(baseT(key), `${locale}/${namespace}:${key}`).toBe(value);
|
||||
expect(baseT(key), `${locale}/${namespace}:${key}`).not.toBe(key);
|
||||
expect(formalT(key), `${formalLocale}/${namespace}:${key}`).toBe(formalEntries.get(key) ?? value);
|
||||
expect(formalT(key), `${formalLocale}/${namespace}:${key}`).not.toBe(key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps static UI translation calls backed by locale entries", () => {
|
||||
const result = checkI18nParity({ cwd: path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../") });
|
||||
const missingKeysWithoutFallback = result.issues.filter((issue) => issue.type === "missing-source-key" && issue.fallback === "no-fallback");
|
||||
|
||||
@@ -1,8 +1,26 @@
|
||||
import type { InitOptions } from "i18next";
|
||||
|
||||
export const defaultLocale = "de";
|
||||
export const supportedLocales = ["de", "en"];
|
||||
export type SupportedLocale = (typeof supportedLocales)[number];
|
||||
import { catalogReadyLocales, fallbackLng, supportedLocales } from "./locales.js";
|
||||
|
||||
export {
|
||||
EnabledLocalesConfigError,
|
||||
catalogReadyLocales,
|
||||
defaultEnabledLocales,
|
||||
defaultLocale,
|
||||
fallbackLng,
|
||||
formalLngs,
|
||||
isSupportedLocale,
|
||||
localeReleaseStages,
|
||||
normalizeLocaleCandidate,
|
||||
parseEnabledLocales,
|
||||
resolveEnabledLocale,
|
||||
supportedLocales,
|
||||
type EnabledLocalesIssue,
|
||||
type EnabledLocalesIssueCode,
|
||||
type FormalLocale,
|
||||
type ResolveEnabledLocaleInput,
|
||||
type SupportedLocale,
|
||||
} from "./locales.js";
|
||||
|
||||
// Namespace order:
|
||||
// - `translations` is the legacy single-file namespace that still holds the
|
||||
@@ -16,34 +34,37 @@ export const i18nNamespaces = ["translations", "errors", "mail", "common", "sett
|
||||
export type I18nNamespace = (typeof i18nNamespaces)[number];
|
||||
|
||||
export const i18nConfig = {
|
||||
supportedLngs: supportedLocales,
|
||||
fallbackLng: defaultLocale,
|
||||
supportedLngs: catalogReadyLocales,
|
||||
fallbackLng,
|
||||
defaultNS: "translations",
|
||||
ns: [...i18nNamespaces],
|
||||
interpolation: {
|
||||
// React escapes every text node it renders, so i18next must not escape
|
||||
// interpolated values a second time. With i18next's default
|
||||
// (`escapeValue: true`) any value containing HTML-relevant characters is
|
||||
// turned into entities that React then renders literally — a time zone
|
||||
// interpolates as `Europe/Berlin` and a URL as `https://…`.
|
||||
// Values that legitimately reach `dangerouslySetInnerHTML` are sanitized
|
||||
// explicitly at those call sites (see `app/utils/html-sanitizer.ts`).
|
||||
escapeValue: false,
|
||||
},
|
||||
react: {
|
||||
useSuspense: false,
|
||||
},
|
||||
} satisfies InitOptions;
|
||||
|
||||
export function isSupportedLocale(locale: string | undefined): locale is SupportedLocale {
|
||||
return Boolean(locale && supportedLocales.includes(locale));
|
||||
}
|
||||
|
||||
// Formality (Anrede) axis — orthogonal to locale. "du" is the base language
|
||||
// (existing keys), "sie" resolves to the "<locale>-formal" i18next variant
|
||||
// which holds only the formal overrides and falls back to the base locale via
|
||||
// the existing `fallbackLng` ("de"). This keeps the change purely additive:
|
||||
// (existing keys), "sie" resolves to the "<locale>-formal" i18next variant.
|
||||
// Sparse overrides fall back through the matching informal locale before
|
||||
// German. This keeps the change purely additive:
|
||||
// with the default "du" the effective language is the plain locale, so existing
|
||||
// behaviour is byte-identical. Toggling a tenant to "sie" switches the
|
||||
// effective language to "de-formal"/"en-formal"; any key without a formal
|
||||
// override transparently falls back to the informal text.
|
||||
// effective language to "<locale>-formal"; any key without a formal override
|
||||
// transparently falls back to the matching informal text.
|
||||
export const anredeVariants = ["du", "sie"] as const;
|
||||
export type Anrede = (typeof anredeVariants)[number];
|
||||
export const defaultAnrede: Anrede = "du";
|
||||
|
||||
/** Formal language variants for every supported locale ("de-formal", "en-formal"). */
|
||||
export const formalLngs = supportedLocales.map((locale) => `${locale}-formal`);
|
||||
|
||||
export function isAnrede(value: string | undefined): value is Anrede {
|
||||
return Boolean(value && (anredeVariants as readonly string[]).includes(value));
|
||||
}
|
||||
@@ -53,7 +74,7 @@ export function effectiveLng(locale: string, anrede: Anrede = defaultAnrede): st
|
||||
return anrede === "sie" ? `${locale}-formal` : locale;
|
||||
}
|
||||
|
||||
const ltrLocales = new Set<string>(["de", "en"]);
|
||||
const ltrLocales = new Set<string>(supportedLocales);
|
||||
const rtlLocales = new Set<string>(["ar", "he", "fa", "ur"]);
|
||||
|
||||
export type TextDirection = "ltr" | "rtl";
|
||||
@@ -79,10 +100,12 @@ export {
|
||||
formatPercent,
|
||||
formatCompactNumber,
|
||||
formatCurrency,
|
||||
formatCurrencyAmount,
|
||||
formatDate,
|
||||
formatRelativeTime,
|
||||
formatList,
|
||||
type FormatNumberOptions,
|
||||
type CurrencyAmount,
|
||||
type FormatCurrencyOptions,
|
||||
type FormatDateOptions,
|
||||
type FormatRelativeTimeOptions,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { formatCurrency } from "./currency.js";
|
||||
import { formatCurrency, formatCurrencyAmount } from "./currency.js";
|
||||
|
||||
// String comparisons normalise whitespace because the ICU output uses U+00A0
|
||||
// (NBSP) between digits and the currency symbol — depending on Node/ICU
|
||||
@@ -26,4 +26,31 @@ describe("formatCurrency", () => {
|
||||
test("renders JPY without decimals by default", () => {
|
||||
expect(normalise(formatCurrency(1500, { locale: "ja-JP", currency: "JPY" }))).toBe("¥1,500");
|
||||
});
|
||||
|
||||
test.each([
|
||||
[0, "0,00 €"],
|
||||
[-1_234.5, "-1.234,50 €"],
|
||||
[10_000, "10.000,00 €"],
|
||||
["12345678901234567890.55", "12.345.678.901.234.567.890,55 €"],
|
||||
[{ toString: () => "10000.005" }, "10.000,01 €"],
|
||||
])("formats exact decimal-like EUR amounts (%o)", (value, expected) => {
|
||||
expect(
|
||||
normalise(
|
||||
formatCurrencyAmount(value, {
|
||||
locale: "de-DE",
|
||||
currency: "EUR",
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}) ?? "",
|
||||
),
|
||||
).toBe(expected);
|
||||
});
|
||||
|
||||
test("returns null for missing or invalid amounts", () => {
|
||||
const options = { locale: "de-DE", currency: "EUR" };
|
||||
expect(formatCurrencyAmount(null, options)).toBeNull();
|
||||
expect(formatCurrencyAmount("", options)).toBeNull();
|
||||
expect(formatCurrencyAmount("not-a-number", options)).toBeNull();
|
||||
expect(formatCurrencyAmount(Number.POSITIVE_INFINITY, options)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -12,9 +12,41 @@ export type FormatCurrencyOptions = {
|
||||
currencyDisplay?: Intl.NumberFormatOptions["currencyDisplay"];
|
||||
};
|
||||
|
||||
export type CurrencyAmount = number | bigint | string | { toString(): string };
|
||||
|
||||
const DECIMAL_AMOUNT_PATTERN = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
|
||||
|
||||
const currencyFormatters = new Map<string, Intl.NumberFormat>();
|
||||
|
||||
export function formatCurrency(value: number, options: FormatCurrencyOptions): string {
|
||||
function getCurrencyFormatter(options: FormatCurrencyOptions): Intl.NumberFormat {
|
||||
const { locale, currency, ...rest } = options;
|
||||
return getCachedFormatter(currencyFormatters, locale, { style: "currency", currency, ...rest }, (formatterLocale, formatterOptions) => new Intl.NumberFormat(formatterLocale, formatterOptions)).format(value);
|
||||
return getCachedFormatter(currencyFormatters, locale, { style: "currency", currency, ...rest }, (formatterLocale, formatterOptions) => new Intl.NumberFormat(formatterLocale, formatterOptions));
|
||||
}
|
||||
|
||||
function normalizeCurrencyAmount(value: CurrencyAmount | null | undefined): number | bigint | string | null {
|
||||
if (value == null) return null;
|
||||
if (typeof value === "number") return Number.isFinite(value) ? value : null;
|
||||
if (typeof value === "bigint") return value;
|
||||
|
||||
let raw: string;
|
||||
try {
|
||||
raw = (typeof value === "string" ? value : value.toString()).trim();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return raw && DECIMAL_AMOUNT_PATTERN.test(raw) ? raw : null;
|
||||
}
|
||||
|
||||
export function formatCurrency(value: number, options: FormatCurrencyOptions): string {
|
||||
return getCurrencyFormatter(options).format(value);
|
||||
}
|
||||
|
||||
export function formatCurrencyAmount(value: CurrencyAmount | null | undefined, options: FormatCurrencyOptions): string | null {
|
||||
const normalized = normalizeCurrencyAmount(value);
|
||||
if (normalized == null) return null;
|
||||
|
||||
// ECMA-402 accepts exact decimal strings even though TypeScript's older Intl
|
||||
// declaration only exposes number/bigint. Keeping the string avoids losing
|
||||
// cents for large database Decimal values.
|
||||
return getCurrencyFormatter(options).format(normalized as number | bigint);
|
||||
}
|
||||
@@ -3,6 +3,6 @@
|
||||
// render exactly what the client sees.
|
||||
|
||||
export { formatNumber, formatPercent, formatCompactNumber, type FormatNumberOptions } from "./number.js";
|
||||
export { formatCurrency, type FormatCurrencyOptions } from "./currency.js";
|
||||
export { formatCurrency, formatCurrencyAmount, type CurrencyAmount, type FormatCurrencyOptions } from "./currency.js";
|
||||
export { formatDate, formatRelativeTime, type FormatDateOptions, type FormatRelativeTimeOptions } from "./date.js";
|
||||
export { formatList, type FormatListOptions } from "./list.js";
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
EnabledLocalesConfigError,
|
||||
defaultEnabledLocales,
|
||||
fallbackLng,
|
||||
normalizeLocaleCandidate,
|
||||
parseEnabledLocales,
|
||||
resolveEnabledLocale,
|
||||
supportedLocales,
|
||||
} from "./locales.js";
|
||||
|
||||
describe("locale catalog and release gate", () => {
|
||||
it("publishes the six catalog locales and defaults runtime activation to de,en", () => {
|
||||
expect(supportedLocales).toEqual(["de", "en", "pl", "ru", "uk", "hu"]);
|
||||
expect(parseEnabledLocales(undefined)).toEqual(defaultEnabledLocales);
|
||||
});
|
||||
|
||||
it("allows catalog-ready review locales outside production", () => {
|
||||
expect(parseEnabledLocales("de,en,pl", { allowReviewLocales: true })).toEqual(["de", "en", "pl"]);
|
||||
expect(() => parseEnabledLocales("de,en,pl")).toThrowError(EnabledLocalesConfigError);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["de,en,en", "duplicate"],
|
||||
["de,en,fr", "unknown"],
|
||||
["de,,en", "empty-value"],
|
||||
["", "empty-value"],
|
||||
[" ", "empty-value"],
|
||||
["en", "missing-default"],
|
||||
["de,PL", "unknown"],
|
||||
])("rejects invalid configuration %s", (value, code) => {
|
||||
try {
|
||||
parseEnabledLocales(value, { allowReviewLocales: true });
|
||||
throw new Error("expected locale configuration to fail");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(EnabledLocalesConfigError);
|
||||
expect((error as EnabledLocalesConfigError).issues).toContainEqual(expect.objectContaining({ code }));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("enabled locale resolution", () => {
|
||||
const enabled = ["de", "en", "pl", "uk"] as const;
|
||||
|
||||
it("normalizes regional and formal variants to their base locale", () => {
|
||||
expect(normalizeLocaleCandidate("pl-PL")).toBe("pl");
|
||||
expect(normalizeLocaleCandidate("uk_UA")).toBe("uk");
|
||||
expect(normalizeLocaleCandidate("hu-formal")).toBe("hu");
|
||||
expect(normalizeLocaleCandidate("ua")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("uses enabled user then tenant then weighted Accept-Language and finally German", () => {
|
||||
expect(resolveEnabledLocale({ enabledLocales: enabled, userLocale: "pl-PL", tenantLocale: "uk", acceptLanguage: "en" })).toBe("pl");
|
||||
expect(resolveEnabledLocale({ enabledLocales: enabled, userLocale: "ru", tenantLocale: "uk-UA", acceptLanguage: "en" })).toBe("uk");
|
||||
expect(resolveEnabledLocale({ enabledLocales: enabled, userLocale: "ru", tenantLocale: "hu", cookieLocale: "en", acceptLanguage: "pl" })).toBe("en");
|
||||
expect(resolveEnabledLocale({ enabledLocales: enabled, userLocale: "ru", tenantLocale: "hu", acceptLanguage: "ru;q=1,en;q=0.8,pl;q=0.9" })).toBe("pl");
|
||||
expect(resolveEnabledLocale({ enabledLocales: enabled, userLocale: "ru", tenantLocale: "hu", acceptLanguage: "ru;q=0,*;q=1" })).toBe("de");
|
||||
});
|
||||
|
||||
it("never lets a disabled cookie, preference, or browser header activate a locale", () => {
|
||||
expect(resolveEnabledLocale({ enabledLocales: ["de", "en"], userLocale: "pl", tenantLocale: "uk", acceptLanguage: "ru,hu;q=0.9" })).toBe("de");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formal fallback", () => {
|
||||
it("always falls back through the matching informal catalog before German", () => {
|
||||
expect(fallbackLng["pl-formal"]).toEqual(["pl", "de"]);
|
||||
expect(fallbackLng["ru-formal"]).toEqual(["ru", "de"]);
|
||||
expect(fallbackLng["uk-formal"]).toEqual(["uk", "de"]);
|
||||
expect(fallbackLng["hu-formal"]).toEqual(["hu", "de"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
export const defaultLocale = "de" as const;
|
||||
export const supportedLocales = ["de", "en", "pl", "ru", "uk", "hu"] as const;
|
||||
export type SupportedLocale = (typeof supportedLocales)[number];
|
||||
|
||||
// This registry advances with the atomic per-language catalog commits. A
|
||||
// supported locale cannot be enabled until every namespace and QA artifact for
|
||||
// that locale is present in the same commit.
|
||||
export const catalogReadyLocales = ["de", "en", "pl", "ru", "uk", "hu"] as const satisfies readonly SupportedLocale[];
|
||||
|
||||
export const defaultEnabledLocales = ["de", "en"] as const satisfies readonly SupportedLocale[];
|
||||
|
||||
export const localeReleaseStages = {
|
||||
de: "production",
|
||||
en: "production",
|
||||
pl: "review",
|
||||
ru: "review",
|
||||
uk: "review",
|
||||
hu: "review",
|
||||
} as const satisfies Record<SupportedLocale, "production" | "review">;
|
||||
|
||||
export type EnabledLocalesIssueCode = "empty-value" | "duplicate" | "unknown" | "missing-catalog" | "missing-default" | "review-only";
|
||||
|
||||
export type EnabledLocalesIssue = {
|
||||
code: EnabledLocalesIssueCode;
|
||||
value?: string;
|
||||
};
|
||||
|
||||
export class EnabledLocalesConfigError extends Error {
|
||||
readonly issues: readonly EnabledLocalesIssue[];
|
||||
|
||||
constructor(issues: readonly EnabledLocalesIssue[]) {
|
||||
const details = issues.map((issue) => (issue.value ? `${issue.code}:${issue.value}` : issue.code)).join(", ");
|
||||
super(`I18N_ENABLED_LOCALES is invalid (${details}). Use unique comma-separated locale codes from: ${supportedLocales.join(",")}.`);
|
||||
this.name = "EnabledLocalesConfigError";
|
||||
this.issues = [...issues];
|
||||
}
|
||||
}
|
||||
|
||||
export function isSupportedLocale(locale: string | undefined): locale is SupportedLocale {
|
||||
return Boolean(locale && (supportedLocales as readonly string[]).includes(locale));
|
||||
}
|
||||
|
||||
export function parseEnabledLocales(
|
||||
value: string | undefined,
|
||||
options: { allowReviewLocales?: boolean } = {}
|
||||
): readonly SupportedLocale[] {
|
||||
const configured = value === undefined ? [...defaultEnabledLocales] : value.split(",").map((part) => part.trim());
|
||||
const issues: EnabledLocalesIssue[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const locale of configured) {
|
||||
if (!locale) {
|
||||
issues.push({ code: "empty-value" });
|
||||
continue;
|
||||
}
|
||||
if (seen.has(locale)) {
|
||||
issues.push({ code: "duplicate", value: locale });
|
||||
continue;
|
||||
}
|
||||
seen.add(locale);
|
||||
if (!isSupportedLocale(locale)) {
|
||||
issues.push({ code: "unknown", value: locale });
|
||||
continue;
|
||||
}
|
||||
if (!(catalogReadyLocales as readonly SupportedLocale[]).includes(locale)) {
|
||||
issues.push({ code: "missing-catalog", value: locale });
|
||||
continue;
|
||||
}
|
||||
if (localeReleaseStages[locale] === "review" && options.allowReviewLocales !== true) {
|
||||
issues.push({ code: "review-only", value: locale });
|
||||
}
|
||||
}
|
||||
|
||||
if (!seen.has(defaultLocale)) {
|
||||
issues.push({ code: "missing-default", value: defaultLocale });
|
||||
}
|
||||
if (issues.length > 0) {
|
||||
throw new EnabledLocalesConfigError(issues);
|
||||
}
|
||||
|
||||
return configured as SupportedLocale[];
|
||||
}
|
||||
|
||||
export function normalizeLocaleCandidate(value: string | null | undefined): SupportedLocale | undefined {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
if (!normalized) return undefined;
|
||||
const base = normalized.endsWith("-formal") ? normalized.slice(0, -"-formal".length) : normalized.split(/[-_]/u)[0];
|
||||
return isSupportedLocale(base) ? base : undefined;
|
||||
}
|
||||
|
||||
function parseAcceptLanguage(value: string | null | undefined): SupportedLocale[] {
|
||||
if (!value) return [];
|
||||
return value
|
||||
.split(",")
|
||||
.map((entry, index) => {
|
||||
const [tag, ...parameters] = entry.trim().split(";");
|
||||
const qualityParameter = parameters.map((parameter) => parameter.trim()).find((parameter) => parameter.startsWith("q="));
|
||||
const parsedQuality = qualityParameter ? Number(qualityParameter.slice(2)) : 1;
|
||||
return {
|
||||
locale: tag === "*" ? undefined : normalizeLocaleCandidate(tag),
|
||||
quality: Number.isFinite(parsedQuality) && parsedQuality >= 0 && parsedQuality <= 1 ? parsedQuality : 0,
|
||||
index,
|
||||
};
|
||||
})
|
||||
.filter((entry): entry is { locale: SupportedLocale; quality: number; index: number } => Boolean(entry.locale) && entry.quality > 0)
|
||||
.sort((left, right) => right.quality - left.quality || left.index - right.index)
|
||||
.map((entry) => entry.locale);
|
||||
}
|
||||
|
||||
export type ResolveEnabledLocaleInput = {
|
||||
enabledLocales: readonly SupportedLocale[];
|
||||
userLocale?: string | null;
|
||||
tenantLocale?: string | null;
|
||||
cookieLocale?: string | null;
|
||||
acceptLanguage?: string | null;
|
||||
};
|
||||
|
||||
export function resolveEnabledLocale(input: ResolveEnabledLocaleInput): SupportedLocale {
|
||||
const enabled = new Set<SupportedLocale>(input.enabledLocales);
|
||||
const preferred = [
|
||||
normalizeLocaleCandidate(input.userLocale),
|
||||
normalizeLocaleCandidate(input.tenantLocale),
|
||||
normalizeLocaleCandidate(input.cookieLocale),
|
||||
...parseAcceptLanguage(input.acceptLanguage),
|
||||
];
|
||||
for (const locale of preferred) {
|
||||
if (locale && enabled.has(locale)) return locale;
|
||||
}
|
||||
return defaultLocale;
|
||||
}
|
||||
|
||||
export const formalLngs = supportedLocales.map((locale) => `${locale}-formal` as const);
|
||||
export type FormalLocale = (typeof formalLngs)[number];
|
||||
|
||||
export const fallbackLng = {
|
||||
"de-formal": ["de"],
|
||||
"en-formal": ["en", "de"],
|
||||
"pl-formal": ["pl", "de"],
|
||||
"ru-formal": ["ru", "de"],
|
||||
"uk-formal": ["uk", "de"],
|
||||
"hu-formal": ["hu", "de"],
|
||||
default: [defaultLocale],
|
||||
} as const;
|
||||
Reference in new issue
Block a user