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

@@ -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";