/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import assert from 'node:assert/strict'; import test from 'node:test'; import { STORAGE_KEYS, bootstrapLanguage, browserFallbackLanguage, getBootConfig, rememberUserLanguage, resolveLocalLanguage, storeBootResult, } from './bootstrap.js'; const memoryStorage = (initial = {}) => { const map = new Map(Object.entries(initial)); return { getItem: (key) => (map.has(key) ? map.get(key) : null), setItem: (key, value) => map.set(key, String(value)), removeItem: (key) => map.delete(key), has: (key) => map.has(key), }; }; const config = (overrides = {}) => ({ enabled_languages: ['zh', 'zh-TW', 'en', 'ja', 'ko', 'vi', 'th'], default_language: 'en', language_switch_enabled: true, hash: 'abcd1234', ...overrides, }); const bootJSON = (language, overrides) => JSON.stringify({ language, config: config(overrides) }); const makeEnv = (overrides = {}) => { const calls = []; const env = { local: memoryStorage({ [STORAGE_KEYS.migrated]: '1' }), session: memoryStorage(), search: '', navigatorLanguages: ['en-US'], fetchLocale: async () => null, loadLanguage: async (code) => calls.push(`load:${code}`), requestTimeoutMs: 30, loadTimeoutMs: 30, ...overrides, }; const i18n = { language: 'zh', async changeLanguage(code) { calls.push(`change:${code}`); this.language = code; }, }; return { env, i18n, calls }; }; const never = () => new Promise(() => {}); test('local priority: session > user choice > cached server result', () => { const boot = { language: 'ja', config: config() }; assert.deepEqual( resolveLocalLanguage({ sessionLanguage: 'th', userChoice: 'ko', boot }), { language: 'th', source: 'query' }, ); assert.deepEqual(resolveLocalLanguage({ userChoice: 'zh-HK', boot }), { language: 'zh-TW', source: 'user', }); assert.deepEqual(resolveLocalLanguage({ boot }), { language: 'ja', source: 'cache', }); assert.equal(resolveLocalLanguage({}), null); }); test('switch disabled ignores user choice; disabled languages are skipped', () => { assert.deepEqual( resolveLocalLanguage({ userChoice: 'ko', boot: { language: 'ja', config: config({ language_switch_enabled: false }), }, }), { language: 'ja', source: 'cache' }, ); assert.equal( resolveLocalLanguage({ sessionLanguage: 'th', userChoice: 'th', boot: { language: 'th', config: config({ enabled_languages: ['en'] }) }, }), null, ); assert.equal( resolveLocalLanguage({ sessionLanguage: 'fr', userChoice: '' }), null, ); }); test('browser fallback maps to a catalog language or en', () => { assert.equal(browserFallbackLanguage(['fr-FR', 'zh-HK', 'en']), 'zh-TW'); assert.equal(browserFallbackLanguage(['fr', 'de']), 'zh'); assert.equal(browserFallbackLanguage(undefined), 'zh'); }); test('first visit waits for server result and caches it', async () => { let params; const { env, i18n, calls } = makeEnv({ fetchLocale: async (p) => { params = p; return { language: 'ja', source: 'ip', config: config() }; }, }); const result = await bootstrapLanguage(i18n, env); assert.equal(result.language, 'ja'); assert.equal(result.source, 'ip'); assert.deepEqual(calls, ['load:ja', 'change:ja']); assert.deepEqual(params, { user_lang: '', browser: 'en-US' }); assert.deepEqual(JSON.parse(env.local.getItem(STORAGE_KEYS.boot)), { language: 'ja', config: config(), }); }); test('first visit timeout falls back to browser language', async () => { const { env, i18n } = makeEnv({ fetchLocale: never, navigatorLanguages: ['fr-FR', 'ko-KR'], }); const result = await bootstrapLanguage(i18n, env); assert.equal(result.language, 'ko'); assert.equal(result.source, 'fallback'); }); test('cached result renders immediately and refreshes in background for next visit', async () => { const { env, i18n } = makeEnv({ fetchLocale: async () => ({ language: 'zh-TW', source: 'ip', config: config({ hash: 'new' }), }), }); env.local.setItem(STORAGE_KEYS.boot, bootJSON('ja')); const result = await bootstrapLanguage(i18n, env); assert.equal(result.language, 'ja', 'must not switch language mid-session'); await result.refresh; assert.equal( JSON.parse(env.local.getItem(STORAGE_KEYS.boot)).language, 'zh-TW', ); // 挂起的请求也不能阻塞有缓存时的启动 const pending = makeEnv({ fetchLocale: never }); pending.env.local.setItem(STORAGE_KEYS.boot, bootJSON('ko')); assert.equal( (await bootstrapLanguage(pending.i18n, pending.env)).language, 'ko', ); }); test('failed refresh keeps the previous cache', async () => { const { env, i18n } = makeEnv({ fetchLocale: async () => { throw new Error('network'); }, }); env.local.setItem(STORAGE_KEYS.boot, bootJSON('vi')); const result = await bootstrapLanguage(i18n, env); assert.equal(result.language, 'vi'); assert.equal(await result.refresh, null); assert.equal(JSON.parse(env.local.getItem(STORAGE_KEYS.boot)).language, 'vi'); }); test('?lang= wins for the session and is not sent to the server', async () => { let params; const { env, i18n } = makeEnv({ search: '?lang=th-TH', fetchLocale: async (p) => { params = p; return { language: 'en', source: 'default', config: config() }; }, }); env.local.setItem(STORAGE_KEYS.userChoice, 'ko'); const result = await bootstrapLanguage(i18n, env); assert.equal(result.language, 'th'); assert.equal(env.session.getItem(STORAGE_KEYS.session), 'th'); assert.equal(params.lang, undefined); assert.equal(params.user_lang, 'ko'); // 同会话内跳转(URL 不再带参数)仍保持 const next = await bootstrapLanguage(i18n, { ...env, search: '' }); assert.equal(next.language, 'th'); }); test('valid ?lang= is stripped from the address bar; invalid one is left alone', async () => { let stripped = 0; const valid = makeEnv({ search: '?lang=ja&from=ad', stripLangParam: () => stripped++, }); await bootstrapLanguage(valid.i18n, valid.env); assert.equal(stripped, 1); const invalid = makeEnv({ search: '?lang=fr', stripLangParam: () => stripped++, }); await bootstrapLanguage(invalid.i18n, invalid.env); assert.equal(stripped, 1); }); test('boot update is announced only after a successful refresh', async () => { let announced = 0; const ok = makeEnv({ fetchLocale: async () => ({ language: 'ja', config: config() }), onBootUpdated: () => announced++, }); await ( await bootstrapLanguage(ok.i18n, ok.env) ).refresh; assert.equal(announced, 1); const failed = makeEnv({ fetchLocale: async () => { throw new Error('network'); }, onBootUpdated: () => announced++, }); await ( await bootstrapLanguage(failed.i18n, failed.env) ).refresh; assert.equal(announced, 1); }); test('storeBootResult writes cache and notifies only for a real result', () => { const local = memoryStorage(); let notified = 0; const notify = () => notified++; assert.equal(storeBootResult(null, { local, notify }), false); assert.equal(storeBootResult({ source: 'ip' }, { local, notify }), false); assert.equal(local.has(STORAGE_KEYS.boot), false); assert.equal(notified, 0); assert.equal( storeBootResult({ language: 'ko', config: config() }, { local, notify }), true, ); assert.deepEqual(JSON.parse(local.getItem(STORAGE_KEYS.boot)), { language: 'ko', config: config(), }); assert.equal(notified, 1); }); test('hanging language pack still renders after the load timeout', async () => { const { env, i18n, calls } = makeEnv({ fetchLocale: async () => ({ language: 'th', config: config() }), loadLanguage: () => new Promise(() => {}), }); const result = await bootstrapLanguage(i18n, env); assert.equal(result.language, 'th'); assert.deepEqual(calls, ['change:th']); }); test('cached start changes language exactly once, even after refresh resolves', async () => { const { env, i18n, calls } = makeEnv({ fetchLocale: async () => ({ language: 'ko', config: config() }), }); env.local.setItem(STORAGE_KEYS.boot, bootJSON('ja')); const result = await bootstrapLanguage(i18n, env); await result.refresh; assert.deepEqual(calls, ['load:ja', 'change:ja']); }); test('cached language disabled by the cached config falls through to the server', async () => { const { env, i18n } = makeEnv({ fetchLocale: async () => ({ language: 'en', source: 'default', config: config(), }), }); env.local.setItem( STORAGE_KEYS.boot, bootJSON('th', { enabled_languages: ['en', 'ja'] }), ); const result = await bootstrapLanguage(i18n, env); assert.equal(result.language, 'en'); assert.equal(result.source, 'default'); }); // 首访没有缓存配置时,?lang= 与旧手选都必须先经服务端下发的启用语言白名单(R82 F1) test('first visit validates ?lang= and stored choice against the served config', async () => { const served = config({ enabled_languages: ['zh', 'en'] }); const disabled = makeEnv({ search: '?lang=ja', fetchLocale: async () => ({ language: 'en', source: 'default', config: served, }), }); const blocked = await bootstrapLanguage(disabled.i18n, disabled.env); assert.equal(blocked.language, 'en'); assert.equal(blocked.source, 'default'); const stored = makeEnv({ fetchLocale: async () => ({ language: 'en', source: 'default', config: served, }), }); stored.env.local.setItem(STORAGE_KEYS.userChoice, 'ja'); assert.equal( (await bootstrapLanguage(stored.i18n, stored.env)).language, 'en', ); const allowed = makeEnv({ search: '?lang=ja', fetchLocale: async () => ({ language: 'en', source: 'default', config: config(), }), }); const kept = await bootstrapLanguage(allowed.i18n, allowed.env); assert.equal(kept.language, 'ja'); assert.equal(kept.source, 'query'); // 配置拿不到(超时/离线)时才退回目录级校验,保证分享链接仍可用 const offline = makeEnv({ search: '?lang=ja', fetchLocale: never }); const best = await bootstrapLanguage(offline.i18n, offline.env); assert.equal(best.language, 'ja'); assert.equal(best.source, 'fallback'); }); test('candidates are not accepted while the enabled list is unknown', () => { assert.equal( resolveLocalLanguage({ sessionLanguage: 'ja', boot: null }), null, ); assert.equal(resolveLocalLanguage({ userChoice: 'ja', boot: null }), null); assert.equal( resolveLocalLanguage({ userChoice: 'ja', boot: { language: 'ja', config: {} }, }), null, ); }); // 生产默认超时此前从未被执行:所有用例都注入 30ms,把默认值放大 1000× 也全绿(R85 ③-5)。 test('default request timeout keeps the first paint under ~1s', async () => { const { env, i18n } = makeEnv({ fetchLocale: never }); delete env.requestTimeoutMs; delete env.loadTimeoutMs; const started = Date.now(); const result = await bootstrapLanguage(i18n, env); const elapsed = Date.now() - started; assert.equal(result.source, 'fallback'); assert.ok( elapsed >= 300 && elapsed < 1500, `首访等待 ${elapsed}ms,应落在 500ms 量级(默认 LOCALE_REQUEST_TIMEOUT_MS)`, ); }); // 语言包 chunk 404 时应立即回退渲染,而不是干等满加载超时(R85 ③-5)。 test('rejected language pack falls through immediately', async () => { const { env, i18n, calls } = makeEnv({ fetchLocale: async () => ({ language: 'th', config: config() }), loadLanguage: async () => { throw new Error('chunk 404'); }, loadTimeoutMs: 5000, }); const started = Date.now(); const result = await bootstrapLanguage(i18n, env); const elapsed = Date.now() - started; assert.equal(result.language, 'th'); assert.deepEqual(calls, ['change:th']); assert.ok(elapsed < 1000, `加载失败应立即继续,实际等待 ${elapsed}ms`); }); test('getBootConfig exposes the cached public config', () => { const local = memoryStorage(); assert.equal(getBootConfig(local), null); local.setItem(STORAGE_KEYS.boot, bootJSON('ja')); assert.deepEqual(getBootConfig(local), config()); local.setItem(STORAGE_KEYS.boot, 'not json'); assert.equal(getBootConfig(local), null); }); test('missing language_switch_enabled is treated as enabled', () => { const partial = config(); delete partial.language_switch_enabled; assert.deepEqual( resolveLocalLanguage({ userChoice: 'ko', boot: { language: 'ja', config: partial }, }), { language: 'ko', source: 'user' }, ); }); test('offline fallback prefers the session parameter over the stored choice', async () => { const { env, i18n } = makeEnv({ search: '?lang=th', fetchLocale: never }); env.local.setItem(STORAGE_KEYS.userChoice, 'ko'); const result = await bootstrapLanguage(i18n, env); assert.equal(result.language, 'th'); }); test('legacy i18nextLng is removed exactly once', async () => { const { env, i18n } = makeEnv(); env.local.removeItem(STORAGE_KEYS.migrated); env.local.setItem(STORAGE_KEYS.legacy, 'en-US'); await bootstrapLanguage(i18n, env); assert.equal(env.local.has(STORAGE_KEYS.legacy), false); assert.equal(env.local.getItem(STORAGE_KEYS.migrated), '1'); env.local.setItem(STORAGE_KEYS.legacy, 'ja'); await bootstrapLanguage(i18n, env); assert.equal(env.local.getItem(STORAGE_KEYS.legacy), 'ja'); }); test('rememberUserLanguage stores explicit choice and clears session override', () => { const local = memoryStorage(); const session = memoryStorage({ [STORAGE_KEYS.session]: 'th' }); assert.equal(rememberUserLanguage('ja-JP', { local, session }), 'ja'); assert.equal(local.getItem(STORAGE_KEYS.userChoice), 'ja'); assert.equal(session.has(STORAGE_KEYS.session), false); assert.equal(rememberUserLanguage('fr', { local, session }), ''); assert.equal(local.getItem(STORAGE_KEYS.userChoice), 'ja'); }); test('throwing storage never breaks startup', async () => { const broken = { getItem() { throw new Error('denied'); }, setItem() { throw new Error('denied'); }, removeItem() { throw new Error('denied'); }, }; const { env, i18n } = makeEnv({ local: broken, session: broken, fetchLocale: async () => ({ language: 'ko', config: config() }), }); assert.equal((await bootstrapLanguage(i18n, env)).language, 'ko'); });