import { createCookie } from "react-router"; import { loadRequiredWebConfig, resolveSessionCookiePolicy } from "@hivegrid/config"; import { type Anrede, defaultAnrede, isAnrede } from "@hivegrid/i18n"; const webConfig = loadRequiredWebConfig(); /** * Query-string override for the formality axis (`?anrede=sie`). Highest * priority so links / previews can force a variant for a single navigation * without mutating any persisted state. */ export const ANREDE_PARAM = "anrede"; /** * Persisted browser preference for du/Sie. The settings toggle writes this on * change; `resolveAnrede` reads it. Unsigned (the value is non-sensitive — just * "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, }), }); /** * Resolves the effective Anrede for a request. * * Priority (first match wins): * 1. explicit `?anrede=` query param * 2. explicit `_anrede` cookie (set by the settings toggle) * 3. the tenant's persisted default (`Tenant.anrede`) * 4. the global default ("du") * * Every source is validated through `isAnrede`, so unknown values fall through * to the next source. With no cookie / param and a "du" (or unset) tenant the * result is `defaultAnrede`, which keeps `effectiveLng` equal to the base * locale — i.e. byte-identical to the pre-toggle behaviour. */ export async function resolveAnrede(request: Request, tenant?: { anrede?: string | null } | null): Promise { const param = new URL(request.url).searchParams.get(ANREDE_PARAM) ?? undefined; if (isAnrede(param)) { return param; } const cookieValue = (await anredeCookie.parse(request.headers.get("Cookie"))) as string | null; if (isAnrede(cookieValue ?? undefined)) { return cookieValue as Anrede; } const tenantAnrede = tenant?.anrede ?? undefined; if (isAnrede(tenantAnrede)) { return tenantAnrede; } return defaultAnrede; }