(params: {
pathname: string
hostname: string | undefined
cookieHeader: string | undefined
acceptLanguageHeader: string | undefined
i18n: I18nConfig
})
| 194 | * Detects the appropriate locale based on path, domain, cookie, and accept-language |
| 195 | */ |
| 196 | export function detectLocale(params: { |
| 197 | pathname: string |
| 198 | hostname: string | undefined |
| 199 | cookieHeader: string | undefined |
| 200 | acceptLanguageHeader: string | undefined |
| 201 | i18n: I18nConfig |
| 202 | }): { |
| 203 | locale: string |
| 204 | pathnameWithoutLocale: string |
| 205 | localeInPath: boolean |
| 206 | } { |
| 207 | const { pathname, hostname, cookieHeader, acceptLanguageHeader, i18n } = |
| 208 | params |
| 209 | |
| 210 | // 1. Check if locale is in the pathname |
| 211 | const pathLocaleResult = normalizeLocalePath(pathname, i18n.locales) |
| 212 | if (pathLocaleResult.detectedLocale) { |
| 213 | return { |
| 214 | locale: pathLocaleResult.detectedLocale, |
| 215 | pathnameWithoutLocale: pathLocaleResult.pathname, |
| 216 | localeInPath: true, |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | // If locale detection is disabled, use domain locale or default locale |
| 221 | if (i18n.localeDetection === false) { |
| 222 | const domainLocale = detectDomainLocale(i18n.domains, hostname) |
| 223 | return { |
| 224 | locale: domainLocale?.defaultLocale || i18n.defaultLocale, |
| 225 | pathnameWithoutLocale: pathname, |
| 226 | localeInPath: false, |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | // 2. Check cookie (priority over domain when locale detection is enabled) |
| 231 | const cookieLocale = getCookieLocale(cookieHeader, i18n.locales) |
| 232 | if (cookieLocale) { |
| 233 | return { |
| 234 | locale: cookieLocale, |
| 235 | pathnameWithoutLocale: pathname, |
| 236 | localeInPath: false, |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | // 3. Check accept-language header (priority over domain when locale detection is enabled) |
| 241 | const acceptLocale = getAcceptLanguageLocale( |
| 242 | acceptLanguageHeader || '', |
| 243 | i18n.locales |
| 244 | ) |
| 245 | if (acceptLocale) { |
| 246 | return { |
| 247 | locale: acceptLocale, |
| 248 | pathnameWithoutLocale: pathname, |
| 249 | localeInPath: false, |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // 4. Check domain locale |
no test coverage detected
searching dependent graphs…