11import { stringify } from 'devalue'
22import { defineI18nMiddleware } from '@intlify/h3'
3- import { defineNitroPlugin } from 'nitropack/runtime'
3+ import { isString } from '@intlify/shared'
4+ import { defineNitroPlugin , useRuntimeConfig } from 'nitropack/runtime'
45import { tryUseI18nContext , createI18nContext } from './context'
56import { createUserLocaleDetector } from './utils/locale-detector'
67import { pickNested } from './utils/messages-utils'
@@ -12,17 +13,51 @@ import { localeDetector } from '#internal/i18n/locale.detector.mjs'
1213
1314import type { H3Event } from 'h3'
1415import type { CoreOptions } from '@intlify/core'
16+ import { localeCodes } from '#internal/i18n/options.mjs'
17+ import { genString } from 'knitwork'
18+ import type { I18nPublicRuntimeConfig , RootRedirectOptions } from '#internal-i18n-types'
1519
1620export default defineNitroPlugin ( async nitro => {
1721 const options = await setupVueI18nOptions ( )
22+ const runtimeI18n = useRuntimeConfig ( ) . public . i18n as I18nPublicRuntimeConfig
23+ const { useCookie, cookieKey } = runtimeI18n . detectBrowserLanguage || { }
1824 const localeConfigs = createLocaleConfigs ( options . fallbackLocale )
1925
2026 nitro . hooks . hook ( 'request' , async ( event : H3Event ) => {
2127 event . context . nuxtI18n = createI18nContext ( )
2228 event . context . nuxtI18n . localeConfigs = localeConfigs
2329 } )
2430
31+ function getPrefixRedirectionScript ( ) {
32+ if ( runtimeI18n . rootRedirect ) {
33+ return `
34+ if(${ JSON . stringify ( ! ! runtimeI18n . rootRedirect ) } ) {
35+ window.location.replace('${ isString ( runtimeI18n . rootRedirect ) ? runtimeI18n . rootRedirect : ( runtimeI18n . rootRedirect as RootRedirectOptions ) . path } ');
36+ }`
37+ }
38+ return `
39+ function getCookieValue(cookieName) {
40+ if (${ JSON . stringify ( ! useCookie ) } ) return '';
41+ for (const cookie of document.cookie.split('; ')) {
42+ const [name, value] = cookie.split('=');
43+ if (name === ${ genString ( cookieKey || __DEFAULT_COOKIE_KEY__ ) } ) return value;
44+ }
45+ }
46+ const locale = getCookieValue() || navigator.language;
47+ const locales = ${ JSON . stringify ( localeCodes ) } ;
48+ const defaultLocale = ${ genString ( options . locale || localeCodes [ 0 ] ) } ;
49+ window.location.replace('/' + (locales.includes(locale) ? locale : defaultLocale));`
50+ }
51+ const ssgPrefixRedirectionScript =
52+ __IS_SSG__ && __I18N_STRATEGY__ === 'prefix' && `<script>${ getPrefixRedirectionScript ( ) } </script>`
53+
2554 nitro . hooks . hook ( 'render:html' , ( htmlContext , { event } ) => {
55+ if ( ssgPrefixRedirectionScript && event . path === '/' ) {
56+ htmlContext . body . length = 0
57+ htmlContext . bodyAppend . unshift ( ssgPrefixRedirectionScript )
58+ return
59+ }
60+
2661 if ( __I18N_PRELOAD__ ) {
2762 const ctx = tryUseI18nContext ( event )
2863 if ( ctx == null || Object . keys ( ctx . messages ?? { } ) . length == 0 ) return
0 commit comments