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 { resolveAnrede } from "./anrede.server"; import Backend from "i18next-fs-backend"; const webConfig = loadRequiredWebConfig(); type ResolveServerLocalePathOptions = { moduleUrl?: string; cwd?: string; exists?: (candidate: string) => boolean; }; 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"), ]; 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 remixI18Next = new RemixI18Next({ detection: { // The cookie used to store user's language preference. cookie: i18nCookie, // The supported languages. supportedLanguages: i18nConfig.supportedLngs, // The fallback language. fallbackLanguage: i18nConfig.fallbackLng, }, // The i18next configuration used when translating // Server-Side only messages. i18next: { ...i18nConfig, // Allow the formal variants ("de-formal", "en-formal") as *translation* // languages so `getFixedT("-formal")` resolves the formal bundle // (and falls back to the base locale for un-overridden keys). Detection // (`detection.supportedLanguages` above) intentionally stays base-only so // `getLocale()` — which drives `` — never returns a non-BCP47 // "-formal" code. supportedLngs: [...i18nConfig.supportedLngs, ...formalLngs], backend: { localePath: serverLocalePath, loadPath: `${serverLocalePath}/{{lng}}/{{ns}}.json`, }, }, // 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], }); export async function getTranslations(request: Request, namespace = "translations", options?: { tenant?: { anrede?: string | null } | null }) { // Load every namespace so callers can resolve cross-namespace keys like // `t("auth:errors.invalidEmail")` while `namespace` stays the default for // un-prefixed keys. See #72 i18n namespace split. const namespaces: [string, ...string[]] = [namespace, ...i18nNamespaces.filter((ns) => ns !== namespace)]; const locale = await remixI18Next.getLocale(request); // Resolve the formality axis and translate against the *effective* language. // With the default "du" (no cookie/param, "du"/unset tenant) `effectiveLng` // returns the plain locale, so `getFixedT(locale, …)` is equivalent to the // previous `getFixedT(request, …)` — byte-identical output. "sie" switches to // "-formal" and falls back to the base locale for un-overridden keys. const anrede = await resolveAnrede(request, options?.tenant); const lng = effectiveLng(locale, anrede); const t = await remixI18Next.getFixedT(lng, namespaces); let translations: any = {}; return { t, translations, locale }; }