Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(i18n): improve locale path checking and normalization #13038

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/gold-bats-scream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro": patch
---

fix(i18n): improve locale path checking and normalization
25 changes: 16 additions & 9 deletions packages/astro/src/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,24 @@ export function requestIs404Or500(request: Request, base = '') {
return isRoute404(pathname) || isRoute500(pathname);
}

// Checks if the pathname has any locale
// Checks if the `realtivePath` starts with any locale
export function pathHasLocale(path: string, locales: Locales): boolean {
const segments = path.split('/');
for (const segment of segments) {
for (const locale of locales) {
if (typeof locale === 'string') {
if (normalizeTheLocale(segment) === normalizeTheLocale(locale)) {
const base = import.meta.env.BASE_URL;
const relativePath = path.startsWith(base) ? path.slice(base.length) : path;
const segments = relativePath.split('/').filter(Boolean);

for (const locale of locales) {
if (typeof locale === 'string') {
if (normalizeTheLocale(segments[0]) === normalizeTheLocale(locale)) {
return true;
}
} else if (segments[0] === locale.path) {
return true;
} else if (locale.codes) {
for (const code of locale.codes) {
if (normalizeTheLocale(segments[0]) === normalizeTheLocale(code)) {
return true;
}
} else if (segment === locale.path) {
return true;
}
}
}
Expand Down Expand Up @@ -222,7 +229,7 @@ export function getLocaleByPath(path: string, locales: Locales): string {
* - transforms all letters to be lower case;
*/
export function normalizeTheLocale(locale: string): string {
return locale.replaceAll('_', '-').toLowerCase();
return locale?.replaceAll('_', '-').toLowerCase();
}

/**
Expand Down
Loading