Skip to content

Commit 02e38d8

Browse files
authored
refactor: fix i18n bug in node v22 (#10129)
1 parent e48b781 commit 02e38d8

File tree

1 file changed

+43
-10
lines changed
  • packages/docusaurus/src/server

1 file changed

+43
-10
lines changed

packages/docusaurus/src/server/i18n.ts

Lines changed: 43 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,36 @@ import {getLangDir} from 'rtl-detect';
1010
import type {I18n, DocusaurusConfig, I18nLocaleConfig} from '@docusaurus/types';
1111
import type {LoadContextParams} from './site';
1212

13+
function inferLanguageDisplayName(locale: string) {
14+
const tryLocale = (l: string) => {
15+
try {
16+
return new Intl.DisplayNames(l, {
17+
type: 'language',
18+
fallback: 'code',
19+
}).of(l)!;
20+
} catch (e) {
21+
// This is to compensate "of()" that is a bit strict
22+
// Looks like starting Node 22, this locale throws: "en-US-u-ca-buddhist"
23+
// RangeError: invalid_argument
24+
return null;
25+
}
26+
};
27+
28+
const parts = locale.split('-');
29+
30+
// This is a best effort, we try various locale forms that could give a result
31+
return (
32+
tryLocale(locale) ??
33+
tryLocale(`${parts[0]}-${parts[1]}`) ??
34+
tryLocale(parts[0]!)
35+
);
36+
}
37+
1338
function getDefaultLocaleLabel(locale: string) {
14-
const languageName = new Intl.DisplayNames(locale, {type: 'language'}).of(
15-
locale,
16-
)!;
39+
const languageName = inferLanguageDisplayName(locale);
40+
if (!languageName) {
41+
return locale;
42+
}
1743
return (
1844
languageName.charAt(0).toLocaleUpperCase(locale) + languageName.substring(1)
1945
);
@@ -44,13 +70,20 @@ function getDefaultCalendar(localeStr: string) {
4470
}
4571

4672
export function getDefaultLocaleConfig(locale: string): I18nLocaleConfig {
47-
return {
48-
label: getDefaultLocaleLabel(locale),
49-
direction: getLangDir(locale),
50-
htmlLang: locale,
51-
calendar: getDefaultCalendar(locale),
52-
path: locale,
53-
};
73+
try {
74+
return {
75+
label: getDefaultLocaleLabel(locale),
76+
direction: getLangDir(locale),
77+
htmlLang: locale,
78+
calendar: getDefaultCalendar(locale),
79+
path: locale,
80+
};
81+
} catch (e) {
82+
throw new Error(
83+
`Docusaurus couldn't get default locale config for ${locale}`,
84+
{cause: e},
85+
);
86+
}
5487
}
5588

5689
export async function loadI18n(

0 commit comments

Comments
 (0)