Skip to content

Commit 10aaeee

Browse files
authored
refactor: simplify runtime logic (#3496)
1 parent a0190a6 commit 10aaeee

File tree

7 files changed

+79
-138
lines changed

7 files changed

+79
-138
lines changed

src/bundler.ts

+25-32
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,6 @@ import type { I18nNuxtContext } from './context'
1616
const debug = createDebug('@nuxtjs/i18n:bundler')
1717

1818
export async function extendBundler(ctx: I18nNuxtContext, nuxt: Nuxt) {
19-
const { options: nuxtOptions } = ctx
20-
const localePaths = [...new Set([...ctx.localeInfo.flatMap(x => x.meta.map(m => m.path))])]
21-
const localeIncludePaths = localePaths.length ? localePaths : undefined
22-
23-
const sourceMapOptions: BundlerPluginOptions = {
24-
sourcemap: !!nuxt.options.sourcemap.server || !!nuxt.options.sourcemap.client
25-
}
26-
2719
addTemplate({
2820
write: true,
2921
filename: 'nuxt-i18n-logger.mjs',
@@ -34,9 +26,7 @@ export async function extendBundler(ctx: I18nNuxtContext, nuxt: Nuxt) {
3426

3527
return `
3628
import { createConsola } from 'consola'
37-
3829
const debugLogger = createConsola({ level: ${ctx.options.debug === 'verbose' ? 999 : 4} }).withTag('i18n')
39-
4030
export function createLogger(label) {
4131
return debugLogger.withTag(label)
4232
}`
@@ -48,47 +38,50 @@ export function createLogger(label) {
4838
/**
4939
* shared plugins (nuxt/nitro)
5040
*/
51-
const resourcePlugin = ResourcePlugin(sourceMapOptions, ctx)
41+
const pluginOptions: BundlerPluginOptions = {
42+
sourcemap: !!nuxt.options.sourcemap.server || !!nuxt.options.sourcemap.client
43+
}
44+
const resourcePlugin = ResourcePlugin(pluginOptions, ctx)
5245

5346
addBuildPlugin(resourcePlugin)
54-
5547
nuxt.hook('nitro:config', async cfg => {
5648
cfg.rollupConfig!.plugins = (await cfg.rollupConfig!.plugins) || []
5749
cfg.rollupConfig!.plugins = toArray(cfg.rollupConfig!.plugins)
58-
5950
cfg.rollupConfig!.plugins.push(resourcePlugin.rollup())
6051
})
6152

6253
/**
63-
* shared plugins (webpack/vite)
54+
* shared plugins (vite/webpack/rspack)
6455
*/
56+
const { options } = ctx
57+
const localePaths = [...new Set([...ctx.localeInfo.flatMap(x => x.meta.map(m => m.path))])]
6558
const vueI18nPluginOptions: PluginOptions = {
6659
allowDynamic: true,
67-
include: localeIncludePaths,
68-
runtimeOnly: nuxtOptions.bundle.runtimeOnly,
69-
fullInstall: nuxtOptions.bundle.fullInstall,
70-
onlyLocales: nuxtOptions.bundle.onlyLocales,
71-
escapeHtml: nuxtOptions.compilation.escapeHtml,
72-
compositionOnly: nuxtOptions.bundle.compositionOnly,
73-
strictMessage: nuxtOptions.compilation.strictMessage,
74-
defaultSFCLang: nuxtOptions.customBlocks.defaultSFCLang,
75-
globalSFCScope: nuxtOptions.customBlocks.globalSFCScope,
76-
dropMessageCompiler: nuxtOptions.bundle.dropMessageCompiler,
77-
optimizeTranslationDirective: nuxtOptions.bundle.optimizeTranslationDirective
60+
include: localePaths.length ? localePaths : undefined,
61+
runtimeOnly: options.bundle.runtimeOnly,
62+
fullInstall: options.bundle.fullInstall,
63+
onlyLocales: options.bundle.onlyLocales,
64+
escapeHtml: options.compilation.escapeHtml,
65+
compositionOnly: options.bundle.compositionOnly,
66+
strictMessage: options.compilation.strictMessage,
67+
defaultSFCLang: options.customBlocks.defaultSFCLang,
68+
globalSFCScope: options.customBlocks.globalSFCScope,
69+
dropMessageCompiler: options.bundle.dropMessageCompiler,
70+
optimizeTranslationDirective: options.bundle.optimizeTranslationDirective
7871
}
7972
addBuildPlugin({
8073
vite: () => VueI18nPlugin.vite(vueI18nPluginOptions),
8174
webpack: () => VueI18nPlugin.webpack(vueI18nPluginOptions)
8275
})
83-
addBuildPlugin(TransformMacroPlugin(sourceMapOptions))
84-
if (nuxtOptions.experimental.autoImportTranslationFunctions) {
85-
addBuildPlugin(TransformI18nFunctionPlugin(sourceMapOptions))
76+
addBuildPlugin(TransformMacroPlugin(pluginOptions))
77+
if (options.experimental.autoImportTranslationFunctions) {
78+
addBuildPlugin(TransformI18nFunctionPlugin(pluginOptions))
8679
}
8780

8881
const defineConfig = {
89-
...getFeatureFlags(nuxtOptions.bundle),
90-
__DEBUG__: String(!!nuxtOptions.debug),
91-
__TEST__: String(!!nuxtOptions.debug || nuxt.options._i18nTest)
82+
...getFeatureFlags(options.bundle),
83+
__DEBUG__: String(!!options.debug),
84+
__TEST__: String(!!options.debug || nuxt.options._i18nTest)
9285
}
9386
/**
9487
* webpack plugin
@@ -105,7 +98,7 @@ export function createLogger(label) {
10598
/**
10699
* rspack plugin
107100
*/
108-
if (nuxt.options.builder == '@nuxt/rspack-builder') {
101+
if (nuxt.options.builder === '@nuxt/rspack-builder') {
109102
try {
110103
const { rspack } = await import('@rspack/core')
111104
addRspackPlugin(new rspack.DefinePlugin(defineConfig))

src/runtime/composables/index.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useNuxtApp, useCookie as useNuxtCookie } from '#imports'
1+
import { useNuxtApp, useCookie } from '#imports'
22
import { ref } from 'vue'
33
import { runtimeDetectBrowserLanguage, wrapComposable } from '../internal'
44
import { localeCodes } from '#build/i18n.options.mjs'
@@ -208,7 +208,7 @@ export function useCookieLocale(): Ref<string> {
208208
return locale
209209
}
210210

211-
const code: string | null = useNuxtCookie<string>(detect.cookieKey!).value
211+
const code = useCookie(detect.cookieKey!).value
212212
if (code && localeCodes.includes(code)) {
213213
locale.value = code
214214
}

src/runtime/domain.ts

+12-16
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { isString, isObject, isArray } from '@intlify/shared'
1+
import { isArray, isString } from '@intlify/shared'
22
import { hasProtocol } from 'ufo'
33
import { getRequestProtocol } from 'h3'
44
import { useRequestEvent, useRuntimeConfig, useRouter, useRequestHeaders, useNuxtApp } from '#imports'
@@ -24,21 +24,20 @@ export function getHost() {
2424
export function getLocaleDomain(locales: LocaleObject[], strategy: string, route: string | CompatRoute): string {
2525
const logger = /*#__PURE__*/ createLogger(`getLocaleDomain`)
2626
const host = getHost()
27-
const routePath = isObject(route) ? route.path : isString(route) ? route : ''
28-
2927
if (!host) {
3028
return host
3129
}
3230

33-
__DEBUG__ && logger.log(`locating domain for host`, { host, strategy, path: routePath })
34-
31+
const routePath = isString(route) ? route : route.path
3532
const matchingLocales = locales.filter(locale => {
3633
if (locale.domain) {
3734
return (hasProtocol(locale.domain) ? locale.domain.replace(/(http|https):\/\//, '') : locale.domain) === host
3835
}
3936
return isArray(locale?.domains) ? locale.domains.includes(host) : false
4037
})
4138

39+
__DEBUG__ && logger.log(`locating domain for host`, { host, strategy, path: routePath })
40+
4241
if (matchingLocales.length === 0) {
4342
return ''
4443
}
@@ -59,16 +58,14 @@ export function getLocaleDomain(locales: LocaleObject[], strategy: string, route
5958
}
6059

6160
// get prefix from route
62-
if (route) {
61+
if (route && routePath) {
6362
__DEBUG__ && logger.log(`check matched domain for locale match`, { path: routePath, host })
6463

65-
if (routePath && routePath !== '') {
66-
const matched = routePath.match(getLocalesRegex(matchingLocales.map(l => l.code)))?.at(1)
67-
if (matched) {
68-
const matchingLocale = matchingLocales.find(l => l.code === matched)
69-
__DEBUG__ && logger.log(`matched locale from path`, { matchedLocale: matchingLocale?.code })
70-
return matchingLocale?.code ?? ''
71-
}
64+
const matched = routePath.match(getLocalesRegex(matchingLocales.map(l => l.code)))?.at(1)
65+
if (matched) {
66+
const matchingLocale = matchingLocales.find(l => l.code === matched)
67+
__DEBUG__ && logger.log(`matched locale from path`, { matchedLocale: matchingLocale?.code })
68+
return matchingLocale?.code ?? ''
7269
}
7370
}
7471

@@ -82,11 +79,10 @@ export function getLocaleDomain(locales: LocaleObject[], strategy: string, route
8279
export function getDomainFromLocale(localeCode: Locale): string | undefined {
8380
const nuxt = useNuxtApp()
8481
const host = getHost()
85-
const runtimeI18n = useRuntimeConfig().public.i18n as I18nPublicRuntimeConfig
82+
const { domainLocales } = useRuntimeConfig().public.i18n as I18nPublicRuntimeConfig
8683
const lang = normalizedLocales.find(locale => locale.code === localeCode)
8784
// lookup the `differentDomain` origin associated with given locale.
88-
const domain =
89-
runtimeI18n?.domainLocales?.[localeCode]?.domain || lang?.domain || lang?.domains?.find(v => v === host)
85+
const domain = domainLocales?.[localeCode]?.domain || lang?.domain || lang?.domains?.find(v => v === host)
9086

9187
if (!domain) {
9288
console.warn(formatMessage('Could not find domain name for locale ' + localeCode))

src/runtime/internal.ts

+10-27
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
import { isString } from '@intlify/shared'
2-
import { useCookie as useNuxtCookie, useRuntimeConfig, useNuxtApp, useRequestHeader } from '#imports'
2+
import { useCookie, useNuxtApp, useRequestHeader, useRuntimeConfig } from '#imports'
33
import { DEFAULT_COOKIE_KEY, isSSG, localeCodes, normalizedLocales } from '#build/i18n.options.mjs'
44
import { findBrowserLocale, regexpPath } from './routing/utils'
55
import { initCommonComposableOptions } from './utils'
66
import { createLogger } from '#nuxt-i18n/logger'
77

88
import type { Locale } from 'vue-i18n'
9-
import type { DetectBrowserLanguageOptions } from '#internal-i18n-types'
10-
import type { CookieRef } from 'nuxt/app'
11-
import type { I18nPublicRuntimeConfig } from '#internal-i18n-types'
9+
import type { DetectBrowserLanguageOptions, I18nPublicRuntimeConfig } from '#internal-i18n-types'
10+
import type { CookieOptions, CookieRef } from 'nuxt/app'
1211
import type { CompatRoute } from './types'
1312
import type { CommonComposableOptions } from './utils'
1413

@@ -44,27 +43,24 @@ export function getBrowserLocale(): string | undefined {
4443
return findBrowserLocale(normalizedLocales, browserLocales) || undefined
4544
}
4645

47-
export function getI18nCookie() {
46+
export function createI18nCookie() {
4847
const detect = runtimeDetectBrowserLanguage()
4948
const cookieKey = (detect && detect.cookieKey) || DEFAULT_COOKIE_KEY
5049
const date = new Date()
51-
const cookieOptions: Record<string, unknown> = {
52-
expires: new Date(date.setDate(date.getDate() + 365)),
50+
const cookieOptions: CookieOptions<string | null | undefined> & { readonly: false } = {
5351
path: '/',
52+
readonly: false,
53+
expires: new Date(date.setDate(date.getDate() + 365)),
5454
sameSite: detect && detect.cookieCrossOrigin ? 'none' : 'lax',
55+
domain: (detect && detect.cookieDomain) || undefined,
5556
secure: (detect && detect.cookieCrossOrigin) || (detect && detect.cookieSecure)
5657
}
57-
58-
if (detect && detect.cookieDomain) {
59-
cookieOptions.domain = detect.cookieDomain
60-
}
61-
62-
return useNuxtCookie<string | undefined>(cookieKey, cookieOptions)
58+
return useCookie(cookieKey, cookieOptions)
6359
}
6460

6561
// TODO: remove side-effects
6662
export function getLocaleCookie(
67-
cookieRef: CookieRef<string | undefined>,
63+
cookieRef: CookieRef<string | null | undefined>,
6864
detect: false | DetectBrowserLanguageOptions,
6965
defaultLocale: string
7066
): string | undefined {
@@ -101,18 +97,6 @@ export function getLocaleCookie(
10197
cookieRef.value = undefined
10298
}
10399

104-
export function setLocaleCookie(
105-
cookieRef: CookieRef<string | undefined>,
106-
locale: string,
107-
detect: false | DetectBrowserLanguageOptions
108-
) {
109-
if (detect === false || !detect.useCookie) {
110-
return
111-
}
112-
113-
cookieRef.value = locale
114-
}
115-
116100
type DetectFailureStates =
117101
| 'not_found_match'
118102
| 'first_access_only'
@@ -194,6 +178,5 @@ export function runtimeDetectBrowserLanguage(
194178
opts: I18nPublicRuntimeConfig = useRuntimeConfig().public.i18n as I18nPublicRuntimeConfig
195179
) {
196180
if (opts?.detectBrowserLanguage === false) return false
197-
198181
return opts?.detectBrowserLanguage
199182
}

src/runtime/plugins/i18n.ts

+11-10
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,12 @@ import { loadVueI18nOptions, loadLocale } from '../messages'
1313
import { loadAndSetLocale, detectRedirect, navigate, extendBaseUrl, createNuxtI18nDev } from '../utils'
1414
import {
1515
getLocaleCookie,
16-
getI18nCookie,
16+
createI18nCookie,
1717
runtimeDetectBrowserLanguage,
1818
wrapComposable,
19-
getBrowserLocale,
20-
setLocaleCookie
19+
getBrowserLocale
2120
} from '../internal'
22-
import { createLocaleFromRouteGetter, resolveBaseUrl } from '../routing/utils'
21+
import { createLocaleFromRouteGetter } from '../routing/utils'
2322
import { extendI18n } from '../routing/i18n'
2423
import { createLogger } from '#nuxt-i18n/logger'
2524
import { getI18nTarget } from '../compatibility'
@@ -30,8 +29,7 @@ import { getDefaultLocaleForDomain, setupMultiDomainLocales } from '../domain'
3029

3130
import type { Locale, I18nOptions, Composer } from 'vue-i18n'
3231
import type { NuxtApp } from '#app'
33-
import type { LocaleObject } from '#internal-i18n-types'
34-
import type { I18nPublicRuntimeConfig } from '#internal-i18n-types'
32+
import type { LocaleObject, I18nPublicRuntimeConfig } from '#internal-i18n-types'
3533
import type { LocaleHeadFunction, ResolveRouteFunction } from '../composables'
3634

3735
export default defineNuxtPlugin({
@@ -87,7 +85,7 @@ export default defineNuxtPlugin({
8785
nuxt._nuxtI18nDev = createNuxtI18nDev()
8886
}
8987

90-
const localeCookie = getI18nCookie()
88+
const localeCookie = createI18nCookie()
9189
const detectBrowserOptions = runtimeDetectBrowserLanguage()
9290
// extend i18n instance
9391
extendI18n(i18n, {
@@ -98,11 +96,11 @@ export default defineNuxtPlugin({
9896
const _localeCodes = ref<Locale[]>(localeCodes)
9997
composer.localeCodes = computed(() => _localeCodes.value)
10098

101-
const _baseUrl = ref<string>(resolveBaseUrl(runtimeI18n.baseUrl, nuxt))
99+
const _baseUrl = ref(runtimeI18n.baseUrl())
102100
composer.baseUrl = computed(() => _baseUrl.value)
103101

104102
if (import.meta.client) {
105-
watch(composer.locale, () => (_baseUrl.value = resolveBaseUrl(runtimeI18n.baseUrl, nuxt)))
103+
watch(composer.locale, () => (_baseUrl.value = runtimeI18n.baseUrl()))
106104
}
107105

108106
composer.strategy = runtimeI18n.strategy
@@ -133,7 +131,10 @@ export default defineNuxtPlugin({
133131
composer.defaultLocale = runtimeI18n.defaultLocale
134132
composer.getBrowserLocale = () => getBrowserLocale()
135133
composer.getLocaleCookie = () => getLocaleCookie(localeCookie, detectBrowserOptions, composer.defaultLocale)
136-
composer.setLocaleCookie = (locale: string) => setLocaleCookie(localeCookie, locale, detectBrowserOptions)
134+
composer.setLocaleCookie = (locale: string) => {
135+
if (!detectBrowserOptions || !detectBrowserOptions.useCookie) return
136+
localeCookie.value = locale
137+
}
137138

138139
composer.onBeforeLanguageSwitch = (oldLocale, newLocale, initialSetup, context) =>
139140
nuxt.callHook('i18n:beforeLocaleSwitch', {

0 commit comments

Comments
 (0)