@@ -72,6 +72,79 @@ const LANGUAGE_MAPPING: Record<string, string> = {
7272 'zh-MO' : 'zh-Hant' , // Macau -> Traditional
7373} ;
7474
75+ /**
76+ * The locales this site publishes, keyed by their case-folded spelling.
77+ *
78+ * The value is always the string `i18n.languages` itself holds. This map is
79+ * the one place a folded spelling is turned back into a canonical one, and it
80+ * is what makes both the header side and the path side below case-insensitive
81+ * without either of them inventing a locale.
82+ */
83+ const PUBLISHED_BY_FOLDED_LOCALE : ReadonlyMap < string , string > = new Map (
84+ SUPPORTED_LANGUAGES . map ( ( locale ) => [ locale . toLowerCase ( ) , locale ] ) ,
85+ ) ;
86+
87+ /**
88+ * Every browser tag we answer to, case-folded, mapped to the canonical locale.
89+ *
90+ * BCP 47 tags are case-insensitive — RFC 5646 section 2.1.1: "the tags and
91+ * their subtags ... are not case sensitive". The casing the spec recommends
92+ * (lowercase language, Titlecase script, UPPERCASE region) is a writing
93+ * convention, not a constraint on the wire. Both tables above are written in
94+ * that convention, so before this index existed, matching them with plain
95+ * string equality meant a client spelling its tags differently missed rows
96+ * that name it exactly (#220).
97+ *
98+ * Measured on the pre-fix tree, one tag, no q-list, `GET /docs/quickstart`:
99+ * `zh-tw`, `zh-hk`, `zh-mo`, `zh-hant` and `zh-hant-tw` all negotiated to
100+ * Simplified, because the Chinese keys are the only ones carrying a script or
101+ * region subtag. Those are the rows #220 was filed for.
102+ *
103+ * The same run showed the defect is wider than the card's picture of it: it
104+ * is the LOWERCASE direction that is Chinese-only. `DE-AT`, `JA-jp`, `KO-kr`
105+ * and `ZH-TW` all fell through to English, because a bare `de` is lowercase
106+ * by convention too — any other casing missed every locale, not just the
107+ * Chinese ones. Folding the key closes the whole space at once.
108+ *
109+ * ## The KEY is folded. The value never is.
110+ *
111+ * The payload is the canonical string taken from `i18n.languages`, never the
112+ * folded key and never the caller's spelling. A folded value would build a
113+ * redirect to `/zh-hant/...`, which this site does not publish: it 404s, that
114+ * 404 re-enters negotiation, and a wrong-script page becomes a loop.
115+ *
116+ * ## The membership check is still the only exit
117+ *
118+ * #217 made a single check against `i18n.languages` the one door out of
119+ * `resolveSupportedLanguage`, so that neither truncation nor a table row
120+ * outliving its locale could return something unpublished. That check is not
121+ * removed here, it is moved to where this index is built and paid once: a
122+ * supported locale enters as itself, and a `LANGUAGE_MAPPING` row enters only
123+ * if its target resolves through the published map. Every value in this index
124+ * is therefore a member of `i18n.languages` by construction — the same
125+ * invariant, established at module load instead of re-checked per lookup.
126+ *
127+ * Insertion order carries ordering decision 2 of `resolveSupportedLanguage`:
128+ * the ruled rows are written last, so where a tag is both published and ruled
129+ * the ruling wins. No such tag exists today — `zh`, `zh-TW`, `zh-HK` and
130+ * `zh-MO` are none of them published locales — and the order is fixed here so
131+ * that adding one cannot silently reverse the rule.
132+ *
133+ * Folded keys collide only if `i18n.languages` publishes one locale under two
134+ * spellings, which would be a defect in that file: two BCP 47 tags differing
135+ * only in case are the same tag.
136+ */
137+ const CANONICAL_BY_FOLDED_TAG : ReadonlyMap < string , string > = ( ( ) => {
138+ const index = new Map ( PUBLISHED_BY_FOLDED_LOCALE ) ;
139+
140+ for ( const [ tag , target ] of Object . entries ( LANGUAGE_MAPPING ) ) {
141+ const published = PUBLISHED_BY_FOLDED_LOCALE . get ( target . toLowerCase ( ) ) ;
142+ if ( published ) index . set ( tag . toLowerCase ( ) , published ) ;
143+ }
144+
145+ return index ;
146+ } ) ( ) ;
147+
75148/**
76149 * Legacy locale redirects: old locale code -> current BCP 47 tag.
77150 * Permanent (308) so search engines transfer ranking to the new path.
@@ -110,29 +183,28 @@ const LEGACY_LOCALE_REDIRECTS: Record<string, string> = {
110183 * the Simplified that dropping `TW` would reach. Consulting the table at
111184 * every step, not only on the full tag, is also what lets a longer tag
112185 * built on a ruled one (`zh-TW-x-anything`) still land on Traditional.
186+ * Both tables are merged into one folded index, and that merge carries
187+ * this ordering: the ruled rows are written last, so a ruling still wins.
113188 *
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.
189+ * Tags are matched case-insensitively (#220). The walk folds each candidate
190+ * and takes a single look at `CANONICAL_BY_FOLDED_TAG` — see there for why
191+ * the KEY is folded and the returned value never is.
120192 *
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.
193+ * That lookup is the only exit from this function, and every value in the
194+ * index is a member of `i18n.languages` by construction, so neither mechanism
195+ * can hand back a locale the site does not publish. Truncation manufactures
196+ * strings out of whatever the client sent (`xx`, `tlh`), and a table row
197+ * outliving the locale it names would do the same; either would otherwise
198+ * produce a redirect to a path that 404s.
125199 */
126200function resolveSupportedLanguage ( tag : string ) : string | undefined {
127201 const subtags = tag . split ( '-' ) ;
128202
129203 for ( let length = subtags . length ; length > 0 ; length -= 1 ) {
130204 const candidate = subtags . slice ( 0 , length ) . join ( '-' ) ;
131205
132- const ruled = LANGUAGE_MAPPING [ candidate ] ;
133- if ( ruled && SUPPORTED_LANGUAGES . includes ( ruled ) ) return ruled ;
134-
135- if ( SUPPORTED_LANGUAGES . includes ( candidate ) ) return candidate ;
206+ const canonical = CANONICAL_BY_FOLDED_TAG . get ( candidate . toLowerCase ( ) ) ;
207+ if ( canonical ) return canonical ;
136208 }
137209
138210 return undefined ;
@@ -142,7 +214,11 @@ function resolveSupportedLanguage(tag: string): string | undefined {
142214 * Get the preferred language from the request
143215 */
144216function getPreferredLanguage ( request : NextRequest ) : string {
145- // Check cookie first
217+ // Check cookie first. Deliberately NOT case-folded: this cookie is written
218+ // by this file and nowhere else, always in canonical form, so folding it
219+ // would widen only what a hand-set cookie can say — no real client is
220+ // helped. The fold belongs where strings arrive from outside: the
221+ // Accept-Language header below, and the URL path in `middleware`.
146222 const cookieLocale = request . cookies . get ( LOCALE_COOKIE ) ?. value ;
147223 if ( cookieLocale && SUPPORTED_LANGUAGES . includes ( cookieLocale ) ) {
148224 return cookieLocale ;
@@ -201,25 +277,75 @@ export default function middleware(request: NextRequest) {
201277 return response ;
202278 }
203279
204- // Check if the pathname already has a locale
205- const pathnameHasLocale = i18n . languages . some (
206- ( locale ) => pathname . startsWith ( `/${ locale } /` ) || pathname === `/${ locale } `
207- ) ;
280+ // Does the pathname already carry a locale?
281+ //
282+ // Matched case-insensitively, and a non-canonical spelling is redirected to
283+ // the canonical one. #220 asked for this to be settled either way rather
284+ // than left to fall out of the matcher, so the reasoning is recorded here.
285+ //
286+ // Both answers are defensible on their face. URL path segments ARE
287+ // case-sensitive (RFC 3986 section 6.2.2.1), so reading `/zh-hant/...` as a
288+ // different resource is legitimate, and an extra redirect hop is a real
289+ // cost. What decided it is what the file actually did, measured rather than
290+ // reasoned about. On the pre-fix tree:
291+ //
292+ // GET /zh-hant/docs/quickstart 404
293+ // GET /zh-hant/docs/quickstart (Accept-Language: zh-Hant)
294+ // 307 to /zh-Hant/zh-hant/docs/quickstart, which 404s
295+ //
296+ // The second row is the one that settles it. A lowercase locale path did not
297+ // fail as an unknown URL — it fell through to negotiation, which prepended a
298+ // locale to a path that already named one and produced a URL nobody could
299+ // have meant. That is the header-side defect's own shape: a wrong answer
300+ // rather than an absent one, arrived at by accident. And it is reachable the
301+ // same way, by a proxy that lowercases what it forwards.
302+ //
303+ // So the segment is folded, and a non-canonical spelling gets a 308 to the
304+ // spelling this site publishes. `/zh-Hant/...` still costs zero hops; only a
305+ // URL that is broken today pays anything. 308 rather than 307 for the same
306+ // reason as the legacy `/cn/` rows above: it is permanent, and it collapses
307+ // the aliases onto one indexable URL.
308+ //
309+ // Three things this deliberately does NOT do:
310+ //
311+ // - It matches published locales only, never `LANGUAGE_MAPPING`. That
312+ // table rules on what a browser TAG means; it is not a list of URL
313+ // aliases. `/zh-TW/docs` stays a 404 rather than becoming a second name
314+ // for `/zh-Hant/docs` — publishing one page under two URLs is an SEO
315+ // problem this file has no mandate to create.
316+ // - It does not set the locale cookie. A locale-bearing path does not set
317+ // one today (this branch ends in `next()`); the hop is URL
318+ // normalisation, not negotiation, and `/zh-hant/x` should not carry a
319+ // side effect that `/zh-Hant/x` does not.
320+ // - It cannot loop. The target segment comes from `i18n.languages`, so the
321+ // redirected request matches canonically and falls straight through.
322+ //
323+ // `/EN/docs` therefore takes two hops — 308 to `/en/docs`, then the
324+ // default-locale strip below. Same shape as the pre-existing two-hop `/cn/`
325+ // case; each rule stays responsible for one thing.
326+ const localeSegment = pathname . split ( '/' ) [ 1 ] ;
327+ const pathLocale = localeSegment
328+ ? PUBLISHED_BY_FOLDED_LOCALE . get ( localeSegment . toLowerCase ( ) )
329+ : undefined ;
330+
331+ if ( pathLocale ) {
332+ // Non-canonical casing: normalise the spelling first, permanently.
333+ if ( localeSegment !== pathLocale ) {
334+ const url = new URL ( request . url ) ;
335+ url . pathname = `/${ pathLocale } ${ pathname . slice ( localeSegment . length + 1 ) } ` ;
336+ return NextResponse . redirect ( url , 308 ) ;
337+ }
208338
209- if ( pathnameHasLocale ) {
210- // Extract the locale from the pathname
211- const locale = pathname . split ( '/' ) [ 1 ] ;
212-
213339 // If it's the default locale and hideLocale is 'default-locale', redirect to remove locale prefix
214- if ( locale === i18n . defaultLanguage && i18n . hideLocale === 'default-locale' ) {
340+ if ( pathLocale === i18n . defaultLanguage && i18n . hideLocale === 'default-locale' ) {
215341 const url = new URL ( request . url ) ;
216342 // Remove locale prefix more precisely to avoid issues with partial matches
217343 url . pathname = pathname . replace ( new RegExp ( `^/${ i18n . defaultLanguage } (/|$)` ) , '$1' ) || '/' ;
218344 const response = NextResponse . redirect ( url ) ;
219- setLocaleCookie ( response , locale ) ;
345+ setLocaleCookie ( response , pathLocale ) ;
220346 return response ;
221347 }
222-
348+
223349 return NextResponse . next ( ) ;
224350 }
225351
0 commit comments