Skip to content

Commit 9380468

Browse files
committed
fix(console): negotiate the console language against the server locales before the authored check
The server negotiates a request's tag against getLocales() before it resolves; the console now does the same against /i18n/locales codes, so a zh-Hans or zh console on a zh-CN-authored stack walks no chain. The fallbackChain describe now says it is absent when the i18n service reports none. Claude-Session: https://claude.ai/code/session_01WGufzh1FMUQYf1PcEunaaK Co-Authored-By: Claude <noreply@anthropic.com>
1 parent b276ff4 commit 9380468

6 files changed

Lines changed: 129 additions & 35 deletions

File tree

‎content/docs/ui/translations.mdx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,9 @@ Where the Console resolves a string itself (the `flows` group below), it walks
217217
the same chain. `GET /api/v1/i18n/locales` names the declared chain as
218218
`fallbackChain` (absent when the stack declares none) beside `sourceLocale`,
219219
and the Console loads each fallback locale's `flows` group with the active
220-
locale's bundle. A flow label the active locale lacks then reads the fallback
220+
locale's bundle. It first matches its own language against the locales that
221+
answer lists, as the server matches a request's locale, so a `zh-Hans` Console
222+
on a stack authored in `zh-CN` reads the authored Chinese and walks no chain. A flow label the active locale lacks then reads the fallback
221223
locale's text before the authored one, as the server's own reads do; with no
222224
declared chain it reads the active locale, then the authored label.
223225

‎packages/spec/src/api/protocol.zod.ts‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4823,11 +4823,16 @@ export const GetLocalesRequestSchema = lazySchema(() => z.object({}));
48234823
* service's `getFallbackLocale()` (the stack's `i18n.fallbackLocale`, else its
48244824
* `defaultLocale`, as the boot collapses them), which the server's own
48254825
* metadata translations already hand the spec resolvers as
4826-
* `ResolveOptions.fallbackChain`. It is absent when the service declares no
4827-
* fallback, and a client then resolves the requested locale alone, as the
4828-
* server does. A client that resolves translated metadata itself (the
4829-
* console's flow labels) reads it beside `sourceLocale` (the resolvers'
4830-
* `defaultLocale`) so its answer and the server's walk the same locales.
4826+
* `ResolveOptions.fallbackChain`. It is absent when the i18n service reports
4827+
* no fallback (the file-backed service always reports one, collapsed from
4828+
* `fallbackLocale || defaultLocale || 'en'`), and a client then resolves the
4829+
* requested locale alone, as the server does. A client that resolves
4830+
* translated metadata itself (the console's flow labels) reads it beside
4831+
* `sourceLocale` (the resolvers' `defaultLocale`), after negotiating its
4832+
* request tag against `locales[].code` as the server negotiates a request's
4833+
* tag (`resolveLocaleAmong`), so its answer and the server's walk the same
4834+
* locales: a `zh-Hans` request on a deployment holding `zh-CN` is the
4835+
* `zh-CN` request, and walks no chain when `zh-CN` is the source locale.
48314836
*/
48324837
export const GetLocalesResponseSchema = lazySchema(() => z.object({
48334838
locales: z.array(z.object({
@@ -4843,8 +4848,9 @@ export const GetLocalesResponseSchema = lazySchema(() => z.object({
48434848
),
48444849
fallbackChain: z.array(z.string()).optional().describe(
48454850
'The locales the server consults, in order, after the requested one and before the authored text: the deployment\'s '
4846-
+ 'declared fallback (`i18n.fallbackLocale`, else `defaultLocale`). Absent when the server declares none; the requested '
4847-
+ 'locale alone is then consulted. Not walked for a request in `sourceLocale`',
4851+
+ 'declared fallback (`i18n.fallbackLocale`, else `defaultLocale`). Absent when the i18n service reports none; the '
4852+
+ 'requested locale alone is then consulted. A request tag is negotiated against `locales[].code` first, and the chain '
4853+
+ 'is not walked for a request that negotiates to `sourceLocale`',
48484854
),
48494855
}));
48504856

‎ui/apps/console/src/loadLanguage.fallbackChain-36809.test.tsx‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,3 +117,49 @@ describe('loadLanguage brings the declared fallback chain (objectstack#36809)',
117117
expect(resources).toHaveProperty('app.flows');
118118
});
119119
});
120+
121+
describe('the language is negotiated against the server locales first (objectstack#36809)', () => {
122+
// The server negotiates a request's tag against the locales it holds before
123+
// it resolves (`negotiatedTranslationLocale`, `@objectstack/rest`), so an
124+
// alias of the authored locale is the authored request and walks no chain.
125+
const ALIAS_LOCALES = [{ code: 'zh-CN', label: 'zh-CN', isDefault: true }, { code: 'en', label: 'en', isDefault: false }];
126+
127+
it.each(['zh-Hans', 'zh'])('a %s console on a zh-CN-authored stack with fallback en shows the authored Chinese, as the server does', async (lang) => {
128+
const asked = serve({ locales: ALIAS_LOCALES, sourceLocale: 'zh-CN', fallbackChain: ['en'] }, { [lang]: ZH, en: EN });
129+
const { resources, instance } = await loaded(lang);
130+
expect(asked.some((url) => url.endsWith('/translations/en'))).toBe(false);
131+
expect(resources).not.toHaveProperty(DECLARED_FLOWS_FALLBACK_KEY);
132+
133+
// The server: the request negotiated to zh-CN, the source locale, so its
134+
// own bundle and then the authored label answer.
135+
const serverBundle = { 'zh-CN': ZH, en: EN } as unknown as TranslationBundle;
136+
const server = translateFlow<{ name: string; label?: string }>(
137+
{ name: FLOW, label: '交易审核 (authored)' },
138+
serverBundle,
139+
{ locale: 'zh-CN', fallbackChain: ['en'], defaultLocale: 'zh-CN' },
140+
).label;
141+
expect(server).toBe('交易审核 (authored)');
142+
143+
const options = flowsResolveOptions(instance, lang);
144+
const consoleLabel = translateFlow<{ name: string; label?: string }>(
145+
{ name: FLOW, label: '交易审核 (authored)' },
146+
activeFlowsBundle(instance, lang, FLOW),
147+
options,
148+
).label;
149+
expect(consoleLabel).toBe(server);
150+
});
151+
152+
it('a ja console on a stack holding ja-JP resolves as ja-JP and still reads the fallback', async () => {
153+
const asked = serve(
154+
{ locales: [...LOCALES.filter((l) => l.code !== 'ja-JP'), { code: 'ja-JP', label: 'ja-JP', isDefault: false }], sourceLocale: 'zh-CN', fallbackChain: ['en'] },
155+
{ ja: ZH, en: EN },
156+
);
157+
const { instance } = await loaded('ja');
158+
expect(asked.some((url) => url.endsWith('/translations/en'))).toBe(true);
159+
const options = flowsResolveOptions(instance, 'ja');
160+
expect(options).toEqual({ locale: 'ja-JP', fallbackChain: ['en'], defaultLocale: 'zh-CN' });
161+
const t = flowLabelTranslations(activeFlowsBundle(instance, 'ja', FLOW), FLOW, 'ja', options);
162+
expect(t?.flowLabel).toBe('Deal review');
163+
expect(t?.stepLabel({ id: 'score_deal', type: 'script' })).toBe('评分');
164+
});
165+
});

‎ui/apps/console/src/loadLanguage.ts‎

Lines changed: 34 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,15 @@
2020
*
2121
* The server resolves translated metadata through the deployment's declared
2222
* fallback chain: the requested locale, then each fallback, then the authored
23-
* text. `GET /api/v1/i18n/locales` names that chain (`fallbackChain`) and the
24-
* authored language (`sourceLocale`). The loader reads both beside the bundle
25-
* and, unless `lang` is the authored language (the server walks no chain
26-
* then), fetches each fallback locale's bundle too, keeping its `flows`
27-
* group. It lays them beside the app namespace
23+
* text. `GET /api/v1/i18n/locales` names that chain (`fallbackChain`), the
24+
* authored language (`sourceLocale`) and the locales the server holds
25+
* (`locales[].code`). The loader reads them beside the bundle and first
26+
* negotiates `lang` against those codes, as the server negotiates a request's
27+
* tag before it resolves (`resolveLocaleAmong(lang, codes) ?? lang`;
28+
* `negotiatedTranslationLocale` in `@objectstack/rest`): a `zh-Hans` or `zh`
29+
* console on a stack holding `zh-CN` is the `zh-CN` request. Unless that
30+
* negotiated language is the authored one (the server walks no chain then),
31+
* it fetches each fallback locale's bundle too, keeping its `flows` group. It lays them beside the app namespace
2832
* (`withDeclaredFlowsFallback`, `@object-ui/i18n`), where the flow-label
2933
* readers find them, so a flow label `lang` does not carry reads the fallback
3034
* locale's text, as the server's own reads do. A server that declares no chain
@@ -38,6 +42,7 @@ import {
3842
type DeclaredFlowsFallback,
3943
type FlowsTranslation,
4044
} from '@object-ui/i18n';
45+
import { resolveLocaleAmong } from '@objectstack/spec/system';
4146
import { i18nFetch, whenSessionAnswered } from './i18nSession';
4247

4348
const serverUrl = () => import.meta.env.VITE_SERVER_URL || '';
@@ -56,11 +61,19 @@ async function fetchTranslations(lang: string): Promise<Record<string, unknown>
5661
return json;
5762
}
5863

64+
interface DeclaredChain {
65+
fallbackChain: string[];
66+
sourceLocale?: string;
67+
/** `locales[].code`: what the server negotiates a request's tag against. */
68+
codes: string[];
69+
}
70+
5971
/**
60-
* The declared chain and authored language off `GET /api/v1/i18n/locales`,
61-
* or `null` when the server declares no chain or the read fails.
72+
* The declared chain, authored language and held locales off
73+
* `GET /api/v1/i18n/locales`, or `null` when the server declares no chain or
74+
* the read fails.
6275
*/
63-
async function fetchDeclaredChain(): Promise<{ fallbackChain: string[]; sourceLocale?: string } | null> {
76+
async function fetchDeclaredChain(): Promise<DeclaredChain | null> {
6477
try {
6578
const res = await i18nFetch(`${serverUrl()}/api/v1/i18n/locales`);
6679
if (!res.ok) return null;
@@ -70,7 +83,11 @@ async function fetchDeclaredChain(): Promise<{ fallbackChain: string[]; sourceLo
7083
const fallbackChain = chain.filter((code): code is string => typeof code === 'string' && code.length > 0);
7184
if (fallbackChain.length === 0) return null;
7285
const sourceLocale = typeof body?.sourceLocale === 'string' && body.sourceLocale ? body.sourceLocale : undefined;
73-
return { fallbackChain, sourceLocale };
86+
const descriptors: unknown[] = Array.isArray(body?.locales) ? body.locales : [];
87+
const codes = descriptors
88+
.map((d) => (d && typeof d === 'object' ? (d as { code?: unknown }).code : undefined))
89+
.filter((code): code is string => typeof code === 'string' && code.length > 0);
90+
return { fallbackChain, sourceLocale, codes };
7491
} catch {
7592
return null;
7693
}
@@ -80,19 +97,21 @@ const sameTag = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();
8097

8198
/**
8299
* The fallback locales' `flows` groups for `lang`, or `undefined` when there
83-
* is nothing to lay beside its bundle: no declared chain, or `lang` is the
84-
* authored language (the resolvers walk no chain for it).
100+
* is nothing to lay beside its bundle: no declared chain, or `lang`,
101+
* negotiated against the server's locales, is the authored language (the
102+
* resolvers walk no chain for it).
85103
*/
86104
async function declaredFlowsFallback(
87105
lang: string,
88-
declared: { fallbackChain: string[]; sourceLocale?: string } | null,
106+
declared: DeclaredChain | null,
89107
): Promise<DeclaredFlowsFallback | undefined> {
90108
if (!declared) return undefined;
91-
if (declared.sourceLocale && sameTag(lang, declared.sourceLocale)) return undefined;
109+
const locale = resolveLocaleAmong(lang, declared.codes) ?? lang;
110+
if (declared.sourceLocale && sameTag(locale, declared.sourceLocale)) return undefined;
92111
const bundles: DeclaredFlowsFallback['bundles'] = {};
93112
await Promise.all(
94113
declared.fallbackChain
95-
.filter((code) => !sameTag(code, lang))
114+
.filter((code) => !sameTag(code, locale))
96115
.map(async (code) => {
97116
try {
98117
const translations = await fetchTranslations(code);
@@ -104,6 +123,7 @@ async function declaredFlowsFallback(
104123
}),
105124
);
106125
return {
126+
locale,
107127
fallbackChain: declared.fallbackChain,
108128
...(declared.sourceLocale ? { defaultLocale: declared.sourceLocale } : {}),
109129
bundles,

‎ui/packages/i18n/src/flowLabels.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,8 @@ export interface FlowLabelTranslations {
7373
* resolution path, and an approval step's label through the spec's
7474
* `resolveFlowApprovalStepLabel`, the server's; both are asked with the same
7575
* options: `{ locale: language }` plus the server's declared `fallbackChain`
76-
* and `defaultLocale` when `declared` carries them ({@link flowsResolveOptions},
76+
* and `defaultLocale` (and the negotiated `locale`) when `declared` carries
77+
* them ({@link flowsResolveOptions},
7778
* objectstack#36809), so a label the active language lacks reads the declared
7879
* fallback locale's text before the authored one, as on the server. Any other
7980
* step label is the spec-typed address of the node's name (see the module
@@ -84,10 +85,12 @@ export function flowLabelTranslations(
8485
bundle: TranslationBundle | undefined,
8586
flowName: string,
8687
language: string,
87-
declared?: Pick<ResolveOptions, 'fallbackChain' | 'defaultLocale'>,
88+
declared?: Pick<ResolveOptions, 'locale' | 'fallbackChain' | 'defaultLocale'>,
8889
): FlowLabelTranslations | undefined {
8990
if (!bundle || !flowName) return undefined;
90-
const resolveOptions: ResolveOptions = { ...declared, locale: language };
91+
// `declared.locale` is the language as the server negotiated it, when the
92+
// loader recorded one (`flowsResolveOptions`); else `language` as it is.
93+
const resolveOptions: ResolveOptions = { ...declared, locale: declared?.locale ?? language };
9194
const flowLabel = translateFlow<{ name: string; label?: string }>({ name: flowName }, bundle, resolveOptions).label;
9295
// The `nodes` and `screens` reads walk the locales the resolvers above walk
9396
// (`flowsLocaleChain`), each tag matched by the spec's one locale ladder

‎ui/packages/i18n/src/flowsBundle.ts‎

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,14 @@ export const DECLARED_FLOWS_FALLBACK_KEY = '__declaredFlowsFallback';
5656

5757
/** What a language's tree holds under {@link DECLARED_FLOWS_FALLBACK_KEY}. */
5858
export interface DeclaredFlowsFallback {
59+
/**
60+
* The active language NEGOTIATED against `GET /i18n/locales` `locales[].code`
61+
* (`resolveLocaleAmong(language, codes) ?? language`), the tag the server
62+
* hands the resolvers (`negotiatedTranslationLocale`, `@objectstack/rest`):
63+
* a `zh-Hans` console on a stack holding `zh-CN` resolves as `zh-CN`.
64+
* Absent: the active language as it is.
65+
*/
66+
locale?: string;
5967
/** `GET /i18n/locales` `fallbackChain`: the locales the server consults after the requested one. */
6068
fallbackChain: string[];
6169
/** `GET /i18n/locales` `sourceLocale`: the authored language, the resolvers' `defaultLocale`. */
@@ -89,6 +97,7 @@ function readDeclared(tree: Record<string, unknown> | undefined): DeclaredFlowsF
8997
const fallbackChain = entry.fallbackChain.filter((code): code is string => typeof code === 'string' && code.length > 0);
9098
if (fallbackChain.length === 0) return undefined;
9199
return {
100+
locale: typeof entry.locale === 'string' && entry.locale ? entry.locale : undefined,
92101
fallbackChain,
93102
defaultLocale: typeof entry.defaultLocale === 'string' && entry.defaultLocale ? entry.defaultLocale : undefined,
94103
bundles: entry.bundles && typeof entry.bundles === 'object' ? entry.bundles : {},
@@ -100,17 +109,20 @@ const sameTag = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();
100109
/**
101110
* The spec `ResolveOptions` the flow-label readers hand the resolvers in
102111
* `language`: `{ locale: language }`, plus the server's declared
103-
* `fallbackChain` and `defaultLocale` when the loaded tree carries them. The
104-
* server's metadata translations pass the same three
105-
* (`metaTranslateOptions`, `@objectstack/rest`), so the console and the server
106-
* walk the same locales. With no declared chain the answer is
107-
* `{ locale: language }`: the requested locale, then the authored copy.
112+
* `fallbackChain` and `defaultLocale` when the loaded tree carries them, with
113+
* `locale` the language as the server negotiated it against its own locales
114+
* ({@link DeclaredFlowsFallback.locale}). The server's metadata translations
115+
* pass the same three (`metaTranslateOptions`, `@objectstack/rest`), so the
116+
* console and the server walk the same locales, and an alias of the authored
117+
* locale (`zh-Hans` for `zh-CN`) walks no chain on either side. With no
118+
* declared chain the answer is `{ locale: language }`: the requested locale,
119+
* then the authored copy.
108120
*/
109121
export function flowsResolveOptions(i18n: TranslationResourceReader | undefined, language: string): ResolveOptions {
110122
const declared = readDeclared(readTree(i18n, language));
111123
if (!declared) return { locale: language };
112124
return {
113-
locale: language,
125+
locale: declared.locale ?? language,
114126
fallbackChain: declared.fallbackChain,
115127
...(declared.defaultLocale ? { defaultLocale: declared.defaultLocale } : {}),
116128
};
@@ -143,7 +155,9 @@ export function flowsLocaleChain(options: ResolveOptions): string[] {
143155
* The active language's row comes from the app namespace at the top of its
144156
* resource tree (`app` for a spec payload, whatever the payload named for an
145157
* already-namespaced one): the first namespace whose `flows` group addresses
146-
* this flow. When the server declares a fallback chain (`GET /i18n/locales`
158+
* this flow, keyed by the language as the server negotiated it when the loader
159+
* recorded one ({@link DeclaredFlowsFallback.locale}), else by `language`.
160+
* When the server declares a fallback chain (`GET /i18n/locales`
147161
* `fallbackChain`, objectstack#36809), each fallback locale whose `flows`
148162
* group addresses this flow adds its own row, keyed by the locale as the
149163
* chain names it, out of the entry the console's loader laid beside the tree
@@ -164,17 +178,20 @@ export function activeFlowsBundle(
164178
const tree = readTree(i18n, language);
165179
if (!tree) return undefined;
166180
const bundle: TranslationBundle = {};
181+
const declared = readDeclared(tree);
182+
// The active row is keyed by the tag the resolvers are asked for
183+
// (`flowsResolveOptions`): the negotiated one when the server declared a chain.
184+
const active = declared?.locale ?? language;
167185
for (const [key, namespace] of Object.entries(tree)) {
168186
if (key === DECLARED_FLOWS_FALLBACK_KEY) continue;
169187
const flows = (namespace as { flows?: unknown } | null)?.flows;
170188
if (flows && typeof flows === 'object' && (flows as Record<string, unknown>)[flowName]) {
171-
bundle[language] = { flows: flows as FlowsTranslation };
189+
bundle[active] = { flows: flows as FlowsTranslation };
172190
break;
173191
}
174192
}
175-
const declared = readDeclared(tree);
176193
for (const code of declared?.fallbackChain ?? []) {
177-
if (sameTag(code, language) || bundle[code]) continue;
194+
if (sameTag(code, active) || bundle[code]) continue;
178195
const flows = declared?.bundles[code]?.flows;
179196
if (flows && typeof flows === 'object' && flows[flowName]) bundle[code] = { flows };
180197
}

0 commit comments

Comments
 (0)