Skip to content

Commit 2e19f36

Browse files
fix(console): the language seed's me/localization leaves at parse time, beside discovery (#35618)
Fixes #35534 Refs #35455 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:新设备首次打开控制台时,取界面语言的请求在页面一开始就发出,不再等整包脚本下载完;托管环境下首屏可少等约一次服务器往返,语言判断结果不变。 - 为什么做:属于“控制台首屏请求串行”专题(托管环境打开要 9–10 秒),这是其中语言请求那一段等待。 - 出错会怎样:最坏情况是首次访问多发一次语言请求,或界面先用默认语言;直接撤回本次合并即可恢复原样。 - 要你做什么:无。 ## What changes On a device's true first visit (no stored language choice, no cached seed), `seedTenantLanguage()` asks `GET /api/v1/auth/me/localization` before React mounts. Asked from the bundle, that request waited for the 105-file eager module graph to download and evaluate. It needs only discovery's `locale.supported`, and discovery is already a parse-time request. 1. **`index.html` gets a parse-time `startEarlyLanguageSeed` script, after `startEarlyDiscovery`.** It applies the seed's own gates: an explicit choice (`objectui-locale`) or a cached seed (`objectui-locale-seed`) sends nothing, and blocked storage reads as neither, as in the seed. Like the seed, it does not wait for the session. It hangs off the parse-time discovery answer and sends the seed's request byte for byte: the same URL through the same `%VITE_SERVER_URL%` substitution, `credentials: 'include'`, the same `Accept`, and the same `Accept-Language`. That header is the browser's language in the app's spelling when `locale.supported` lists it, else none (ruling 6915665005, #34392). The pending `Response` goes into `Symbol.for('objectui.earlyLanguageSeed')`. A failed discovery sends nothing. 2. **`languageSeed.ts` takes it once (`takeEarlySeedRequest`), only when it is the request the seed would send.** The test is an equal `inflightGetKey`: URL, credentials and headers, `Accept-Language` included. The seed hands the parse-time response to the same `sharedGetJson` call as its transport. Unchanged: the in-flight sharing with `LocalizationFetchProvider`, the error path, slice 1's settled-answer hand-off, and the 500 ms race with its fallback. The first look spends the slot, and the script sends nothing after it. So a mismatch, or a script that has not sent yet, leaves exactly one request: the seed's own. 3. **The language ladder is spelled a second time, inside the inline script.** It is `resolveLocaleAmong` over the platform locale table, copied because a classic inline script cannot import. That copy can never change the language: the seed takes only a byte-equal request. A drift therefore costs one extra request, and a matrix pin catches it (Tests). `main.tsx` and `LocalizationFetchProvider.tsx` are not edited. No spec, server, `ui/packages/**`, endpoint or i18n key is touched. ## Tests New top-level describe in `ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx` (the parse-time harness: it executes the shipped `index.html` scripts against the real modules): - The script is one inline classic script, placed after the discovery script it reads. - It leaves once discovery answers, before any bundle code runs, with the stated language (A3 pin 1). - One cold load, one `me/localization` (A3 pin 2). End to end with `VITE_SERVER_URL` set: the parse-time request, then the real `seedTenantLanguage()` (seed cached before the race resolves, so the locale is still applied before first paint), then the real `LocalizationFetchProvider` served from the seed's settled answer. One request, one discovery. - Drift pin: the parse-time `Accept-Language` equals the real `pickPreferredLocale()` for every platform tag and read alias (enumerated from `@objectstack/spec/system`, upper-cased too, plus non-table tags) against 34 supported lists. - CONTROL: a parse-time request the seed would not send is never taken. The seed sends its own, with the right header. - CONTROL: a stored explicit language choice still wins, and a cached seed still applies. Nothing is sent at parse time or by the seed. - CONTROL: a signed-out first visit sends one request, as the seed did, and caches nothing. - CONTROL: the race keeps its bound and its fallback. With the request still open the boot goes on unseeded, the late answer is cached for the next boot, and a provider mounted meanwhile joins the same request. - CONTROL: a failed parse-time discovery sends nothing early. The seed asks for both itself, once each. - Blocked storage still sends, as the seed does. <details><summary>Runs (product code and tests at e422cc7; head 1562fae adds only the changeset)</summary> - Under the verify lock: `pnpm exec vitest run --maxWorkers=2` on `sessionCheckBootDedup.test.tsx`, `localizationBootDedup.test.tsx`, `languageSeed.test.ts`, `LocalizationFetchProvider.test.tsx`: `Test Files 4 passed (4)`, `Tests 101 passed (101)`, `VERDICT command-exit 0`. The drift matrix takes 2.7 s. - `pnpm --filter @object-ui/console run type-check`: `VERDICT command-exit 0`. `--listFiles` includes the test file. - eslint over `languageSeed.ts` and the test file: exit 0. - `pnpm --dir ui exec vitest run --maxWorkers=2 scripts/` (derived): `Test Files 171 passed | 2 skipped (173)`, `VERDICT command-exit 0`. `pnpm check:new-line-citations`: 0 new citations. - Ablation 1, with `scripts/ablation-replace.mjs` (`anchor 1 -> 0`, restored `blob == HEAD`, `git diff HEAD` empty): the seed no longer takes the parse-time response. Three pins go red with `expected ... to have a length of 1 but got 2`: one cold load, signed out, and the race. `Tests 3 failed | 45 passed (48)`. - Ablation 2, the same tool: the inline alias `'zh-TW': 'zh-Hant'` is dropped. The drift pin goes red, e.g. `"zh-HK" among ["zh-CN","zh-TW"]: sent zh-CN, seed zh-TW`. `Tests 1 failed | 47 passed (48)`. </details> <details><summary>Readings: A1-A3, built console, before (e25ca63) and after (this branch)</summary> Method: a turbo build of the showcase closure and `@object-ui/console` in this tree, then `packages/console/build-dist.sh`, served by `objectstack dev --fresh` from `examples/app-showcase` on a private port. Headless Chromium 1440x900, a new context per load. Resource Timing, plus the CDP initiator of every `me/localization`. Layer = chain depth, as in the #35455 report. cold = cookie only (no Bearer, no stored language, no seed). warm = cookie + Bearer. signed out = no cookie. Shared 4-core box, so the times are shared-box ms. A1 (before, e25ca63): the seed's request is module-issued (`framework-*.js` frames) on 15/15 loads. It leaves at 466-563 ms cold, 429-519 ms warm and 451-644 ms signed out. Every load fetched 105 JS files first; the last one ended at 315-514 ms. A2: the parse-time point with `locale.supported` is the `startEarlyDiscovery` answer. The new script is chained on it. The seed takes the pending `Response` through `sharedGetJson`'s transport argument after an `inflightGetKey` equality check. | page / posture | me/localization leaves, before | after | initiator before -> after | me/localization count before -> after | chain depth before | after | |:--|:--|:--|:--|:--|:--|:--| | list cold | 529 / 522 / 466 ms | 149 / 81 / 159 ms | module -> inline index.html | 1/1/1 -> 1/1/1 | 9 / 10 / 11 | 10 / 11 / 11 | | record cold | 563 / 561 / 506 | 86 / 83 / 166 | module -> inline | 1/1/1 -> 1/1/1 | 12 / 12 / 11 | 12 / 12 / 12 | | list warm | 456 / 466 / 519 | 121 / 176 / 187 | module -> inline | 1/1/1 -> 1/1/1 | 10 / 11 / 10 | 9 / 11 / 11 | | record warm | 474 / 491 / 429 | 133 / 159 / 93 | module -> inline | 1/1/1 -> 1/1/1 | 12 / 11 / 12 | 12 / 11 / 12 | | signed out (lands on /login) | 451 / 636 / 644 | 116 / 137 / 199 | module -> inline | 1/1/1 -> 1/1/1 | 4 / 4 / 4 | 4 / 4 / 4 | The request keeps its layer (L2, after discovery), so chain depth does not move. The gain is wall time on the path to the mount: locally the seed's own round trip was 10-17 ms, so the local mount barely moves. Latency probe (`me/localization` responses held 300 ms, list cold, 3 loads each): the first post-mount request (`me/permissions`) left at 937 / 993 / 935 ms before and 610 / 551 / 552 ms after. The first data read left at 1946 / 2211 / 1634 ms before and 1664 / 1601 / 1483 ms after. Every load stated `Accept-Language: en` in both builds, the same language. </details> ## Acceptance notes - The language ladder now has a third spelling, in `index.html`, beside `resolveLocaleAmong` and the spec table it reads. The inline script cannot import, and the alternatives were outside this card's fence: a build-time HTML transform in `vite.config.ts`, or a server change. A drift there costs one request and never a language, because the seed takes only a byte-equal request. The drift pin enumerates the spec's own table, so a new tag or alias in the spec reds this test until the inline copy follows. - The owner count for the slice-1 hand-off is read when the seed takes the request, as before. The parse-time request carries the cookie session the page was loaded with, the same session the discovery and get-session hand-offs already assume. - A1 also shows the signed-out first visit sends `me/localization` (answered `authenticated: false`). That is unchanged and kept on purpose: the seed has never waited on the session, and the dispatch says to keep what it does today. ## Verification Read first, by risk: `ui/apps/console/index.html` `startEarlyLanguageSeed` (the gates and `resolveAmong`); `ui/apps/console/src/languageSeed.ts` `takeEarlySeedRequest` and the `sharedGetJson` transport argument; the new describe's drift-matrix test. Two minutes: `cd ui && pnpm exec vitest run apps/console/src/__tests__/sessionCheckBootDedup.test.tsx`. Expect 48 tests green, 11 of them in the describe named for this card. --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CZrgaiMgTJCnswR6jQ)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent b38e133 commit 2e19f36

4 files changed

Lines changed: 374 additions & 1 deletion

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/console': patch
3+
---
4+
5+
fix(console): the language seed's `me/localization` leaves at parse time, beside discovery
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
On a device's first visit the console's language seed asked `GET /api/v1/auth/me/localization` from the bundle, so the request waited for the whole eager module graph to download and evaluate, about half a second after navigation on a local server and longer on a hosted one. It needs nothing from the bundle except discovery's `locale.supported`, which `index.html` already asks for during parse. A new parse-time script now asks the seed's question the moment that discovery answers, under the seed's own gates (no stored language choice, no cached seed), and leaves the pending response for the seed. The seed takes it once, and only when it is exactly the request it would send itself, `Accept-Language` included, so the page still sends one `me/localization` and the language it picks is unchanged. The seed's 500 ms race and its fallback, the in-flight sharing with the localization provider and the hand-off of the settled answer are unchanged. A failed parse-time discovery sends nothing early, and the seed asks as before.

‎ui/apps/console/index.html‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,108 @@
258258
globalThis[Symbol.for('objectui.earlyDiscovery')] = { url: url, token: token, body: body };
259259
})();
260260
</script>
261+
<!--
262+
The language seed's `GET /api/v1/auth/me/localization`, started during
263+
parse as soon as `discovery` above answers (objectstack#35534).
264+
265+
On a device's true first visit `seedTenantLanguage()` in
266+
`src/languageSeed.ts` asks this endpoint before React mounts. Asked from
267+
the bundle, it waited for the eager module graph to download and
268+
evaluate, though it needs nothing from the bundle: only discovery's
269+
`locale.supported`, which the script above has already asked for. This
270+
script asks the seed's question the moment discovery answers and leaves
271+
the pending response for the seed, which takes it once, as its one
272+
request. The seed's 500 ms race and its fallback are unchanged.
273+
274+
It asks only when the seed would: no explicit language choice
275+
(`objectui-locale`) and no cached seed (`objectui-locale-seed`). Blocked
276+
storage reads as neither, as it does in the seed. Like the seed it does
277+
not wait for the session: signed out, the server answers
278+
`{ authenticated: false }` and the seed caches nothing.
279+
280+
The request is the seed's byte for byte: the same URL (the server origin
281+
through the same Vite HTML env substitution as the scripts above),
282+
`credentials: 'include'`, the same `Accept`, and the same
283+
`Accept-Language`: the browser's language in the app's own spelling when
284+
discovery `locale.supported` lists it, else none (ruling 6915665005,
285+
objectstack#34392). "Lists it" is the platform's one locale ladder,
286+
`resolveLocaleAmong` over the platform locale table in
287+
`@objectstack/spec/system`, spelled again here because a classic inline
288+
script cannot import. The seed takes the response only when its own
289+
request would be the same one (the in-flight key: URL, credentials and
290+
headers), so a drift between the two spellings costs a request and never
291+
changes the language. A failed discovery sends nothing here, and nothing
292+
is sent once the seed has looked: the seed then asks itself, as before.
293+
294+
`src/__tests__/sessionCheckBootDedup.test.tsx` executes THIS script's
295+
text against the real `seedTenantLanguage()` and `pickPreferredLocale()`,
296+
the latter over every tag and alias of the platform table, so a drift
297+
fails a test rather than silently adding the request back.
298+
-->
299+
<script>
300+
(function startEarlyLanguageSeed() {
301+
try {
302+
if (localStorage.getItem('objectui-locale')) return; // the user's choice outranks a seed
303+
if (localStorage.getItem('objectui-locale-seed')) return; // a cached seed applies at once
304+
} catch (_) { /* storage blocked: the seed reads neither, and asks */ }
305+
const discovery = globalThis[Symbol.for('objectui.earlyDiscovery')];
306+
if (!discovery) return;
307+
308+
const injected = '%VITE_SERVER_URL%';
309+
const base = (injected.charAt(0) === '%' ? '' : injected).replace(/\/+$/, '');
310+
const slot = { url: base + '/api/v1/auth/me/localization', init: null, response: null, taken: false };
311+
globalThis[Symbol.for('objectui.earlyLanguageSeed')] = slot;
312+
313+
// The platform locale table: its tags, and its read aliases, case-folded.
314+
const TAGS = ['en', 'zh-Hans', 'zh-Hant', 'es', 'ar', 'fr', 'pt-BR', 'ru', 'de', 'ja', 'ko'];
315+
const ALIASES = {
316+
zh: 'zh-Hans', 'zh-CN': 'zh-Hans', 'zh-SG': 'zh-Hans',
317+
'zh-TW': 'zh-Hant', 'zh-HK': 'zh-Hant', 'zh-MO': 'zh-Hant',
318+
'zh-Hans-CN': 'zh-Hans', 'zh-Hans-SG': 'zh-Hans',
319+
'zh-Hant-TW': 'zh-Hant', 'zh-Hant-HK': 'zh-Hant', 'zh-Hant-MO': 'zh-Hant',
320+
'ja-JP': 'ja', 'es-ES': 'es', pt: 'pt-BR', 'en-US': 'en',
321+
};
322+
const TAG_BY_FOLDED = new Map();
323+
TAGS.forEach(function (tag) { TAG_BY_FOLDED.set(tag.toLowerCase(), tag); });
324+
Object.keys(ALIASES).forEach(function (code) { TAG_BY_FOLDED.set(code.toLowerCase(), ALIASES[code]); });
325+
const fold = function (code) { return code.toLowerCase(); };
326+
const tagOf = function (code) { return TAG_BY_FOLDED.get(fold(code)); };
327+
// `resolveLocaleAmong`: exact, case, table language, base language, first variant.
328+
function resolveAmong(requested, available) {
329+
if (available.indexOf(requested) !== -1) return requested;
330+
const lower = fold(requested);
331+
const caseMatch = available.find(function (code) { return fold(code) === lower; });
332+
if (caseMatch) return caseMatch;
333+
const tag = tagOf(requested);
334+
const tagMatch = tag === undefined ? undefined
335+
: available.find(function (code) { return fold(code) === fold(tag); })
336+
|| available.find(function (code) { return tagOf(code) === tag; });
337+
if (tagMatch) return tagMatch;
338+
const lang = lower.split('-')[0];
339+
return available.find(function (code) { return fold(code) === lang; })
340+
|| available.find(function (code) { return fold(code).split('-')[0] === lang; });
341+
}
342+
343+
discovery.body.then(function (doc) {
344+
if (slot.taken) return;
345+
// `early-discovery.ts` unwraps the envelope; `languageSeed.ts` reads the list.
346+
if (doc && typeof doc === 'object' && typeof doc.success === 'boolean' && 'data' in doc) doc = doc.data;
347+
const listed = doc && doc.locale ? doc.locale.supported : undefined;
348+
const supported = Array.isArray(listed)
349+
? listed.filter(function (entry) { return typeof entry === 'string' && entry.length > 0; })
350+
: [];
351+
const browser = typeof navigator === 'undefined' || typeof navigator.language !== 'string'
352+
? '' : navigator.language.trim();
353+
const preferred = browser ? resolveAmong(browser, supported) : undefined;
354+
const headers = { Accept: 'application/json' };
355+
if (preferred) headers['Accept-Language'] = preferred;
356+
slot.init = { credentials: 'include', headers: headers };
357+
slot.response = fetch(slot.url, slot.init);
358+
// The seed reads a failure as its own request's; it is never unhandled.
359+
slot.response.catch(function () {});
360+
}, function () { /* discovery failed: the seed asks for it, then the server, itself */ });
361+
})();
362+
</script>
261363
<script>
262364
window.process = window.process || { env: { NODE_ENV: 'development' }, version: '', platform: 'browser' };
263365
</script>

‎ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx‎

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ import { readConsoleDiscovery } from '../lib/early-discovery';
2727
import { getSharedDiscovery } from '@object-ui/data-objectstack';
2828
import { clearSharedDiscoveryCache } from '../../../../packages/data-objectstack/src/sharedDiscovery';
2929
import { SessionUserScope } from '../../../../packages/auth/src/ActiveOrganizationStorage';
30+
import { resetInflightGetsForTesting } from '../../../../packages/types/src/http-inflight';
31+
import { readCachedLanguageSeed, useLocalization } from '@object-ui/i18n';
32+
import { PLATFORM_LOCALE_READ_ALIASES, PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system';
33+
import { __resetPreferredLocaleForTests, pickPreferredLocale, seedTenantLanguage } from '../languageSeed';
34+
import { LocalizationFetchProvider } from '../LocalizationFetchProvider';
3035

3136
const TOKEN = 'tok_valid';
3237
const EARLY_SLOT = Symbol.for('objectui.earlySessionCheck');
@@ -82,9 +87,13 @@ const urlOf = (input: RequestInfo | URL) =>
8287
typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
8388

8489
let sessionAnswer: () => Response | Promise<Response> = () => json(SESSION_BODY);
90+
let discoveryAnswer: () => Response | Promise<Response> = () => json(null);
91+
let localizationAnswer: () => Response | Promise<Response> = () => json(null);
8592
const fetchStub = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => {
8693
const url = urlOf(input);
8794
if (url.includes('/get-session')) return sessionAnswer();
95+
if (url.includes('/discovery')) return discoveryAnswer();
96+
if (url.includes('/me/localization')) return localizationAnswer();
8897
if (url.includes('/runtime/config')) return json({ branding: {} });
8998
if (url.includes('/organization/')) return json([]);
9099
return json(null);
@@ -108,6 +117,8 @@ beforeEach(() => {
108117
vi.stubGlobal('fetch', fetchStub);
109118
fetchStub.mockClear();
110119
sessionAnswer = () => json(SESSION_BODY);
120+
discoveryAnswer = () => json(null);
121+
localizationAnswer = () => json(null);
111122
localStorage.clear();
112123
clearSlots();
113124
});
@@ -685,3 +696,205 @@ describe('discovery starts at parse time beside get-session, and the console rea
685696
expect(discoveryCalls()).toHaveLength(2);
686697
});
687698
});
699+
700+
describe("the language seed's me/localization starts at parse time beside discovery, and the seed takes it (objectstack#35534)", () => {
701+
const DISCOVERY_SLOT = Symbol.for('objectui.earlyDiscovery');
702+
const SEED_SLOT = Symbol.for('objectui.earlyLanguageSeed');
703+
const ME = '/api/v1/auth/me/localization';
704+
const SIGNED_IN = { authenticated: true, locale: 'zh-CN', currency: 'CNY', timezone: 'Asia/Shanghai' };
705+
const localizationCalls = () => fetchStub.mock.calls.filter(([input]) => urlOf(input).includes('/me/localization'));
706+
const discoveryCalls = () => fetchStub.mock.calls.filter(([input]) => urlOf(input).includes('/discovery'));
707+
const statedOf = (call: unknown[]) =>
708+
new Headers((call[1] as RequestInit | undefined)?.headers).get('Accept-Language');
709+
const serves = (supported: string[]) => () => json({ locale: { default: 'en', supported } });
710+
const browserSays = (tag: string) => vi.spyOn(window.navigator, 'language', 'get').mockReturnValue(tag);
711+
/** The two parse-time scripts this read needs, in document order. */
712+
const parse = (html?: string) => {
713+
runScript('startEarlyDiscovery', html);
714+
runScript('startEarlyLanguageSeed', html);
715+
};
716+
const forget = () => {
717+
const holder = globalThis as unknown as Record<symbol, unknown>;
718+
delete holder[DISCOVERY_SLOT];
719+
delete holder[SEED_SLOT];
720+
clearSharedDiscoveryCache();
721+
resetInflightGetsForTesting();
722+
__resetPreferredLocaleForTests();
723+
};
724+
725+
function Value() {
726+
const { locale, currency } = useLocalization();
727+
return <span data-testid="localization">{`${locale ?? '-'}/${currency ?? '-'}`}</span>;
728+
}
729+
730+
beforeEach(forget);
731+
afterEach(forget);
732+
733+
it('is exactly one inline classic script, after the discovery script it reads', () => {
734+
const scripts = inlineScripts(indexHtml);
735+
const at = (marker: string) => scripts.findIndex((body) => body.includes(marker));
736+
const source = extractScript('startEarlyLanguageSeed');
737+
expect(source).toContain("Symbol.for('objectui.earlyLanguageSeed')");
738+
expect(source).toContain("Symbol.for('objectui.earlyDiscovery')");
739+
expect(source).toContain('%VITE_SERVER_URL%');
740+
expect(at('startEarlyLanguageSeed')).toBeGreaterThan(at('startEarlyDiscovery'));
741+
});
742+
743+
it('leaves once discovery answers, before any bundle code runs, stating the supported browser language', async () => {
744+
discoveryAnswer = serves(['en', 'zh-CN']);
745+
browserSays('zh-CN');
746+
parse();
747+
// It waits for discovery's `locale.supported`, and for nothing else.
748+
expect(localizationCalls()).toHaveLength(0);
749+
await settle();
750+
751+
expect(localizationCalls()).toHaveLength(1);
752+
const [url, init] = localizationCalls()[0]!;
753+
expect(url).toBe(ME);
754+
expect(init).toMatchObject({ credentials: 'include' });
755+
expect(new Headers(init?.headers).get('Accept')).toBe('application/json');
756+
expect(statedOf(localizationCalls()[0]!)).toBe('zh-CN');
757+
});
758+
759+
it('one cold load, one me/localization: the seed takes the parse-time request and the provider its settled answer', async () => {
760+
const SERVER = 'https://api.example.test';
761+
discoveryAnswer = serves(['en', 'zh-CN']);
762+
localizationAnswer = () => json(SIGNED_IN);
763+
browserSays('zh-CN');
764+
parse(applyViteHtmlEnv(indexHtml, { VITE_SERVER_URL: `${SERVER}/` }));
765+
await settle();
766+
767+
await seedTenantLanguage(SERVER, 1_000);
768+
// The locale still applies before first paint: cached when the race resolves.
769+
expect(readCachedLanguageSeed()).toBe('zh-CN');
770+
render(
771+
<LocalizationFetchProvider endpoint={`${SERVER}${ME}`}>
772+
<Value />
773+
</LocalizationFetchProvider>,
774+
);
775+
expect(await screen.findByText('zh-CN/CNY')).toBeTruthy();
776+
777+
expect(localizationCalls()).toHaveLength(1);
778+
expect(localizationCalls()[0]![0]).toBe(`${SERVER}${ME}`);
779+
expect(discoveryCalls()).toHaveLength(1);
780+
});
781+
782+
it('states exactly what the seed states, for every platform tag and alias the browser may send', async () => {
783+
const codes = [...PLATFORM_LOCALE_TAGS, ...Object.keys(PLATFORM_LOCALE_READ_ALIASES)];
784+
const requested = [...codes, ...codes.map((c) => c.toUpperCase()), 'en-GB', 'es-MX', 'pt-PT', 'zh-Hant-US', 'fr-CA', 'xx', ' ja ', ''];
785+
const lists = [
786+
[],
787+
...codes.map((c) => [c]),
788+
['en', 'zh-CN', 'ja-JP', 'es-ES'],
789+
['zh-CN', 'zh-TW'],
790+
['zh-Hant', 'zh-CN'],
791+
['zh-TW', 'zh-Hans', 'en-US'],
792+
['es-ES', 'es', 'pt', 'pt-BR'],
793+
['EN', 'Zh-cn', 'de-AT'],
794+
[...PLATFORM_LOCALE_TAGS],
795+
];
796+
const misses: string[] = [];
797+
for (const supported of lists) {
798+
for (const tag of requested) {
799+
forget();
800+
fetchStub.mockClear();
801+
discoveryAnswer = serves(supported);
802+
browserSays(tag);
803+
parse();
804+
await settle();
805+
const sent = statedOf(localizationCalls()[0]!);
806+
const seed = pickPreferredLocale(tag, supported) ?? null;
807+
if (sent !== seed) misses.push(`${JSON.stringify(tag)} among ${JSON.stringify(supported)}: sent ${sent}, seed ${seed}`);
808+
}
809+
}
810+
expect(misses).toEqual([]);
811+
});
812+
813+
it('CONTROL: a parse-time request the seed would not send is never taken; the seed asks once itself', async () => {
814+
discoveryAnswer = serves(['en', 'zh-CN']);
815+
localizationAnswer = () => json(SIGNED_IN);
816+
browserSays('zh-CN');
817+
parse();
818+
await settle();
819+
// A drifted spelling of the ladder: the slot holds a different request.
820+
const slot = (globalThis as unknown as Record<symbol, { init: RequestInit }>)[SEED_SLOT]!;
821+
slot.init = { credentials: 'include', headers: { Accept: 'application/json', 'Accept-Language': 'en' } };
822+
823+
await seedTenantLanguage('', 1_000);
824+
825+
expect(localizationCalls()).toHaveLength(2);
826+
expect(statedOf(localizationCalls()[1]!)).toBe('zh-CN');
827+
expect(readCachedLanguageSeed()).toBe('zh-CN');
828+
});
829+
830+
it('CONTROL: a stored language choice still wins: nothing is asked, at parse time or by the seed', async () => {
831+
localStorage.setItem('objectui-locale', 'ja-JP');
832+
parse();
833+
await settle();
834+
await seedTenantLanguage('', 1_000);
835+
expect(localizationCalls()).toHaveLength(0);
836+
});
837+
838+
it('CONTROL: a cached seed applies at once: nothing is asked at parse time or by the seed', async () => {
839+
localStorage.setItem('objectui-locale-seed', 'de-DE');
840+
parse();
841+
await settle();
842+
await seedTenantLanguage('', 1_000);
843+
expect(localizationCalls()).toHaveLength(0);
844+
});
845+
846+
it('CONTROL: a signed-out first visit asks once, as the seed did, and caches nothing', async () => {
847+
localizationAnswer = () => json({ authenticated: false });
848+
parse();
849+
await settle();
850+
await seedTenantLanguage('', 1_000);
851+
expect(localizationCalls()).toHaveLength(1);
852+
expect(readCachedLanguageSeed()).toBeNull();
853+
});
854+
855+
it('CONTROL: the race keeps its bound and its fallback; a provider mounted meanwhile joins the request', async () => {
856+
let answer!: (response: Response) => void;
857+
localizationAnswer = () => new Promise<Response>((resolve) => { answer = resolve; });
858+
parse();
859+
await settle();
860+
expect(localizationCalls()).toHaveLength(1);
861+
862+
// The request is still open when the race's bound runs out: the boot goes on
863+
// unseeded, in the browser's language, and nothing is cached yet.
864+
await seedTenantLanguage('', 5);
865+
expect(readCachedLanguageSeed()).toBeNull();
866+
render(
867+
<LocalizationFetchProvider endpoint={ME}>
868+
<Value />
869+
</LocalizationFetchProvider>,
870+
);
871+
await settle();
872+
answer(json(SIGNED_IN));
873+
874+
// The late answer is cached for the next boot, and serves the provider.
875+
expect(await screen.findByText('zh-CN/CNY')).toBeTruthy();
876+
expect(readCachedLanguageSeed()).toBe('zh-CN');
877+
expect(localizationCalls()).toHaveLength(1);
878+
});
879+
880+
it('CONTROL: a failed parse-time discovery sends nothing early; the seed asks for both itself, once each', async () => {
881+
discoveryAnswer = () => json({ error: 'boom' }, 503);
882+
parse();
883+
await settle();
884+
expect(localizationCalls()).toHaveLength(0);
885+
886+
discoveryAnswer = serves(['en']);
887+
await seedTenantLanguage('', 1_000);
888+
expect(discoveryCalls()).toHaveLength(2);
889+
expect(localizationCalls()).toHaveLength(1);
890+
});
891+
892+
it('blocked storage asks, as the seed does, and the script does not throw', async () => {
893+
vi.spyOn(window, 'localStorage', 'get').mockImplementation(() => {
894+
throw new DOMException('blocked', 'SecurityError');
895+
});
896+
expect(() => parse()).not.toThrow();
897+
await settle();
898+
expect(localizationCalls()).toHaveLength(1);
899+
});
900+
});

0 commit comments

Comments
 (0)