Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): correct three defects the lazy-locale split introduced

Yudhi Armyndharis650eeb9364c6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 68d524539..ac54ae4db 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- The dashboard bundled all thirteen locales into one 476 KB chunk the page preloaded, so every visitor downloaded twelve languages to read one; each is now fetched on demand.
+- A locale chunk that failed to load left the dashboard right-to-left around English copy, because text direction followed the requested language rather than the catalogue that answered; it now follows what actually rendered.
- `check:sdk-routes` scanned the JavaScript client for backtick-delimited paths only, while its PHP and Python rules already accepted every quote style, so the nine routes that client writes as single-quoted strings were never compared to the contract — `/api/health/ready` among them, which is also the container healthcheck and Kubernetes readiness path. Renaming one of those server-side passed every gate and the JS suite, and the published client would have 404'd with CI green.
- The JavaScript, Python, Go and Java SDKs omitted `contact`, `call` and `ephemeralDuration` from their chat-history message type, so a typed client had to cast to read three fields the endpoint returns; all four now mirror the engine payload.
- `POST /api/infra/import-data` bound its body to an inline type, which erases at runtime, so on the replace-all restore the global ValidationPipe's `whitelist` and `forbidNonWhitelisted` never ran: a body carrying no `tables` failed as a 500 from inside the import, and a misspelled key was accepted in silence. It now takes a DTO — a missing `tables` answers 400 instead, naming the field outside production, where field-level detail is suppressed unless `VALIDATION_ERROR_DETAIL=true`; an unknown key is refused, and `force`/`stopOrphans` accept only a real boolean or an exact `'true'`/`'false'`, so an ambiguous spelling cannot open the orphan-engine escape. The export file still posts back verbatim: the five metadata fields it wraps `tables` in are accepted and ignored, and a spec probes every field the export publishes so a new one cannot start failing the restore.
diff --git a/dashboard/src/i18n/index.ts b/dashboard/src/i18n/index.ts
index d9b909ec3..3d065387f 100644
--- a/dashboard/src/i18n/index.ts
+++ b/dashboard/src/i18n/index.ts
@@ -75,8 +75,17 @@ const lazyLocaleBackend: BackendModule = {
},
};
-function applyDirection(lang: string) {
- const resolved = resolveSupportedLanguage(lang);
+/**
+ * Keyed to `resolvedLanguage` — the language whose catalogue actually answered — rather than to the
+ * one that was requested, which is the expression `Layout` and `Login` already use to label the
+ * picker. The two could not disagree while every catalogue was bundled; now that they are fetched
+ * they can. A chunk that 404s (a tab left open across a redeploy is the realistic way) still sets
+ * `language`, still emits this event and still gets cached by the detector, while `t()` serves the
+ * English fallback — so following the request would dress English copy right-to-left and leave the
+ * picker reading EN against an `ar` document.
+ */
+function applyDirection() {
+ const resolved = resolveSupportedLanguage(i18n.resolvedLanguage || i18n.language);
const dir = rtlLanguages.includes(resolved) ? 'rtl' : 'ltr';
if (typeof document !== 'undefined') {
document.documentElement.lang = resolved;
@@ -97,9 +106,6 @@ export const i18nReady = i18n
fallbackLng: 'en',
supportedLngs: supportedLanguages as unknown as string[],
nonExplicitSupportedLngs: false,
- // Fetch only the resolved language (plus the fallback). i18next's default would also request a
- // bare 'zh' catalogue for a 'zh-CN' visitor, and no such file exists.
- load: 'currentOnly',
interpolation: { escapeValue: false },
detection: {
order: ['localStorage', 'navigator'],
diff --git a/dashboard/src/i18n/lazy-locales-rtl.test.ts b/dashboard/src/i18n/lazy-locales-rtl.test.ts
new file mode 100644
index 000000000..ba0128d81
--- /dev/null
+++ b/dashboard/src/i18n/lazy-locales-rtl.test.ts
@@ -0,0 +1,52 @@
+// The first load of a non-English, right-to-left visitor — the path where the lazy split actually
+// costs something, because the catalogue is now a network round trip that first paint waits on.
+// `lazy-locales.test.ts` cannot cover it: the i18n module is a singleton, so one process only ever
+// has one initial language, and there it is English. Detection is steered the way a returning
+// visitor steers it, through the `openwa_language` key the detector caches into, which also
+// exercises the localStorage branch of `detection.order` that nothing else reaches.
+//
+// Runner constraints honored here: loader hooks registered before any app-module import (see
+// test-helpers/register-hooks), and JSDOM installed before the module is imported — both because it
+// reads `document` and `localStorage` while initializing, and because the seeded key has to be in
+// place before detection runs.
+import '../test-helpers/register-hooks.ts';
+import { test, before } from 'node:test';
+import assert from 'node:assert/strict';
+import type { installJsdomGlobals as installJsdomGlobalsFn } from '../test-helpers/jsdom.ts';
+
+type I18nModule = typeof import('./index.ts');
+
+let i18n: I18nModule['default'];
+
+before(async () => {
+ const { installJsdomGlobals } = (await import('../test-helpers/jsdom.ts')) as {
+ installJsdomGlobals: typeof installJsdomGlobalsFn;
+ };
+ await installJsdomGlobals();
+ localStorage.setItem('openwa_language', 'ar');
+ const module = (await import('./index.ts')) as I18nModule;
+ i18n = module.default;
+ await module.i18nReady;
+});
+
+test('a stored Arabic preference is detected and its catalogue is loaded before i18nReady settles', () => {
+ assert.equal(i18n.resolvedLanguage, 'ar', 'the stored preference was not detected');
+ assert.equal(i18n.t('sessionStatus.failed'), 'فشل', 'the catalogue had not arrived when the promise settled');
+});
+
+// Rendering waits on the same promise, so this is the state the document is in at first paint —
+// the reason the split does not show a left-to-right frame before flipping.
+test('the document is already right-to-left when i18nReady settles', () => {
+ assert.equal(document.documentElement.dir, 'rtl');
+ assert.equal(document.documentElement.lang, 'ar');
+});
+
+// A non-English visitor fetches two catalogues, not one: `fallbackLng` keeps English resident so a
+// key that a translation happens to be missing still renders as copy rather than as a raw key. The
+// published byte figures for this change count both, which makes the second fetch part of what was
+// promised rather than an implementation detail. Only a non-English initial language can assert it —
+// when English is the detected language, it is resident whether or not anything falls back to it.
+test('the English fallback is fetched alongside the detected catalogue', () => {
+ assert.ok(i18n.hasResourceBundle('ar', 'translation'), 'the detected catalogue is not loaded');
+ assert.ok(i18n.hasResourceBundle('en', 'translation'), 'the English fallback was not fetched');
+});
diff --git a/dashboard/src/i18n/lazy-locales.test.ts b/dashboard/src/i18n/lazy-locales.test.ts
index a2049cf5a..8243774b9 100644
--- a/dashboard/src/i18n/lazy-locales.test.ts
+++ b/dashboard/src/i18n/lazy-locales.test.ts
@@ -63,15 +63,40 @@ test('direction follows the language in both directions, for both RTL locales',
assert.equal(document.documentElement.lang, 'en');
});
+// A catalogue that fails to arrive is the one state these runtime tests cannot reach: the loader
+// reads real files here, so it always succeeds. In a browser it can 404 — a tab left open across a
+// redeploy asks for a hashed chunk that no longer exists — and i18next answers by setting
+// `language` to the request, emitting `languageChanged`, and serving the English fallback from
+// `t()`. Direction therefore has to follow `resolvedLanguage`, which reports what actually answered,
+// or the document is dressed right-to-left around English copy. Asserted against the source for the
+// same reason the main.tsx gate below is: the wiring is what breaks, and it cannot be provoked here.
+test('direction follows the catalogue that answered, not the one that was asked for', () => {
+ const source = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'index.ts'), 'utf8');
+ const body = source.slice(source.indexOf('function applyDirection'));
+ // Bound to the assignment rather than to the mere presence of the call, so a leftover reference to
+ // resolvedLanguage cannot satisfy this while the value actually used comes from somewhere else.
+ assert.match(
+ body.slice(0, body.indexOf('}')),
+ /const resolved = resolveSupportedLanguage\(\s*i18n\.resolvedLanguage\b/,
+ 'applyDirection no longer derives the direction it applies from i18n.resolvedLanguage',
+ );
+});
+
// The catalogue is fetched now instead of bundled, so first paint is only free of untranslated text
// while the entry keeps rendering behind that promise. Nothing in a build or a type check notices
// if the gate is dropped, and the flash it brings back is a tick long — easy to miss by hand.
test('main.tsx renders behind i18nReady', () => {
const source = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'main.tsx'), 'utf8');
- assert.match(source, /i18nReady\.then\(/, 'main.tsx no longer defers the first render until the catalogue is loaded');
- assert.doesNotMatch(
- source,
- /^createRoot\(/m,
- 'main.tsx calls createRoot at module scope again — the first paint no longer waits for the catalogue',
+ // Comments stripped first: this file explains the deferral at length, and a gate that reads prose
+ // fires on a description of the bug as readily as on the bug. Counting the calls is what closes
+ // the gap an anchored pattern leaves — an unguarded render put anywhere but column zero, or added
+ // alongside the deferred one, is a second createRoot rather than a differently-shaped first.
+ const code = source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');
+ assert.match(code, /i18nReady\.then\(/, 'main.tsx no longer defers the first render until the catalogue is loaded');
+ assert.match(code, /const render = \(\) =>\s*createRoot\(/, 'the deferred render no longer owns the createRoot call');
+ assert.equal(
+ (code.match(/createRoot\(/g) ?? []).length,
+ 1,
+ 'main.tsx mounts more than once — a render that is not the deferred one does not wait for the catalogue',
);
});
diff --git a/dashboard/src/i18n/locales.test.ts b/dashboard/src/i18n/locales.test.ts
index bdbf23b30..d27d879dc 100644
--- a/dashboard/src/i18n/locales.test.ts
+++ b/dashboard/src/i18n/locales.test.ts
@@ -234,11 +234,27 @@ test('the locale loader imports the whole locales directory by variable', () =>
// Every catalogue used to be imported statically, which put all of them in one chunk the page
// preloaded to read a single language. A reinstated import would restore that quietly: the build
// stays green, the parity gates stay green, and only the byte count moves.
-test('no locale catalogue is imported statically', () => {
- const staticImports = [...I18N_INDEX_SOURCE.matchAll(/^import\s[^\n]*from\s*['"]\.\/locales\/[^\n]*$/gm)].map(
- m => m[0],
- );
- assert.deepEqual(staticImports, [], 'a static locale import is back — every language is on the critical path again');
+//
+// Scanned across the whole source tree rather than index.ts alone, because the bundler does not care
+// which module reaches a catalogue eagerly — one static import anywhere on a path the entry can
+// follow pulls that JSON back into a preloaded chunk. Matching `from '…'` covers default, named,
+// namespace and re-export forms including the ones Prettier wraps onto a second line, and bare
+// `import '…'` covers the side-effect form. Requiring whitespace after the keyword is what excludes
+// the loader's own `import(` — that one is a call, with a template literal rather than a quote.
+// Test files are exempt: they are outside the app build, so a catalogue they import eagerly costs
+// the bundle nothing.
+const SRC_DIR = join(dirname(fileURLToPath(import.meta.url)), '..');
+const STATIC_LOCALE_IMPORT = /(?:^|[\s{,])(?:from|import)\s+['"][^'"]*locales\/[^'"]*\.json['"]/;
+
+test('no locale catalogue is imported statically, anywhere in the dashboard source', () => {
+ const offenders = readdirSync(SRC_DIR, { recursive: true, withFileTypes: true })
+ .filter(entry => entry.isFile() && /\.tsx?$/.test(entry.name) && !entry.name.endsWith('.test.ts'))
+ .map(entry => join(entry.parentPath, entry.name))
+ .filter(file => STATIC_LOCALE_IMPORT.test(readFileSync(file, 'utf8')))
+ .map(file => file.slice(SRC_DIR.length + 1))
+ .sort();
+
+ assert.deepEqual(offenders, [], 'a static locale import is back — those languages are on the critical path again');
});
// rtlLanguages is deliberately a SUBSET (only he/ar today), so it is checked for validity, not parity:
diff --git a/dashboard/src/main.tsx b/dashboard/src/main.tsx
index ba39a5310..90b7def3c 100644
--- a/dashboard/src/main.tsx
+++ b/dashboard/src/main.tsx
@@ -13,8 +13,11 @@ if (storedTheme === 'light' || storedTheme === 'dark') {
}
// The active locale is fetched rather than bundled into the entry, so first paint waits for it —
-// otherwise the shell renders raw keys and swaps to real copy a tick later. Rendering on rejection
-// too: a locale that fails to load must degrade to untranslated text, never to a blank page.
+// otherwise the shell renders raw keys and swaps to real copy a tick later. A catalogue that fails
+// to arrive does not hold this up: i18next settles init either way, falling back to English or, if
+// nothing loads at all, to raw keys. The second handler is therefore belt and braces rather than the
+// live path — but it is what guarantees that no future change to that contract can leave the
+// dashboard blank, which is a worse failure than untranslated text.
const render = () =>
createRoot(document.getElementById('root')!).render(
<StrictMode>
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.ts
index 8c2d3dfe8..2b3b4df24 100644
--- a/dashboard/src/pages/Chats.test.ts
+++ b/dashboard/src/pages/Chats.test.ts
@@ -178,9 +178,13 @@ before(async () => {
// RoleProvider initializes from localStorage; 'admin' makes canWrite true so the composer
// controls render enabled.
window.localStorage.setItem('openwa_user_role', 'admin');
- // Side-effect import: initializes the real i18n instance with all locales (JSON modules are
- // handled by the registered loader hooks).
- await import('../i18n/index.ts');
+ // The real i18n instance, and then its readiness promise: catalogues are fetched rather than
+ // bundled, so importing the module only STARTS the load. Every `getByText` below is English copy
+ // out of en.json, which renders as a raw key until it lands. Awaiting is what makes that
+ // deterministic — without it the assertions race the load and win only because the module imports
+ // that follow take longer than reading one JSON file.
+ const { i18nReady } = await import('../i18n/index.ts');
+ await i18nReady;
rtl = await import('@testing-library/react');
({ RoleProvider } = await import('../components/RoleProvider.tsx'));
({ ToastProvider } = await import('../components/Toast.tsx'));
diff --git a/dashboard/src/pages/Infrastructure.test.ts b/dashboard/src/pages/Infrastructure.test.ts
index 0bb2ed91f..8f9978cb2 100644
--- a/dashboard/src/pages/Infrastructure.test.ts
+++ b/dashboard/src/pages/Infrastructure.test.ts
@@ -211,7 +211,10 @@ before(async () => {
({ installJsdomGlobals } = await import('../test-helpers/jsdom.ts'));
await installJsdomGlobals();
installFetchStub();
- await import('../i18n/index.ts');
+ // Awaited, not just imported: catalogues are fetched now, so the import only starts the load and
+ // the English copy these tests query by name renders as a raw key until it arrives.
+ const { i18nReady } = await import('../i18n/index.ts');
+ await i18nReady;
rtl = await import('@testing-library/react');
({ RoleProvider } = await import('../components/RoleProvider.tsx'));
({ ToastProvider } = await import('../components/Toast.tsx'));
diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.ts
index 5eb686334..61240d4d0 100644
--- a/dashboard/src/pages/Sessions.test.ts
+++ b/dashboard/src/pages/Sessions.test.ts
@@ -193,7 +193,10 @@ before(async () => {
// Deliberately NOT setting sessionStorage['openwa_api_key']: useWebSocket.connect() reads it and
// bails with a console.warn when it's absent. Setting it would make socket.io actually dial
// http://localhost/events and hit ECONNREFUSED in this environment.
- await import('../i18n/index.ts');
+ // Awaited, not just imported: catalogues are fetched now, so the import only starts the load and
+ // the English copy these tests query by name renders as a raw key until it arrives.
+ const { i18nReady } = await import('../i18n/index.ts');
+ await i18nReady;
rtl = await import('@testing-library/react');
({ RoleProvider } = await import('../components/RoleProvider.tsx'));
({ ToastProvider } = await import('../components/Toast.tsx'));