Files

51 lines
2.0 KiB
TypeScript

import { defaultLocale, normalizeLocaleCandidate, type SupportedLocale } from "@hivegrid/i18n";
import { enabledLocales, remixI18Next } from "./i18next.server";
/**
* Mail-side translator function. Kept locally now that the legacy
* `@hivegrid/mail` template-string renderer is retired; the React-Email
* templates do not consume a translator directly, but this signature is
* still exposed for downstream callers that audit/log under translator
* context.
*/
export type MailTranslator = (key: string, vars?: Record<string, unknown>) => string;
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): SupportedLocale {
const normalized = normalizeLocaleCandidate(locale);
if (normalized && enabledLocales.includes(normalized)) return normalized;
return defaultLocale;
}
/**
* Return a {@link MailTranslator} bound to the given user locale, backed by the
* `mail` i18next namespace (loaded from `apps/web/public/locales/<locale>/mail.json`).
*/
export async function getMailTranslator(locale: string | null | undefined): Promise<{
t: MailTranslator;
locale: SupportedLocale;
}> {
const resolved = resolveMailLocale(locale);
const fixedT = await remixI18Next.getFixedT(resolved, MAIL_NAMESPACE);
const t: MailTranslator = (key, vars) => fixedT(key, vars ?? {}) as string;
return { t, locale: resolved };
}
/**
* Convenience helper that derives the mail translator from a Request — used
* when the caller does not yet have a user record (e.g. pre-registration, anonymous
* password reset, anonymous invitation acceptance).
*/
export async function getMailTranslatorFromRequest(request: Request): Promise<{
t: MailTranslator;
locale: SupportedLocale;
}> {
const detected = await remixI18Next.getLocale(request);
return getMailTranslator(detected);
}