Skip to content

Commit cae6bf5

Browse files
authored
fix(docs): resolve a browser tag by BCP 47 truncation, one subtag at a time (#223)
normalizeLanguage took two shots at every Accept-Language tag -- the exact tag, then the substring before the first hyphen -- and LANGUAGE_MAPPING held only Chinese and Korean rows. So a browser sending a single region tag with no q-list got English for de-AT, fr-CA, es-MX and ja-JP, and zh-Hant-TW skipped past zh-Hant to zh and landed on Simplified. resolveSupportedLanguage walks the tag the way RFC 4647 section 3.4 defines lookup: whole tag, drop the last subtag, repeat. Most specific first, because short-to-long would answer Simplified for every Traditional tag carrying a region. The table is consulted at every step and beats truncation where they disagree -- it is an editorial ruling about what a tag means, truncation is the mechanical default -- which is also what lets zh-TW-x-private reach Traditional. Both paths exit through one membership check against i18n.languages, so neither can return a locale the site does not publish. Six rows truncation now subsumes (zh-CN, zh-SG, zh-Hans, zh-Hant, ko, ko-KR) are removed so the table reads as an exceptions list. A table carrying region rows teaches that region tags belong in it, which is why de-AT was never added and never worked. A differential run over a 167-tag corpus shows pruned and full agree on all 167. Before column measured against a real rebuild of the pre-fix tree, not read off the source: 66 tags change, all in the card's direction; every regression row unchanged. nan-Hant-TW and yue-HK still reach English -- truncation does not leak a non-Mandarin tag into zh-Hant through its script subtag. Case-sensitivity of the lookup is unchanged and filed as #220. Closes #217
1 parent 30b08b6 commit cae6bf5

1 file changed

Lines changed: 88 additions & 37 deletions

File tree

‎apps/docs/middleware.ts‎

Lines changed: 88 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -42,20 +42,34 @@ function setLocaleCookie(response: NextResponse, locale: string): void {
4242
}
4343

4444
/**
45-
* Language code mapping
46-
* Maps browser language codes to our supported language codes
45+
* Tags whose correct locale is NOT the one BCP 47 truncation would reach.
46+
*
47+
* This is an exceptions list, not a catalogue of browser tags. Truncation
48+
* (see `resolveSupportedLanguage`) already resolves every tag whose answer is
49+
* its own base language: `de-AT` reaches `de`, `ja-JP` reaches `ja`, `ko-KR`
50+
* reaches `ko`, `zh-Hans-CN` reaches `zh-Hans`. Rows for those are not
51+
* shorthand, they are noise — and they teach the next reader that region tags
52+
* belong in this table, which is how `de-AT`, `fr-CA`, `es-MX` and `ja-JP`
53+
* came to negotiate to English while four translated locales sat unused.
54+
* Enumerating them is a set with no end (#217).
55+
*
56+
* What is left is the one decision truncation cannot make, because the
57+
* information is not in the tag:
58+
*
59+
* - `zh` on its own is not a supported tag at all, and the house answer for
60+
* unqualified Chinese is Simplified.
61+
* - `zh-TW` / `zh-HK` / `zh-MO` name a region that implies the Traditional
62+
* script. Truncation would drop the region, reach `zh`, and hand back
63+
* Simplified — a wrong answer rather than an absent one.
64+
*
65+
* Add a row here only when the mechanical answer is WRONG. If it is merely
66+
* missing, the fix belongs in `i18n.languages`, not here.
4767
*/
4868
const LANGUAGE_MAPPING: Record<string, string> = {
49-
'zh': 'zh-Hans', // Chinese -> Simplified
50-
'zh-CN': 'zh-Hans', // Chinese (China) -> Simplified
51-
'zh-SG': 'zh-Hans', // Chinese (Singapore) -> Simplified
52-
'zh-Hans': 'zh-Hans', // already Simplified
53-
'zh-Hant': 'zh-Hant', // already Traditional
54-
'zh-TW': 'zh-Hant', // Chinese (Taiwan) -> Traditional
55-
'zh-HK': 'zh-Hant', // Chinese (Hong Kong) -> Traditional
56-
'zh-MO': 'zh-Hant', // Chinese (Macau) -> Traditional
57-
'ko': 'ko', // Korean
58-
'ko-KR': 'ko', // Korean (Korea) -> Korean
69+
'zh': 'zh-Hans', // unqualified Chinese -> Simplified (house default)
70+
'zh-TW': 'zh-Hant', // Taiwan -> Traditional
71+
'zh-HK': 'zh-Hant', // Hong Kong -> Traditional
72+
'zh-MO': 'zh-Hant', // Macau -> Traditional
5973
};
6074

6175
/**
@@ -67,21 +81,61 @@ const LEGACY_LOCALE_REDIRECTS: Record<string, string> = {
6781
};
6882

6983
/**
70-
* Normalize language code to match our supported languages
84+
* Resolve one browser language tag to a supported locale, or `undefined` when
85+
* the tag names nothing we publish.
86+
*
87+
* BCP 47 truncation, as RFC 4647 section 3.4 defines lookup: try the whole
88+
* tag, drop the last subtag, repeat — `zh-Hant-TW`, then `zh-Hant`, then `zh`.
89+
*
90+
* The function this replaced took two shots only: the exact tag, and the
91+
* substring before the first hyphen. Since `LANGUAGE_MAPPING` held nothing but
92+
* Chinese and Korean, `de-AT`, `fr-CA`, `es-MX` and `ja-JP` missed both and
93+
* fell through to English — four locales we translate, unreachable. And
94+
* `zh-Hant-TW`, whose MIDDLE subtag names the script, skipped straight past
95+
* `zh-Hant` to `zh` and landed on Simplified. Most browsers send
96+
* `de-AT,de;q=0.9`, and the bare `de` in the second list entry rescued them,
97+
* which is why this survived unnoticed (#217).
98+
*
99+
* Two orderings decide every answer here, and both are settled on purpose
100+
* rather than by accident:
101+
*
102+
* 1. **Most specific first.** The walk runs long to short, so `zh-Hant-TW`
103+
* reaches `zh-Hant` before it can reach `zh`. Short to long would answer
104+
* Simplified for every Traditional tag that carries a region.
105+
*
106+
* 2. **The table beats truncation, at every step of the walk.**
107+
* `LANGUAGE_MAPPING` is a ruling about what a tag MEANS; truncation is the
108+
* mechanical default for tags nobody has ruled on. Where the two disagree
109+
* the ruling wins — that is what keeps `zh-TW` on Traditional instead of
110+
* the Simplified that dropping `TW` would reach. Consulting the table at
111+
* every step, not only on the full tag, is also what lets a longer tag
112+
* built on a ruled one (`zh-TW-x-anything`) still land on Traditional.
113+
*
114+
* Both paths leave through the same check against `i18n.languages`, and that
115+
* check is the only exit from this function. Neither mechanism can hand back a
116+
* locale the site does not publish: truncation manufactures strings from
117+
* whatever the client sent (`xx`, `tlh`), and a table row outliving the locale
118+
* it names would do the same. Either one would otherwise produce a redirect to
119+
* a path that 404s.
120+
*
121+
* Matching is case-sensitive, so a client that lowercases its tags still
122+
* misses the Chinese rows (`zh-tw` reaches Simplified). Pre-existing and
123+
* unchanged by the truncation walk; measured on both sides of it and filed
124+
* as #220.
71125
*/
72-
function normalizeLanguage(lang: string): string {
73-
// Check direct mapping first
74-
if (LANGUAGE_MAPPING[lang]) {
75-
return LANGUAGE_MAPPING[lang];
76-
}
77-
78-
// Check if the base language (without region) is mapped
79-
const baseLang = lang.split('-')[0];
80-
if (LANGUAGE_MAPPING[baseLang]) {
81-
return LANGUAGE_MAPPING[baseLang];
126+
function resolveSupportedLanguage(tag: string): string | undefined {
127+
const subtags = tag.split('-');
128+
129+
for (let length = subtags.length; length > 0; length -= 1) {
130+
const candidate = subtags.slice(0, length).join('-');
131+
132+
const ruled = LANGUAGE_MAPPING[candidate];
133+
if (ruled && SUPPORTED_LANGUAGES.includes(ruled)) return ruled;
134+
135+
if (SUPPORTED_LANGUAGES.includes(candidate)) return candidate;
82136
}
83-
84-
return lang;
137+
138+
return undefined;
85139
}
86140

87141
/**
@@ -94,21 +148,18 @@ function getPreferredLanguage(request: NextRequest): string {
94148
return cookieLocale;
95149
}
96150

97-
// Then check Accept-Language header
151+
// Then the Accept-Language header, in the browser's own order of preference.
152+
// The first tag that resolves to a supported locale wins; a tag that
153+
// resolves to nothing is skipped rather than ending the search, so
154+
// `xx-YY,de` still reaches German.
98155
const negotiatorHeaders = Object.fromEntries(request.headers.entries());
99156
const negotiator = new Negotiator({ headers: negotiatorHeaders });
100-
const browserLanguages = negotiator.languages();
101-
102-
// Normalize browser languages to match our supported languages
103-
const normalizedLanguages = browserLanguages.map(normalizeLanguage);
104-
105-
// Find the first match
106-
for (const lang of normalizedLanguages) {
107-
if (SUPPORTED_LANGUAGES.includes(lang)) {
108-
return lang;
109-
}
157+
158+
for (const tag of negotiator.languages()) {
159+
const supported = resolveSupportedLanguage(tag);
160+
if (supported) return supported;
110161
}
111-
162+
112163
return i18n.defaultLanguage;
113164
}
114165

0 commit comments

Comments
 (0)