Skip to content

Commit 1c5cee6

Browse files
fix(service-settings): judge OS_LOCALIZATION_LOCALE once the boot's locale list is whole, and one locale matcher for Setup and the IdP claim (#30589)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg21NveYnJ8STuX2gJsTgYaA)_ domain:server#4 · os-bill · session_01Utp6CZMkHvuDeVYgTD73qF ## 维护者速读 - **改了什么:** 三件事。①启动窗口:`OS_LOCALIZATION_LOCALE` 指定的语言如果要到 `kernel:ready` 期间才进语言列表(应用自建翻译项就是这时加载的),以前在 `kernel:ready` 早读的一方(auth 的邮件/短信默认语言)会把它判成 IGNORED 并丢掉;现在设置服务在 `kernel:bootstrapped` 之前不下"不在列表里"的结论,先让它生效,列表齐了再判一次,真不合法才报一次错并发变更事件让读方重读。②一个匹配器:Setup 默认语言的接受规则和 IdP 登录语言声明都改用 core 新导出的 `resolveOfferedLocale`,两边接受同一批写法。③更正 `auth-manager.ts` / `auth-plugin.ts` 里"邮件模板四种语言就是该设置的选项"的过期注释。 - **为什么改:** #30286 合入后的契约审查发现:启动窗口会把合法的环境变量误判丢弃(AGENTS.md "Startup registry reads");Setup 拒收 `fr-FR`(部署提供 `fr`)而 IdP 声明 `fr-FR` 能落到 `fr`,两扇门对同一种语言说法不一;注释描述的是 #30286 之前的世界。 - **风险与回滚:** 放宽(`Clause-②: yes (widening)`):Setup 现在还接受已提供语言的地区/基础写法和大小写变体(`fr` 提供时的 `fr-FR`、`zh-CN` 的 `zh-cn`),以前接受的值全部照旧。IdP 在同时提供 `zh-Hans`/`zh-Hant` 时把 `zh-TW` 落到繁体(以前落到先列出的简体)。一个真正不合法的 `OS_LOCALIZATION_LOCALE` 在 `kernel:ready` 期间会暂时生效,`kernel:bootstrapped` 时报错并通知读方改回;一次性读方(应用内联种子在 `kernel:ready` 读)会用到这个暂时值,无法再通知它改回。回滚即撤本 PR。 - **先看:** `packages/core/src/fallbacks/memory-i18n.ts` 的 `resolveOfferedLocale`;`settings-service.ts` 的 `holdOptionSourceVerdicts` / `sealOptionSources` / `holdsOptionSourceVerdict` 三段和 `effectiveEnvOverride` 里改动的一行;`settings-service-plugin.ts` 的两处接线。 - **两分钟验证:** `pnpm --filter @objectstack/service-settings exec vitest run --maxWorkers=2 src/localization-locale-options.test.ts`,预期 18 条全绿,其中"read while the boot is still filling the locale list"三条是启动窗口的钉子。 - **需要你做的:** 无需你本人决定(非 BREAKING,放宽),按席位流程审查合入。 Fixes #30456 Clause-②: yes (widening) — `@objectstack/core` exports `resolveOfferedLocale(requested, offered)`; `SettingsService` gains `holdOptionSourceVerdicts()` and `sealOptionSources()`. The save of `localization.locale` (`PUT /api/settings/localization`, `SettingsService.setMany`) and an `OS_LOCALIZATION_LOCALE` override now also accept a region or base of an offered language (`fr-FR` where `fr` is offered, `fr` where `fr-FR` is) and another case of an offered code (`zh-cn` for `zh-CN`); nothing accepted before is refused. The IdP locale claim (`resolveIdpLocale`) lands a script or region spelling on the offered code the platform locale table says it means (`zh-TW` on `zh-Hant`, not on a `zh-Hans` listed first). Metadata-protocol: none ## What changes ### 1. The boot window (`settings-service.ts`, `settings-service-plugin.ts`) Measured on `origin/main` 8e5fabe: `localization.locale`'s option source (#30286) reads the i18n service's `getLocales()`, and that list grows during `kernel:ready` when the i18n plugin syncs the app's authored translations (`service-i18n/src/i18n-service-plugin.ts`, `replaceAuthoredTranslations`). Auth's `applyLocalizationLocale` (`plugin-auth/src/auth-plugin.ts`) reads the key in its own `kernel:ready` handler. Whichever runs first decides: an `OS_LOCALIZATION_LOCALE=vi-VN` whose language arrives as an authored translation could be judged against a list without it, reported `IGNORED` at `error`, and auth kept the next layer's value for the rest of the process. That is the three-part shape AGENTS.md "Startup registry reads" names (a filling registry, a terminal "absent", recorded in a log and in the reader's state). Cure 3 of that section, seal then judge: - `holdOptionSourceVerdicts()`: `SettingsServicePlugin.init` calls it before registering the source. While held, an `OS_*` override on a **sourced** key that the source (or the declared table it stands in for, when the list is still empty) does not admit is taken in force, not reported, and remembered. `effectiveEnvOverride` changes by one condition: `if (rejected && !this.holdsOptionSourceVerdict(namespace, key))`. The other families (pattern, value domain, bounds, format) do not depend on the list and are judged at once, as before. - `sealOptionSources()`: the plugin calls it from `kernel:bootstrapped`, which the kernel fires after every `kernel:ready` handler. Each remembered key is judged again: one the list now admits stays in force and nothing is said; one it still does not admit is reported once through the existing `reportRejectedEnvOverride` (same message, same dedupe), and a settings change (`{ namespace, key, scope: 'global', action: 'set' }`) is emitted so a reader that applied the held value reads the key again. Auth's reader already subscribes to `localization` changes, so it re-applies without a code change. - A `SettingsService` constructed without the plugin is never held and judges at once, as before. ### 2. One matcher (`core`, `service-settings`, `plugin-auth`) `resolveOfferedLocale(requested, offered)` in `packages/core/src/fallbacks/memory-i18n.ts`, exported beside `resolveLocale`. It reuses `resolveLocale` rather than copying it: 1. `resolveLocale`'s exact and case-insensitive steps; 2. the platform locale table: an offered code that means the same table language (`platformLocaleTagOf`, through the read aliases), so `zh-TW` is `zh-Hant`, `zh-CN` is `zh-Hans`, `en-US` is `en`; 3. `resolveLocale` itself for the base-language and variant steps. Step 2 is what Setup's old `admits` did on its own, and it only changes `resolveLocale`'s answer where two offered codes share a base language and the table tells them apart (`zh-Hans`/`zh-Hant`), where `resolveLocale` takes the first listed. - Setup (`localization-locale-options.ts`): `admits(v)` is `resolveOfferedLocale(v, codes) !== undefined`, and a stored second spelling is served in the place of the code the matcher lands it on. The docblock's "`fr-FR` is not `fr`" is replaced by the matcher's rules. - IdP claim (`idp-locale-claim.ts`): `resolveIdpLocale` calls `resolveOfferedLocale` instead of `resolveLocale`; the stored value is still the supported code in the column's BCP-47 case. ### 3. The stale comment (`auth-manager.ts`, `auth-plugin.ts`) `AUTH_EMAIL_TEMPLATE_LOCALES`' docblock said those four "are also the four options the `localization.locale` setting offers, so the two ends agree by construction". Since #30286 the setting offers the deployment's list. The docblock now says how they agree: `normalizeAuthEmailLocale` maps a value onto a row spelling where one of the four means it and passes any other through, and `EmailService.sendTemplate` resolves it against the bundle's tags and falls back to the `en-US` row (`plugin-email/src/email-service.ts`, #28880 ladder). The same claim in the `applyLocalizationLocale` comment of `auth-plugin.ts` ("whose four options are exactly `AUTH_EMAIL_TEMPLATE_LOCALES`") is corrected the same way. Comments only. ## Tests - `service-settings/src/localization-locale-options.test.ts` (the component's shared harness, now 18): a new top-level describe boots a `LiteKernel` with a `kernel:ready` reader that runs before a stand-in i18n plugin grows its list in its own `kernel:ready` step: - `OS_LOCALIZATION_LOCALE=vi-VN`, list `['en']` gaining `vi-VN`: the reader's first read is `vi-VN` from `env`, every read stays `vi-VN`, and nothing is logged for the variable; - `OS_LOCALIZATION_LOCALE=xx-XX`, never offered: held at the first read, then exactly one `IGNORED` report and a re-read that lands on the manifest default; - a bare `SettingsService` judges at once; sealing it is a no-op. - Matcher through the real `PUT`/`GET` routes: `fr-FR` where `fr` is offered (served in `fr`'s place), `fr` where `fr-FR` is, `zh-cn` where `zh-CN` is, `zh-TW` where `zh-Hans` and `zh-Hant` are (served in `zh-Hant`'s place), `de-DE` still refused. The old pin "`fr-FR` refused where `fr` is offered" is the narrowing this card removes and is replaced. - `plugin-auth/src/idp-locale-claim.test.ts`: `zh-TW` → `zh-Hant`, `zh-CN` → `zh-Hans` with the scripts listed either way round, `fr-FR` → `fr`, `de-DE` → unset. - `core/src/fallbacks/fallbacks.test.ts`: `resolveOfferedLocale` step by step, including `resolveLocale('zh-TW', ['zh-Hans','zh-Hant'])` answering `zh-Hans` beside the new answer `zh-Hant`. Ablation through `scripts/ablation-replace.mjs`, each restored after: the hold condition removed ⇒ both boot-window pins red; the seal's `emitChange` removed ⇒ the re-read pin red; the `kernel:bootstrapped` hook removed ⇒ 2 red (including the existing "not in force once the list drops it"); Setup's `admits` back to exact codes ⇒ 2 red; `resolveIdpLocale` on a first-match matcher ⇒ the `zh-Hant` pin red; the table step removed from `resolveOfferedLocale` ⇒ the core table pin red. ## Acceptance notes - Seed one-shot readers (`packages/runtime/src/seed-locale.ts`): the app plugin's inline seed reads the key in its `kernel:ready` handler (`app-plugin.ts`), so it sees a held value. For an override the boot does offer, that is now the right value where it used to be the next layer's; for one the boot never offers, the seed uses it before `kernel:bootstrapped` reports it, and a one-shot reader cannot be told to read again. When demo staff or seed files defer the inline seed to `kernel:bootstrapped`, its hook is registered during `kernel:ready`, after the settings plugin's seal hook, so it reads after the seal. - The list growing after the boot (`metadata:reloaded` adding a translation item) is outside this card: by then the hold is sealed, and an override is judged at each read against the list of that moment, as #30286 left it. - Auth prelude query count pin (`auth-prelude-query-count.pin.test.ts`, seat 5's #30520): untouched, no query added. - No service-settings translation key added. ## Verification All at head `06b4c86f` (the branch with `origin/main` c23eafa merged), after `pnpm install --frozen-lockfile` (exit 0) and a full build (`turbo run build --filter='!@objectstack/docs'`, 119/119, under the verify lock): - `pnpm --filter @objectstack/core test`: 135 files, 3017 passed; `typecheck` exit 0. - `pnpm --filter @objectstack/service-settings test`: 69 files, 1175 passed; `typecheck` exit 0. - `pnpm --filter @objectstack/plugin-auth test`: 224 files, 3985 passed and 10 skipped; `typecheck` exit 0. - `node scripts/pm/dispatch-gates.mjs --commands` derived 67 families from the change set; each run with its exit recorded before any pipe: 67 of 67 exit 0. `--ran`: 67 derived, 67 run, 0 NOT-MEASURED, exit 0. - `pnpm lint`: exit 0. - `pnpm --filter @objectstack/dogfood test` under the lock: exit 0, 420 files passed and 3 skipped, 3496 tests passed and 36 skipped. - CI check-runs: not yet reported at opening. --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CZEhtHfQH5TLEVe3TF)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7b80724 commit 1c5cee6

12 files changed

Lines changed: 325 additions & 32 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/core': patch
3+
'@objectstack/service-settings': patch
4+
'@objectstack/plugin-auth': patch
5+
---
6+
7+
fix(service-settings): an `OS_LOCALIZATION_LOCALE` naming a language the boot is still loading is no longer dropped, and Setup's default language accepts by the same locale matcher as the IdP locale claim (#30456)
8+
9+
Clause-②: yes (widening) — `@objectstack/core` exports `resolveOfferedLocale(requested, offered)`; `SettingsService` gains `holdOptionSourceVerdicts()` and `sealOptionSources()`. The save of `localization.locale` (`PUT /api/settings/localization`, `SettingsService.setMany`) and an `OS_LOCALIZATION_LOCALE` override now also accept a region or base of an offered language (`fr-FR` where `fr` is offered, `fr` where `fr-FR` is) and another case of an offered code (`zh-cn` for `zh-CN`); nothing accepted before is refused. The IdP locale claim (`resolveIdpLocale`) lands a script or region spelling on the offered code the platform locale table says it means (`zh-TW` on `zh-Hant`, not on a `zh-Hans` listed first).
10+
Metadata-protocol: none
11+
12+
- **The boot window.** The deployment's locale list fills during the boot: the app's authored translations arrive at `kernel:ready`. A `kernel:ready` reader of `localization.locale` (auth's mail and SMS default language) could ask before the language an `OS_LOCALIZATION_LOCALE` override names was in the list; the override was then reported `IGNORED` and the reader kept the next layer's value, though the boot went on to offer that language. `SettingsServicePlugin` now holds the option verdict on a sourced key until `kernel:bootstrapped`: while held, an override the list does not admit yet is in force and not reported; at `kernel:bootstrapped` it is judged again, and one the list still does not admit is reported once, as before, and a settings change is emitted for `localization.locale` so a reader that applied it reads the key again. The other value checks (pattern, domain, bounds, format) are judged at once, as ever. A `SettingsService` constructed without the plugin judges at once, as it always has.
13+
- **One matcher.** Setup's default language and the IdP locale claim now both ask `resolveOfferedLocale` (`@objectstack/core`): `resolveLocale`'s exact and case-insensitive steps, then the platform locale table's language (`zh-TW` is `zh-Hant`, `en-US` is `en`), then `resolveLocale`'s base-language and variant steps. A language one door takes, the other takes too.
14+
- **Comment.** `AUTH_EMAIL_TEMPLATE_LOCALES` (plugin-auth) no longer claims to be the setting's options: since #30286 the setting offers the deployment's locale list, and the two ends agree through `normalizeAuthEmailLocale`'s pass-through and the email service's `en-US` fallback.

‎packages/core/src/fallbacks/fallbacks.test.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';
22
import { createMemoryCache } from './memory-cache';
33
import { createMemoryQueue } from './memory-queue';
44
import { createMemoryJob } from './memory-job';
5-
import { createMemoryI18n, resolveLocale } from './memory-i18n';
5+
import { createMemoryI18n, resolveLocale, resolveOfferedLocale } from './memory-i18n';
66
import { CORE_FALLBACK_FACTORIES } from './index';
77
import { readServiceSelfInfo } from '@objectstack/spec/api';
88

@@ -573,3 +573,30 @@ describe('createMemoryI18n declared fallbackLocale (#15694)', () => {
573573
expect(i18n.getFallbackLocale).toBeUndefined();
574574
});
575575
});
576+
577+
// #30456: the one matcher for "is this locale offered here, and as which code",
578+
// shared by Setup's default language and the IdP locale claim.
579+
describe('resolveOfferedLocale', () => {
580+
it('takes resolveLocale\'s exact and case-insensitive steps first', () => {
581+
expect(resolveOfferedLocale('zh-CN', ['en', 'zh-CN'])).toBe('zh-CN');
582+
expect(resolveOfferedLocale('zh-cn', ['en', 'zh-CN'])).toBe('zh-CN');
583+
});
584+
585+
it('then the platform table\'s language, so a script or region lands on its own script', () => {
586+
// resolveLocale alone takes the first `zh-*` listed for either spelling.
587+
expect(resolveLocale('zh-TW', ['zh-Hans', 'zh-Hant'])).toBe('zh-Hans');
588+
expect(resolveOfferedLocale('zh-TW', ['zh-Hans', 'zh-Hant'])).toBe('zh-Hant');
589+
expect(resolveOfferedLocale('zh-CN', ['zh-Hant', 'zh-Hans'])).toBe('zh-Hans');
590+
expect(resolveOfferedLocale('en-US', ['zh-CN', 'en'])).toBe('en');
591+
});
592+
593+
it('then resolveLocale\'s base-language and variant steps', () => {
594+
expect(resolveOfferedLocale('fr-FR', ['en', 'fr'])).toBe('fr');
595+
expect(resolveOfferedLocale('fr', ['en', 'fr-FR'])).toBe('fr-FR');
596+
});
597+
598+
it('answers undefined for a language not offered, and for an empty list', () => {
599+
expect(resolveOfferedLocale('de-DE', ['en', 'fr'])).toBeUndefined();
600+
expect(resolveOfferedLocale('en', [])).toBeUndefined();
601+
});
602+
});

‎packages/core/src/fallbacks/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { createMemoryMetadata } from './memory-metadata.js';
88
export { createMemoryCache } from './memory-cache.js';
99
export { createMemoryQueue } from './memory-queue.js';
1010
export { createMemoryJob } from './memory-job.js';
11-
export { createMemoryI18n, resolveLocale, deepMerge } from './memory-i18n.js';
11+
export { createMemoryI18n, resolveLocale, resolveOfferedLocale, deepMerge } from './memory-i18n.js';
1212
export { createMemoryMetadata } from './memory-metadata.js';
1313
export {
1414
wireAuthoredTranslationSync,

‎packages/core/src/fallbacks/memory-i18n.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

3-
import { normalizeSupportedLocales } from '@objectstack/spec/system';
3+
import { normalizeSupportedLocales, platformLocaleTagOf } from '@objectstack/spec/system';
44

55
/**
66
* Recursively merge `source` into `target`. Nested plain objects are merged
@@ -67,6 +67,42 @@ export function resolveLocale(requestedLocale: string, availableLocales: string[
6767
return undefined;
6868
}
6969

70+
/**
71+
* The offered locale a requested one means, or `undefined`: the ONE matcher
72+
* for "is this locale offered here, and as which code", where the offered
73+
* codes are a deployment's locale list (`II18nService.getLocales()`).
74+
*
75+
* Setup's default language (`localization.locale`) accepts a value through
76+
* it, and the IdP locale claim (`plugin-auth`'s `resolveIdpLocale`) closes a
77+
* claimed locale through it, so a language one door takes the other takes
78+
* too. Order, first answer wins:
79+
*
80+
* 1. {@link resolveLocale}'s exact and case-insensitive steps.
81+
* 2. The platform locale table: an offered code that means the same table
82+
* language as the request (`platformLocaleTagOf`, through the table's
83+
* read aliases), so `zh-TW` is `zh-Hant` and never `zh-Hans`, and
84+
* `en-US` is `en`. The table's own note prescribes this order: map the
85+
* code to its table language first, then resolve.
86+
* 3. {@link resolveLocale}'s base-language and variant steps (`fr-FR` is an
87+
* offered `fr`, `fr` an offered `fr-FR`).
88+
*
89+
* Steps 1 and 3 are `resolveLocale`'s own rules; step 2 only decides between two
90+
* offered codes of one base language that the table tells apart by script or
91+
* region (`zh-Hans`/`zh-Hant`), where `resolveLocale` takes the first listed.
92+
*/
93+
export function resolveOfferedLocale(requested: string, offered: readonly string[]): string | undefined {
94+
if (offered.length === 0) return undefined;
95+
const lower = requested.toLowerCase();
96+
const literal = offered.find((code) => code === requested) ?? offered.find((code) => code.toLowerCase() === lower);
97+
if (literal !== undefined) return literal;
98+
const tag = platformLocaleTagOf(requested);
99+
if (tag !== undefined) {
100+
const sameLanguage = offered.find((code) => platformLocaleTagOf(code) === tag);
101+
if (sameLanguage !== undefined) return sameLanguage;
102+
}
103+
return resolveLocale(requested, [...offered]);
104+
}
105+
70106
/**
71107
* In-memory i18n service fallback.
72108
*

‎packages/plugins/plugin-auth/src/auth-manager.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1269,8 +1269,17 @@ export function isScimProtocolPath(endpointPath: string | undefined): boolean {
12691269
*
12701270
* Spelled out rather than imported: `plugin-auth` does not depend on
12711271
* `@objectstack/plugin-email` (it reaches the mail service through the service
1272-
* registry), and these are also the four options the `localization.locale`
1273-
* setting offers, so the two ends agree by construction rather than by import.
1272+
* registry).
1273+
*
1274+
* These are NOT the `localization.locale` setting's options. Since #30286 that
1275+
* setting offers the deployment's own locale list (the i18n service's
1276+
* `getLocales()`), which may hold a language with no row here (`vi-VN`). The
1277+
* two ends agree by pass-through, not by construction:
1278+
* {@link normalizeAuthEmailLocale} maps a value onto a row spelling where one
1279+
* of these four means it and hands any other value on unchanged, and the
1280+
* email service then resolves it against the template bundle's own tags and
1281+
* falls back to the `en-US` row when no tag matches. A language with no row
1282+
* therefore gets English mail, not a failed send.
12741283
*/
12751284
const AUTH_EMAIL_TEMPLATE_LOCALES = ['en-US', 'zh-CN', 'ja-JP', 'es-ES'] as const;
12761285

‎packages/plugins/plugin-auth/src/auth-plugin.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1238,10 +1238,12 @@ export class AuthPlugin implements Plugin {
12381238
// `setDefaultLocale`; the CLI passes `config.i18n.defaultLocale`),
12391239
// and is the bare `en` when the app declares nothing.
12401240
// - `localization.locale` (ADR-0053) is the workspace's RUNTIME
1241-
// language — Setup, Localization, tenant-scoped — whose four
1242-
// options are exactly `AUTH_EMAIL_TEMPLATE_LOCALES`. It is
1243-
// already the authority for auth SMS (#2815) and for audit
1244-
// activity summaries (framework#3039).
1241+
// language — Setup, Localization, tenant-scoped — whose options
1242+
// are the deployment's locale list (#30286), so it may name a
1243+
// language the auth mail rows do not ship (see
1244+
// `AUTH_EMAIL_TEMPLATE_LOCALES`). It is already the authority for
1245+
// auth SMS (#2815) and for audit activity summaries
1246+
// (framework#3039).
12451247
//
12461248
// A workspace that declared Chinese therefore received Chinese SMS
12471249
// and ENGLISH mail. The workspace setting now outranks the

‎packages/plugins/plugin-auth/src/idp-locale-claim.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,14 @@ describe('closing the claim against the supported locales', () => {
8484
expect(resolveIdpLocale('ja', SUPPORTED)).toBe('ja-JP');
8585
});
8686

87+
// #30456: the one offered-locale matcher Setup's default language accepts by.
88+
it('lands a script or region spelling on the offered code the platform table says it means', () => {
89+
expect(resolveIdpLocale('zh-TW', ['en', 'zh-Hans', 'zh-Hant'])).toBe('zh-Hant');
90+
expect(resolveIdpLocale('zh-CN', ['en', 'zh-Hant', 'zh-Hans'])).toBe('zh-Hans');
91+
expect(resolveIdpLocale('fr-FR', ['en', 'fr'])).toBe('fr');
92+
expect(resolveIdpLocale('de-DE', ['en', 'fr'])).toBeUndefined();
93+
});
94+
8795
it('reads the underscore spelling OIDC Core §5.1 notes as the tag it stands for', () => {
8896
expect(resolveIdpLocale('zh_CN', SUPPORTED)).toBe('zh-CN');
8997
});

‎packages/plugins/plugin-auth/src/idp-locale-claim.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@
2020
* is what an unset `sys_user.locale` means everywhere it is read. The
2121
* claim is closed against the locales the i18n service reports
2222
* (`getLocales()`, narrowed to the app's declared `i18n.supportedLocales`)
23-
* with the platform's own matcher (`resolveLocale`: exact → case →
24-
* base language → variant), and the SUPPORTED locale is what is stored,
23+
* with the platform's one offered-locale matcher (`resolveOfferedLocale`:
24+
* exact → case → platform-table language → base language → variant, the
25+
* matcher Setup's `localization.locale` accepts by too), and the
26+
* SUPPORTED locale is what is stored,
2527
* in the BCP-47 case every `sys_user.locale` write is stored in.
2628
* 4. **No claim at all** — the IdP said nothing, so nothing changes.
2729
*
@@ -68,7 +70,7 @@
6870
* so it is reported at `warn`.
6971
*/
7072

71-
import { resolveLocale } from '@objectstack/core';
73+
import { resolveOfferedLocale } from '@objectstack/core';
7274
import type { IDataEngine } from '@objectstack/core';
7375
import { normalizeRecipientLocale } from '@objectstack/service-messaging';
7476
import { authContextOf, type LinkingDbAdapter } from './implicit-account-linking.js';
@@ -143,7 +145,7 @@ export function readIdpLocaleClaim(source: unknown): IdpLocaleClaim | undefined
143145
export function resolveIdpLocale(claim: unknown, supported: readonly string[]): string | undefined {
144146
const tag = normalizeRecipientLocale(typeof claim === 'string' ? claim.replace(/_/g, '-') : claim);
145147
if (!tag) return undefined;
146-
const resolved = resolveLocale(tag, [...supported]);
148+
const resolved = resolveOfferedLocale(tag, supported);
147149
return resolved === undefined ? undefined : (canonicalUserLocale(resolved) as string);
148150
}
149151

‎packages/services/service-settings/src/localization-locale-options.test.ts‎

Lines changed: 129 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,9 +197,31 @@ describe('localization.locale serves the deployment\'s locale list', () => {
197197
booted.i18n.locales = ['en', 'zh-Hans'];
198198
expect((await save(booted.http, { locale: 'zh-CN' })).status).toBe(200);
199199
expect((await save(booted.http, { locale: 'en-US' })).status).toBe(200);
200-
// A code the platform locale table does not alias is accepted only as spelled.
200+
});
201+
202+
// #30456: Setup accepts by the matcher the IdP locale claim resolves by
203+
// (`resolveOfferedLocale`), so a language one door takes the other takes too.
204+
it('accepts a region or base of an offered language, and another case, as the IdP claim does (#30456)', async () => {
201205
booted.i18n.locales = ['en', 'fr'];
202-
expect((await save(booted.http, { locale: 'fr-FR' })).status).toBe(400);
206+
expect((await save(booted.http, { locale: 'fr-FR' })).status).toBe(200);
207+
// Served under the stored spelling, in the offered code's place, so it shows chosen.
208+
expect(servedLocaleOptions((await getPage(booted.http)).body).map((o) => o.value)).toEqual(['en', 'fr-FR']);
209+
210+
booted.i18n.locales = ['en', 'fr-FR'];
211+
expect((await save(booted.http, { locale: 'fr' })).status).toBe(200);
212+
213+
booted.i18n.locales = ['en', 'zh-CN'];
214+
expect((await save(booted.http, { locale: 'zh-cn' })).status).toBe(200);
215+
expect(servedLocaleOptions((await getPage(booted.http)).body).map((o) => o.value)).toEqual(['en', 'zh-cn']);
216+
217+
// Both Chinese scripts offered: each spelling lands on its own script.
218+
booted.i18n.locales = ['en', 'zh-Hans', 'zh-Hant'];
219+
expect((await save(booted.http, { locale: 'zh-TW' })).status).toBe(200);
220+
expect(servedLocaleOptions((await getPage(booted.http)).body).map((o) => o.value)).toEqual(['en', 'zh-Hans', 'zh-TW']);
221+
222+
// A language not offered in any spelling is still refused.
223+
booted.i18n.locales = ['en', 'fr'];
224+
expect((await save(booted.http, { locale: 'de-DE' })).status).toBe(400);
203225
});
204226

205227
it('keeps a stored value the deployment no longer offers readable, and serves it named as such', async () => {
@@ -319,3 +341,108 @@ describe('localeSelfName: a locale named in its own language, else its code', ()
319341
expect(localeSelfName('vi-VN')).toBe(expected);
320342
});
321343
});
344+
345+
/**
346+
* #30456: the locale list fills during the boot (the app's authored
347+
* translations arrive at `kernel:ready`), and `localization.locale` has
348+
* `kernel:ready` readers (auth's mail/SMS default language). An
349+
* `OS_LOCALIZATION_LOCALE` naming a language the list gains later in that
350+
* same step must not be reported IGNORED and dropped: its verdict is held
351+
* until `kernel:bootstrapped`.
352+
*/
353+
describe('an OS_LOCALIZATION_LOCALE override read while the boot is still filling the locale list (#30456)', () => {
354+
/** An i18n stand-in that gains `atReady` in its own `kernel:ready` step, as authored translations arrive. */
355+
class GrowingI18nPlugin extends LocaleListI18nPlugin {
356+
override name = 'test.growing-i18n';
357+
atReady: string[] = [];
358+
async start(ctx: PluginContext): Promise<void> {
359+
ctx.hook('kernel:ready', async () => {
360+
this.locales = [...this.locales, ...this.atReady];
361+
});
362+
}
363+
}
364+
365+
/** A `kernel:ready` reader of `localization.locale` that re-reads on a change, as auth's is. */
366+
class LocaleReaderPlugin implements Plugin {
367+
name = 'test.locale-reader';
368+
version = '0.0.0';
369+
reads: Array<{ value: unknown; source: string }> = [];
370+
async init(): Promise<void> {}
371+
async start(ctx: PluginContext): Promise<void> {
372+
ctx.hook('kernel:ready', async () => {
373+
const settings = ctx.getService<SettingsService>('settings');
374+
const read = async () => {
375+
const resolved = await settings.get('localization', 'locale', {});
376+
this.reads.push({ value: resolved.value, source: resolved.source });
377+
};
378+
await read();
379+
settings.subscribe('localization', () => {
380+
void read();
381+
});
382+
});
383+
}
384+
}
385+
386+
async function bootFilling(envValue: string, atReady: string[]) {
387+
const i18n = new GrowingI18nPlugin();
388+
i18n.locales = ['en'];
389+
i18n.atReady = atReady;
390+
const reader = new LocaleReaderPlugin();
391+
const kernel = new LiteKernel({ logger: { level: 'error' } as never });
392+
const error = vi.spyOn((kernel as unknown as { logger: { error: (...a: unknown[]) => void } }).logger, 'error');
393+
// The reader's `kernel:ready` step runs before the list grows.
394+
kernel.use(reader);
395+
kernel.use(i18n);
396+
kernel.use(new SettingsServicePlugin({ registerRoutes: false, env: { OS_LOCALIZATION_LOCALE: envValue } }));
397+
await kernel.bootstrap();
398+
const reports = () =>
399+
error.mock.calls.map((args) => String(args[0])).filter((m) => m.includes('OS_LOCALIZATION_LOCALE'));
400+
return { kernel, service: kernel.getService<SettingsService>('settings'), reader, reports };
401+
}
402+
403+
it('holds a language the list gains during kernel:ready in force, and never reports it', async () => {
404+
const booted = await bootFilling('vi-VN', ['vi-VN']);
405+
try {
406+
// The reader asked before `vi-VN` was in the list, and got the override.
407+
expect(booted.reader.reads[0]).toEqual({ value: 'vi-VN', source: 'env' });
408+
expect(booted.reader.reads.every((r) => r.value === 'vi-VN')).toBe(true);
409+
const resolved = await booted.service.get('localization', 'locale');
410+
expect(resolved).toMatchObject({ value: 'vi-VN', source: 'env' });
411+
expect(booted.reports()).toEqual([]);
412+
} finally {
413+
await booted.kernel.shutdown();
414+
}
415+
});
416+
417+
it('reports a language the boot never offers once the list is whole, and tells the readers to read again', async () => {
418+
const booted = await bootFilling('xx-XX', ['vi-VN']);
419+
try {
420+
// Held while the list was filling ...
421+
expect(booted.reader.reads[0]).toEqual({ value: 'xx-XX', source: 'env' });
422+
// ... then judged at `kernel:bootstrapped`: reported once, and the reader re-read.
423+
await vi.waitFor(() => expect(booted.reader.reads.length).toBeGreaterThan(1));
424+
expect(booted.reader.reads[booted.reader.reads.length - 1]).toEqual({ value: 'en-US', source: 'default' });
425+
expect(booted.reports()).toHaveLength(1);
426+
expect(booted.reports()[0]).toContain('IGNORED');
427+
expect((await booted.service.get('localization', 'locale')).source).toBe('default');
428+
expect(booted.reports()).toHaveLength(1);
429+
} finally {
430+
await booted.kernel.shutdown();
431+
}
432+
});
433+
434+
it('judges at once on a service no boot holds', async () => {
435+
const error = vi.fn();
436+
const svc = new SettingsService({
437+
env: { OS_LOCALIZATION_LOCALE: 'xx-XX' },
438+
logger: { warn: vi.fn(), error } as never,
439+
});
440+
svc.registerOptionSource('localization', 'locale', localizationLocaleOptionSource(() => ({ getLocales: () => ['en'] })));
441+
svc.registerManifest(localizationSettingsManifest);
442+
expect((await svc.get('localization', 'locale')).source).toBe('default');
443+
expect(error).toHaveBeenCalledTimes(1);
444+
// Sealing a service that never held anything is a no-op.
445+
svc.sealOptionSources();
446+
expect(error).toHaveBeenCalledTimes(1);
447+
});
448+
});

0 commit comments

Comments
 (0)