Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -18,12 +18,23 @@ export const ANREDE_PARAM = "anrede";
* "du"/"sie") and validated with `isAnrede`, so a tampered value degrades to the
* default rather than selecting an unexpected language.
*/
export const anredeCookie = createCookie("_anrede", {
...resolveSessionCookiePolicy({
nodeEnv: webConfig.nodeEnv,
routing: webConfig.routing,
maxAge: 60 * 60 * 24 * 365,
}),
const isPortalRuntime = webConfig.runtimeSurface === "portal";
export const anredeCookie = createCookie(isPortalRuntime ? "__Host-hivegrid_portal_anrede" : "_anrede", {
...(isPortalRuntime
? {
httpOnly: true,
path: "/",
sameSite: "lax" as const,
secure: true,
maxAge: 60 * 60 * 24 * 365,
}
: resolveSessionCookiePolicy({
nodeEnv: webConfig.nodeEnv,
routing: webConfig.routing,
maxAge: 60 * 60 * 24 * 365,
})),
...(isPortalRuntime && webConfig.portalSessionSecret ? { secrets: [webConfig.portalSessionSecret] } : {}),
});
/**
@@ -7,11 +7,19 @@ describe("date-fns locale bridge", () => {
expect(getDateFnsLocale("de-DE").code).toBe("de");
expect(getDateFnsLocale("en").code).toBe("en-US");
expect(getDateFnsLocale("en-US").code).toBe("en-US");
expect(getDateFnsLocale("pl-PL").code).toBe("pl");
expect(getDateFnsLocale("ru-RU").code).toBe("ru");
expect(getDateFnsLocale("uk-UA").code).toBe("uk");
expect(getDateFnsLocale("hu-HU").code).toBe("hu");
});
it("keeps week starts aligned with the active locale", () => {
expect(getLocaleWeekStartsOn("de")).toBe(1);
expect(getLocaleWeekStartsOn("en")).toBe(0);
expect(getLocaleWeekStartsOn("pl")).toBe(1);
expect(getLocaleWeekStartsOn("ru")).toBe(1);
expect(getLocaleWeekStartsOn("uk")).toBe(1);
expect(getLocaleWeekStartsOn("hu")).toBe(1);
expect(getLocaleWeekStartsOn(undefined)).toBe(1);
});
});
@@ -1,10 +1,10 @@
import { de, enUS } from "date-fns/locale";
import { de, enUS, hu, pl, ru, uk } from "date-fns/locale";
type WeekStartsOn = 0 | 1 | 2 | 3 | 4 | 5 | 6;
export function getDateFnsLocale(language?: string) {
const locale = language?.toLowerCase().split("-")[0];
return locale === "en" ? enUS : de;
return { de, en: enUS, hu, pl, ru, uk }[locale ?? "de"] ?? de;
}
export function getLocaleWeekStartsOn(language?: string): WeekStartsOn {
@@ -1,11 +1,14 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import {
MISSING_NUMBER_PLACEHOLDER,
formatCurrency,
formatDate,
formatDateTime,
formatNumber,
formatRelativeDate,
formatRelativeTime,
toFiniteNumber,
} from "./format";
describe("locale formatters", () => {
@@ -13,6 +16,24 @@ describe("locale formatters", () => {
vi.restoreAllMocks();
});
test("renders a dash instead of NaN for values that are not finite numbers", () => {
// A Prisma Decimal that survived loader serialization as an object used to
// reach this formatter as NaN and rendered as "NaN €".
expect(formatCurrency(Number.NaN, "EUR", "de")).toBe(MISSING_NUMBER_PLACEHOLDER);
expect(formatNumber(Number.POSITIVE_INFINITY, "de")).toBe(MISSING_NUMBER_PLACEHOLDER);
expect(formatCurrency(19.99, "EUR", "de")).not.toBe(MISSING_NUMBER_PLACEHOLDER);
});
test("coerces loader payload shapes into finite numbers", () => {
expect(toFiniteNumber(19.99)).toBe(19.99);
expect(toFiniteNumber("19.99")).toBe(19.99);
expect(toFiniteNumber({ toString: () => "299.99" })).toBe(299.99);
expect(toFiniteNumber(Number.NaN)).toBeNull();
expect(toFiniteNumber(undefined)).toBeNull();
expect(toFiniteNumber("")).toBeNull();
expect(toFiniteNumber({})).toBeNull();
});
test("reuses number formatters for repeated locale and option combinations", () => {
const constructorSpy = vi.spyOn(Intl, "NumberFormat");
@@ -40,6 +61,10 @@ describe("locale formatters", () => {
expect(constructorSpy).toHaveBeenCalledTimes(1);
});
test("formats euro prices with German separators and two decimal places", () => {
expect(formatCurrency(10_000, "EUR", "de").replace(/[\u00a0\u202f]/g, " ")).toBe("10.000,00 €");
});
test("reuses date-time formatters for repeated locale and options", () => {
const constructorSpy = vi.spyOn(Intl, "DateTimeFormat");
const options: Intl.DateTimeFormatOptions = { dateStyle: "medium", timeZone: "UTC" };
@@ -50,6 +75,18 @@ describe("locale formatters", () => {
expect(constructorSpy).toHaveBeenCalledTimes(1);
});
test("formats date-times in the fixed app time zone by default", () => {
// 10:00 UTC is 11:00 in Europe/Berlin (CET) — deterministic regardless of
// the host time zone, so SSR and client output match (React #418).
expect(formatDateTime("2026-01-15T10:00:00.000Z", "de")).toBe("15.01.2026, 11:00");
// During DST (CEST) the offset is +2 hours.
expect(formatDateTime("2026-07-15T10:00:00.000Z", "de")).toBe("15.07.2026, 12:00");
});
test("keeps an explicitly passed time zone over the app default", () => {
expect(formatDateTime("2026-01-15T10:00:00.000Z", "de", { timeZone: "UTC" })).toBe("15.01.2026, 10:00");
});
test("preserves relative date output", () => {
const relativeTo = new Date("2026-05-27T10:00:00.000Z");
@@ -5,6 +5,11 @@ import { defaultLocale, type SupportedLocale } from "./i18n";
// explicit locale (resolved by getTranslations); client React code uses the
// useLocaleFormatters() hook which reads the active language from i18next.
// Fixed app-wide time zone so SSR (UTC container) and the browser produce the
// same date strings — deterministic output avoids React #418 hydration
// mismatches. A tenant-level time-zone setting is a future change request.
export const APP_TIME_ZONE = "Europe/Berlin";
const numberFormatters = new Map<string, Intl.NumberFormat>();
const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>();
const relativeTimeFormatters = new Map<string, Intl.RelativeTimeFormat>();
@@ -26,7 +31,8 @@ function getDateTimeFormatter(locale: SupportedLocale | string, options?: Intl.D
const key = formatterKey(locale, options as Record<string, unknown> | undefined);
const cached = dateTimeFormatters.get(key);
if (cached) return cached;
const formatter = new Intl.DateTimeFormat(locale ?? defaultLocale, options);
// Default to the fixed app time zone; an explicitly passed timeZone wins.
const formatter = new Intl.DateTimeFormat(locale ?? defaultLocale, { timeZone: APP_TIME_ZONE, ...options });
dateTimeFormatters.set(key, formatter);
return formatter;
}
@@ -40,23 +46,54 @@ function getRelativeTimeFormatter(locale: SupportedLocale | string, options?: In
return formatter;
}
// Numeric placeholder for values that are missing or not representable. Never
// surface `NaN`, `Infinity` or `null` to a user: a dash reads as "no value",
// while `NaN €` reads as a broken page.
export const MISSING_NUMBER_PLACEHOLDER = "—";
/**
* Coerces loader payloads into a finite number, or `null` when that is
* impossible. Prisma `Decimal` columns survive the turbo-stream loader
* serialization as structural objects rather than strings, so a bare
* `Number(value)` on the client yields `NaN`. Route loaders should normalize
* decimals server-side; this stays as the last line of defence.
*/
export function toFiniteNumber(value: unknown): number | null {
if (typeof value === "number") return Number.isFinite(value) ? value : null;
if (typeof value === "bigint") return Number(value);
if (typeof value === "string") {
const parsed = Number(value.trim());
return value.trim() && Number.isFinite(parsed) ? parsed : null;
}
if (value && typeof value === "object" && "toString" in value) {
const parsed = Number(String(value));
return Number.isFinite(parsed) ? parsed : null;
}
return null;
}
export function formatNumber(value: number, locale: SupportedLocale | string, options?: Intl.NumberFormatOptions): string {
if (!Number.isFinite(value)) return MISSING_NUMBER_PLACEHOLDER;
return getNumberFormatter(locale, options).format(value);
}
export function formatCurrency(value: number, currency: string, locale: SupportedLocale | string, options?: Intl.NumberFormatOptions): string {
if (!Number.isFinite(value)) return MISSING_NUMBER_PLACEHOLDER;
return getNumberFormatter(locale, { style: "currency", currency, ...options }).format(value);
}
export function formatCurrencyFromCents(cents: number, currency: string, locale: SupportedLocale | string, options?: Intl.NumberFormatOptions): string {
if (!Number.isFinite(cents)) return MISSING_NUMBER_PLACEHOLDER;
return formatCurrency(cents / 100, currency, locale, options);
}
export function formatPercent(value: number, locale: SupportedLocale | string, options?: Intl.NumberFormatOptions): string {
if (!Number.isFinite(value)) return MISSING_NUMBER_PLACEHOLDER;
return getNumberFormatter(locale, { style: "percent", ...options }).format(value);
}
export function formatCompactNumber(value: number, locale: SupportedLocale | string, options?: Intl.NumberFormatOptions): string {
if (!Number.isFinite(value)) return MISSING_NUMBER_PLACEHOLDER;
return getNumberFormatter(locale, { notation: "compact", ...options }).format(value);
}
@@ -1,5 +1,20 @@
export { defaultLocale, getDirection, i18nConfig, i18nNamespaces, isRTL, isSupportedLocale, supportedLocales } from "@hivegrid/i18n";
export type { I18nNamespace, SupportedLocale, TextDirection } from "@hivegrid/i18n";
export {
defaultEnabledLocales,
defaultLocale,
catalogReadyLocales,
fallbackLng,
getDirection,
i18nConfig,
i18nNamespaces,
isRTL,
isSupportedLocale,
localeReleaseStages,
normalizeLocaleCandidate,
parseEnabledLocales,
resolveEnabledLocale,
supportedLocales,
} from "@hivegrid/i18n";
export type { I18nNamespace, ResolveEnabledLocaleInput, SupportedLocale, TextDirection } from "@hivegrid/i18n";
// Formality (Anrede) axis — du/Sie. Re-exported here so app-level consumers
// import from the local locale module consistently. Definitions live in the
@@ -0,0 +1,65 @@
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { Resource, ResourceLanguage } from "i18next";
import { catalogReadyLocales, i18nNamespaces } from "@hivegrid/i18n";
type ResolveServerLocalePathOptions = {
moduleUrl?: string;
cwd?: string;
exists?: (candidate: string) => boolean;
};
export function resolveServerLocalePath({
moduleUrl = import.meta.url,
cwd = process.cwd(),
exists = existsSync,
}: ResolveServerLocalePathOptions = {}) {
const parsedModuleUrl = new URL(moduleUrl);
const usesPosixFixturePath = process.platform === "win32" && parsedModuleUrl.protocol === "file:" && !/^\/[a-zA-Z]:\//.test(parsedModuleUrl.pathname);
const pathApi = usesPosixFixturePath ? path.posix : path;
const modulePath = usesPosixFixturePath ? decodeURIComponent(parsedModuleUrl.pathname) : fileURLToPath(parsedModuleUrl);
const moduleDir = pathApi.dirname(modulePath);
const candidates = [
pathApi.resolve(moduleDir, "../../public/locales"),
pathApi.resolve(cwd, "apps/web/public/locales"),
pathApi.resolve(cwd, "public/locales"),
];
return candidates.find((candidate) => exists(candidate)) ?? candidates[0];
}
export const serverLocalePath = resolveServerLocalePath();
const serverLanguages = [...catalogReadyLocales, ...catalogReadyLocales.map((locale) => `${locale}-formal`)];
let resourcesSnapshot: Resource | null = null;
let resourceLoadCount = 0;
export function getServerI18nResourcesSnapshot(): Resource {
if (resourcesSnapshot !== null) return resourcesSnapshot;
const resources: Resource = {};
for (const locale of serverLanguages) {
const bundle: ResourceLanguage = {};
for (const namespace of i18nNamespaces) {
try {
const file = path.join(serverLocalePath, locale, `${namespace}.json`);
bundle[namespace] = JSON.parse(readFileSync(file, "utf8")) as ResourceLanguage[string];
} catch {
bundle[namespace] = {};
}
}
resources[locale] = bundle;
}
resourcesSnapshot = resources;
resourceLoadCount += 1;
return resourcesSnapshot;
}
/** Test-only diagnostic proving locale files are parsed once per process. */
export function __getServerI18nResourceLoadCountForTests(): number {
return resourceLoadCount;
}
@@ -2,29 +2,99 @@ import { describe, expect, test } from "vitest";
import i18next from "i18next";
import { ensureServerGlobalI18n, syncServerGlobalI18nLanguage } from "./i18next.global.server";
import {
__getServerGlobalI18nResourceLoadCountForTests,
ensureServerGlobalI18n,
getServerRequestI18nLanguage,
getServerI18nResourcesSnapshot,
runWithServerI18nLanguage,
} from "./i18next.global.server";
import { requestScopedT } from "./request-scoped-t";
describe("server global i18next bootstrap", () => {
test("initialises the global instance with preloaded resources", async () => {
await ensureServerGlobalI18n();
await ensureServerGlobalI18n();
expect(i18next.isInitialized).toBe(true);
expect(__getServerGlobalI18nResourceLoadCountForTests()).toBe(1);
// The sidebar toggle label is the canonical string that previously rendered
// empty during SSR (causing button-name a11y failures + hydration #418).
expect(i18next.t("components.sidebar.toggle")).not.toBe("");
expect(i18next.t("components.sidebar.toggle")).not.toBe("components.sidebar.toggle");
});
test("aligns the global language with the requested locale", async () => {
await syncServerGlobalI18nLanguage("en");
expect(i18next.language).toBe("en");
const en = i18next.t("components.sidebar.toggle");
test("reuses the same parsed resource snapshot for request-scoped instances", async () => {
const first = await getServerI18nResourcesSnapshot();
const second = await getServerI18nResourcesSnapshot();
await syncServerGlobalI18nLanguage("de");
expect(i18next.language).toBe("de");
const de = i18next.t("components.sidebar.toggle");
expect(second).toBe(first);
expect(__getServerGlobalI18nResourceLoadCountForTests()).toBe(1);
});
expect(en).not.toBe("");
expect(de).not.toBe("");
expect(de).not.toBe(en);
test("keeps overlapping English and German async work request-scoped", async () => {
await ensureServerGlobalI18n();
const singletonLanguage = i18next.language;
const key = "components.sidebar.toggle";
let releaseEnglish!: () => void;
const englishCanFinish = new Promise<void>((resolve) => {
releaseEnglish = resolve;
});
let markEnglishStarted!: () => void;
const englishStarted = new Promise<void>((resolve) => {
markEnglishStarted = resolve;
});
const englishRequest = runWithServerI18nLanguage("en", async () => {
const beforeOverlap = requestScopedT(key);
markEnglishStarted();
await englishCanFinish;
await new Promise<void>((resolve) => setTimeout(resolve, 0));
return {
beforeOverlap,
afterOverlap: requestScopedT(key),
language: getServerRequestI18nLanguage(),
};
});
await englishStarted;
const germanRequest = runWithServerI18nLanguage("de", async () => {
const beforeOverlap = requestScopedT(key);
releaseEnglish();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
return {
beforeOverlap,
afterOverlap: requestScopedT(key),
language: getServerRequestI18nLanguage(),
};
});
const [english, german] = await Promise.all([englishRequest, germanRequest]);
expect(english).toEqual({
beforeOverlap: "Toggle sidebar",
afterOverlap: "Toggle sidebar",
language: "en",
});
expect(german).toEqual({
beforeOverlap: "Seitenleiste umschalten",
afterOverlap: "Seitenleiste umschalten",
language: "de",
});
expect(getServerRequestI18nLanguage()).toBeUndefined();
expect(i18next.language).toBe(singletonLanguage);
});
test("retains the request translator for streaming work created before the response resolves", async () => {
let streamedTranslation!: Promise<string>;
await runWithServerI18nLanguage("de", () => {
streamedTranslation = new Promise((resolve) => {
setTimeout(() => resolve(requestScopedT("components.sidebar.toggle")), 0);
});
return new Response(null, { status: 200 });
});
expect(await streamedTranslation).toBe("Seitenleiste umschalten");
});
});
@@ -1,60 +1,29 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import { AsyncLocalStorage } from "node:async_hooks";
import i18next, { type Resource, type ResourceLanguage } from "i18next";
import i18next, { type Resource, type TFunction } from "i18next";
import { formalLngs, i18nConfig, i18nNamespaces, supportedLocales } from "./i18n";
import { serverLocalePath } from "./i18next.server";
import { catalogReadyLocales, defaultLocale, i18nConfig } from "./i18n";
import { __getServerI18nResourceLoadCountForTests, getServerI18nResourcesSnapshot } from "./i18next-resources.server";
import { REQUEST_TRANSLATOR_RESOLVER, type RequestTranslatorResolver } from "./request-scoped-t";
// The global instance must be able to render *and* `changeLanguage` into the
// formal variants ("de-formal", "en-formal") in addition to the base locales.
// The process-level resource store must resolve fixed translators for the
// formal variants ("de-formal", "en-formal") as well as the base locales.
// Their bundles are loaded best-effort (missing files are non-fatal) and fall
// back to the base locale for un-overridden keys.
const globalLngs = [...supportedLocales, ...formalLngs];
const globalLngs = [...catalogReadyLocales, ...catalogReadyLocales.map((locale) => `${locale}-formal`)];
/**
* Server-side bootstrap for the *global* i18next instance (the default export
* of `i18next`). A large number of components resolve translations through the
* module-level `t` helper (`import { t } from "i18next"`) rather than the
* `useTranslation()` hook. On the client that global instance is initialised in
* `entry.client.tsx`, but on the server only the per-request scoped instance was
* ever initialised. That left the global `t` returning empty strings during SSR,
* which produced empty `sr-only` labels (axe `button-name`/`link-name`
* violations) and — more damagingly — React hydration mismatches (error #418)
* that aborted hydration and broke client interactivity on authenticated pages.
*
* Initialising the global instance with every locale preloaded synchronously,
* then aligning its language with the request locale immediately before the
* (synchronous) shell render, keeps SSR output identical to the hydrated client
* output. The language is mutated per request; because the non-streaming shell
* render that follows `syncServerGlobalI18nLanguage` is synchronous, the global
* language is correct for that render.
* Server-side bootstrap for the process-level i18next resource store. Every
* locale is loaded once, but the singleton language is never changed per
* request: overlapping loaders and streaming renders would otherwise be able to
* observe another request's locale. Request-aware call sites resolve a fixed
* translator through the AsyncLocalStorage bridge below.
*/
function loadAllResources(): Resource {
const resources: Resource = {};
for (const locale of globalLngs) {
const bundle: ResourceLanguage = {};
for (const namespace of i18nNamespaces) {
try {
const file = path.join(serverLocalePath, locale, `${namespace}.json`);
bundle[namespace] = JSON.parse(readFileSync(file, "utf8")) as ResourceLanguage[string];
} catch {
// A missing namespace file is non-fatal: i18next will fall back to the
// fallback language / key for that namespace. This is also the path the
// formal variants take until their override files exist on disk.
bundle[namespace] = {};
}
}
resources[locale] = bundle;
}
return resources;
}
function registerAllBundles(resources: Resource): void {
// Register every locale/namespace bundle. `init({ resources })` only
// guarantees the active language's bundle is added; registering them all
// up-front lets `changeLanguage` resolve any supported locale synchronously.
// up-front lets `getFixedT` resolve any supported locale synchronously.
// This also backfills bundles when another module (e.g. test setup) already
// initialised the global instance with a narrower resource set.
for (const locale of Object.keys(resources)) {
@@ -67,38 +36,89 @@ function registerAllBundles(resources: Resource): void {
}
let initPromise: Promise<typeof i18next> | null = null;
const fixedTranslators = new Map<string, TFunction>();
type RequestI18nStore = {
language: string;
translator: TFunction;
};
const REQUEST_I18N_STORAGE = Symbol.for("hivegrid.i18n.request-storage");
type GlobalWithRequestI18n = typeof globalThis & {
[REQUEST_I18N_STORAGE]?: AsyncLocalStorage<RequestI18nStore>;
[REQUEST_TRANSLATOR_RESOLVER]?: RequestTranslatorResolver;
};
const requestI18nGlobal = globalThis as GlobalWithRequestI18n;
const requestI18nStorage = requestI18nGlobal[REQUEST_I18N_STORAGE] ?? (requestI18nGlobal[REQUEST_I18N_STORAGE] = new AsyncLocalStorage<RequestI18nStore>());
// Reinstall on module evaluation so development reloads cannot leave a resolver
// pointing at an obsolete module-local storage instance.
requestI18nGlobal[REQUEST_TRANSLATOR_RESOLVER] = () => requestI18nStorage.getStore()?.translator;
export async function ensureServerGlobalI18n(): Promise<typeof i18next> {
if (i18next.isInitialized) {
registerAllBundles(loadAllResources());
return i18next;
}
if (!initPromise) {
const resources = loadAllResources();
initPromise = i18next
.init({
...i18nConfig,
// Accept the formal variants as valid languages so a later
// `changeLanguage("<locale>-formal")` is honoured instead of being
// dropped back to the detection fallback.
supportedLngs: globalLngs,
lng: i18nConfig.fallbackLng,
preload: [...globalLngs],
resources,
// Resources are bundled in memory, so no backend/async loading is needed.
initImmediate: false,
})
.then(() => {
registerAllBundles(resources);
return i18next;
});
const resources = getServerI18nResourcesSnapshot();
if (i18next.isInitialized) {
registerAllBundles(resources);
initPromise = Promise.resolve(i18next);
} else {
initPromise = i18next
.init({
...i18nConfig,
// Accept the formal variants so fixed translators retain the
// requested variant instead of dropping back to detection fallback.
supportedLngs: globalLngs,
lng: defaultLocale,
preload: [...globalLngs],
resources,
// Resources are bundled in memory, so no backend/async loading is needed.
initImmediate: false,
})
.then(() => {
registerAllBundles(resources);
return i18next;
});
}
}
return initPromise;
}
export async function syncServerGlobalI18nLanguage(language: string): Promise<void> {
await ensureServerGlobalI18n();
if (i18next.language !== language) {
await i18next.changeLanguage(language);
export async function runWithServerI18nLanguage<T>(language: string, callback: () => T | Promise<T>): Promise<T> {
const instance = await ensureServerGlobalI18n();
const activeStore = requestI18nStorage.getStore();
if (activeStore?.language === language) {
return callback();
}
return requestI18nStorage.run(
{
language,
translator: getFixedTranslator(instance, language),
},
callback
);
}
function getFixedTranslator(instance: typeof i18next, language: string): TFunction {
const cached = fixedTranslators.get(language);
if (cached) {
return cached;
}
const translator = instance.getFixedT(language);
fixedTranslators.set(language, translator);
return translator;
}
export function getServerRequestI18nLanguage(): string | undefined {
return requestI18nStorage.getStore()?.language;
}
/** Test-only diagnostic proving locale files are loaded at most once per process. */
export function __getServerGlobalI18nResourceLoadCountForTests(): number {
return __getServerI18nResourceLoadCountForTests();
}
export { getServerI18nResourcesSnapshot } from "./i18next-resources.server";
@@ -4,6 +4,8 @@ import { describe, expect, it, vi } from "vitest";
type TestWebConfig = {
nodeEnv: string;
sessionSecret: string;
runtimeSurface: "core" | "portal";
i18n: { enabledLocales: readonly ["de", "en"] };
routing: {
appBaseDomain: string;
protocol: "http" | "https";
@@ -13,6 +15,8 @@ type TestWebConfig = {
const testWebConfig: TestWebConfig = {
nodeEnv: "production",
sessionSecret: "production-session-secret-with-enough-entropy",
runtimeSurface: "core",
i18n: { enabledLocales: ["de", "en"] },
routing: {
appBaseDomain: "example.com",
protocol: "https",
@@ -1,47 +1,39 @@
import { existsSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createCookie } from "react-router";
import { loadRequiredWebConfig, resolveSessionCookiePolicy } from "@hivegrid/config";
import { RemixI18Next } from "remix-i18next/server";
import { effectiveLng, formalLngs, i18nConfig, i18nNamespaces } from "./i18n";
import { catalogReadyLocales, defaultLocale, effectiveLng, i18nConfig, i18nNamespaces } from "./i18n";
import { resolveAnrede } from "./anrede.server";
import Backend from "i18next-fs-backend";
import { getServerI18nResourcesSnapshot, resolveServerLocalePath, serverLocalePath } from "./i18next-resources.server";
const webConfig = loadRequiredWebConfig();
type ResolveServerLocalePathOptions = {
moduleUrl?: string;
cwd?: string;
exists?: (candidate: string) => boolean;
};
export { resolveServerLocalePath, serverLocalePath };
export function resolveServerLocalePath({ moduleUrl = import.meta.url, cwd = process.cwd(), exists = existsSync }: ResolveServerLocalePathOptions = {}) {
// `path.resolve(path.dirname(fileURLToPath(url)), "../../...")` instead
// of `new URL("...", moduleUrl)` because vitest 3 resolves relative
// URL constructors through the Vite dev server (returning http://...);
// we need a file path here.
const moduleDir = path.dirname(fileURLToPath(moduleUrl));
const candidates = [
path.resolve(moduleDir, "../../public/locales"),
path.resolve(cwd, "apps/web/public/locales"),
path.resolve(cwd, "public/locales"),
];
const isPortalRuntime = webConfig.runtimeSurface === "portal";
export const enabledLocales = webConfig.i18n.enabledLocales;
return candidates.find((candidate) => exists(candidate)) ?? candidates[0];
}
export const serverLocalePath = resolveServerLocalePath();
export const i18nCookie = createCookie("_i18n", {
...resolveSessionCookiePolicy({
nodeEnv: webConfig.nodeEnv,
routing: webConfig.routing,
maxAge: 60 * 60 * 24 * 30,
}),
secrets: webConfig.sessionSecret ? [webConfig.sessionSecret] : [],
export const i18nCookie = createCookie(isPortalRuntime ? "__Host-hivegrid_portal_locale" : "_i18n", {
...(isPortalRuntime
? {
httpOnly: true,
path: "/",
sameSite: "lax" as const,
secure: true,
maxAge: 60 * 60 * 24 * 30,
}
: resolveSessionCookiePolicy({
nodeEnv: webConfig.nodeEnv,
routing: webConfig.routing,
maxAge: 60 * 60 * 24 * 30,
})),
secrets: isPortalRuntime
? webConfig.portalSessionSecret
? [webConfig.portalSessionSecret]
: []
: webConfig.sessionSecret
? [webConfig.sessionSecret]
: [],
});
export const remixI18Next = new RemixI18Next({
@@ -49,9 +41,9 @@ export const remixI18Next = new RemixI18Next({
// The cookie used to store user's language preference.
cookie: i18nCookie,
// The supported languages.
supportedLanguages: i18nConfig.supportedLngs,
supportedLanguages: [...enabledLocales],
// The fallback language.
fallbackLanguage: i18nConfig.fallbackLng,
fallbackLanguage: defaultLocale,
},
// The i18next configuration used when translating
@@ -64,16 +56,13 @@ export const remixI18Next = new RemixI18Next({
// (`detection.supportedLanguages` above) intentionally stays base-only so
// `getLocale()` — which drives `<html lang>` — never returns a non-BCP47
// "-formal" code.
supportedLngs: [...i18nConfig.supportedLngs, ...formalLngs],
backend: {
localePath: serverLocalePath,
loadPath: `${serverLocalePath}/{{lng}}/{{ns}}.json`,
},
supportedLngs: [...i18nConfig.supportedLngs, ...catalogReadyLocales.map((locale) => `${locale}-formal`)],
resources: getServerI18nResourcesSnapshot(),
},
// The plugins you want RemixI18next to use for `i18n.getFixedT` inside loaders and actions.
// E.g. The Backend plugin for loading translations from the file system.
plugins: [Backend],
plugins: [],
});
export async function getTranslations(request: Request, namespace = "translations", options?: { tenant?: { anrede?: string | null } | null }) {
@@ -1,5 +1,5 @@
import { defaultLocale, isSupportedLocale } from "@hivegrid/i18n";
import { remixI18Next } from "./i18next.server";
import { defaultLocale, normalizeLocaleCandidate, type SupportedLocale } from "@hivegrid/i18n";
import { enabledLocales, remixI18Next } from "./i18next.server";
/**
* Mail-side translator function. Kept locally now that the legacy
@@ -16,10 +16,9 @@ const MAIL_NAMESPACE = "mail" as const;
* Normalize a (possibly null/unsupported) locale string to a supported locale,
* falling back to {@link defaultLocale} when no supported match is found.
*/
export function resolveMailLocale(locale: string | null | undefined): string {
if (locale && isSupportedLocale(locale)) {
return locale;
}
export function resolveMailLocale(locale: string | null | undefined): SupportedLocale {
const normalized = normalizeLocaleCandidate(locale);
if (normalized && enabledLocales.includes(normalized)) return normalized;
return defaultLocale;
}
@@ -29,7 +28,7 @@ export function resolveMailLocale(locale: string | null | undefined): string {
*/
export async function getMailTranslator(locale: string | null | undefined): Promise<{
t: MailTranslator;
locale: string;
locale: SupportedLocale;
}> {
const resolved = resolveMailLocale(locale);
const fixedT = await remixI18Next.getFixedT(resolved, MAIL_NAMESPACE);
@@ -44,7 +43,7 @@ export async function getMailTranslator(locale: string | null | undefined): Prom
*/
export async function getMailTranslatorFromRequest(request: Request): Promise<{
t: MailTranslator;
locale: string;
locale: SupportedLocale;
}> {
const detected = await remixI18Next.getLocale(request);
return getMailTranslator(detected);
@@ -0,0 +1,69 @@
import { readdirSync, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import ts from "typescript";
import { describe, expect, test } from "vitest";
const appDirectory = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const bridgeFile = path.join(appDirectory, "locale", "request-scoped-t.ts");
describe("request-scoped translation bridge", () => {
test("prevents runtime use of the process-global i18next t API", () => {
const violations = new Set<string>();
for (const file of getSourceFiles(appDirectory)) {
const source = readFileSync(file, "utf8");
const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
const defaultImports = new Set<string>();
for (const statement of sourceFile.statements) {
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== "i18next") {
continue;
}
const importClause = statement.importClause;
const namedBindings = importClause?.namedBindings;
if (importClause?.isTypeOnly) {
continue;
}
if (importClause?.name) {
defaultImports.add(importClause.name.text);
}
if (
namedBindings &&
ts.isNamedImports(namedBindings) &&
namedBindings.elements.some((element) => !element.isTypeOnly && (element.propertyName ?? element.name).text === "t")
) {
violations.add(path.relative(appDirectory, file));
}
}
if (file !== bridgeFile && !/\.test\.[cm]?[jt]sx?$/.test(file)) {
visit(sourceFile, (node) => {
if (ts.isPropertyAccessExpression(node) && node.name.text === "t" && ts.isIdentifier(node.expression) && defaultImports.has(node.expression.text)) {
violations.add(path.relative(appDirectory, file));
}
});
}
}
expect([...violations].sort()).toEqual([]);
});
});
function getSourceFiles(directory: string): string[] {
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
const entryPath = path.join(directory, entry.name);
if (entry.isDirectory()) {
return getSourceFiles(entryPath);
}
return entry.isFile() && /\.tsx?$/.test(entry.name) ? [entryPath] : [];
});
}
function visit(node: ts.Node, callback: (node: ts.Node) => void): void {
callback(node);
ts.forEachChild(node, (child) => visit(child, callback));
}
@@ -0,0 +1,22 @@
import * as i18next from "i18next";
import type { TFunction } from "i18next";
/**
* Shared indirection used by code that cannot receive a translator through
* props or a hook. On the server, the resolver is installed by the
* AsyncLocalStorage-backed request scope. In the browser (and outside an HTTP
* request), it falls back to the regular client-initialised i18next instance.
*/
export const REQUEST_TRANSLATOR_RESOLVER = Symbol.for("hivegrid.i18n.request-translator-resolver");
export type RequestTranslatorResolver = () => TFunction | undefined;
type GlobalWithRequestTranslator = typeof globalThis & {
[REQUEST_TRANSLATOR_RESOLVER]?: RequestTranslatorResolver;
};
export const requestScopedT = ((...args: unknown[]) => {
const resolver = (globalThis as GlobalWithRequestTranslator)[REQUEST_TRANSLATOR_RESOLVER];
const translator = resolver?.() ?? i18next.t;
return Reflect.apply(translator, undefined, args);
}) as unknown as TFunction;