-
-
Notifications
You must be signed in to change notification settings - Fork 764
/
Copy pathcreateConfig.ts
303 lines (276 loc) · 9.32 KB
/
createConfig.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import { defaultConfig } from './defaultConfig'
import { InternalConfig, UserConfig } from '../types'
import { getFallbackForLng, unique } from '../utils'
import { FallbackLngObjList, Module } from 'i18next'
const deepMergeObjects = ['backend', 'detection'] as (keyof Pick<
UserConfig,
'backend' | 'detection'
>)[]
export const createConfig = (
userConfig: UserConfig
): InternalConfig => {
if (typeof userConfig?.lng !== 'string') {
throw new Error('config.lng was not passed into createConfig')
}
//
// Initial merge of default and user-provided config
//
const { i18n: userI18n, ...userConfigStripped } = userConfig
const { i18n: defaultI18n, ...defaultConfigStripped } =
defaultConfig
const combinedConfig = {
...defaultConfigStripped,
...userConfigStripped,
...defaultI18n,
...userI18n,
}
const {
defaultNS,
lng,
localeExtension,
localePath,
nonExplicitSupportedLngs,
} = combinedConfig
const locales = combinedConfig.locales.filter((l: string) => l !== 'default')
/**
* Skips translation file resolution while in cimode
* https://github.com/i18next/next-i18next/pull/851#discussion_r503113620
*/
if (lng === 'cimode') {
return combinedConfig as InternalConfig
}
if (typeof combinedConfig.fallbackLng === 'undefined') {
combinedConfig.fallbackLng = combinedConfig.defaultLocale
if (combinedConfig.fallbackLng === 'default')
[combinedConfig.fallbackLng] = locales
}
const userPrefix = userConfig?.interpolation?.prefix
const userSuffix = userConfig?.interpolation?.suffix
const prefix = userPrefix ?? '{{'
const suffix = userSuffix ?? '}}'
if (
typeof userConfig?.localeStructure !== 'string' &&
(userPrefix || userSuffix)
) {
combinedConfig.localeStructure = `${prefix}lng${suffix}/${prefix}ns${suffix}`
}
const { fallbackLng, localeStructure } = combinedConfig
if (nonExplicitSupportedLngs) {
const createFallbackObject = (
acc: FallbackLngObjList,
l: string
) => {
const [locale] = l.split('-')
acc[l] = [locale]
return acc
}
if (typeof fallbackLng === 'string') {
combinedConfig.fallbackLng = combinedConfig.locales
.filter((l: string) => l.includes('-'))
.reduce(createFallbackObject, { default: [fallbackLng] })
} else if (Array.isArray(fallbackLng)) {
combinedConfig.fallbackLng = combinedConfig.locales
.filter((l: string) => l.includes('-'))
.reduce(createFallbackObject, { default: fallbackLng })
} else if (typeof fallbackLng === 'object') {
combinedConfig.fallbackLng = Object.entries(
combinedConfig.fallbackLng
).reduce<FallbackLngObjList>((acc, [l, f]: [string, any]) => {
acc[l] = l.includes('-')
? unique([l.split('-')[0], ...f])
: f
return acc
}, fallbackLng as FallbackLngObjList)
} else if (typeof fallbackLng === 'function') {
throw new Error(
'If nonExplicitSupportedLngs is true, no functions are allowed for fallbackLng'
)
}
}
const hasCustomBackend = userConfig?.use?.some(
(b: Module) => b.type === 'backend'
)
if (!process.browser && typeof window === 'undefined') {
combinedConfig.preload = locales
if (!hasCustomBackend) {
const fs = require('fs')
const path = require('path')
//
// Validate defaultNS
// https://github.com/i18next/next-i18next/issues/358
//
if (
typeof defaultNS === 'string' &&
typeof lng !== 'undefined'
) {
if (typeof localePath === 'string') {
const defaultLocaleStructure = localeStructure
.replace(`${prefix}lng${suffix}`, lng)
.replace(`${prefix}ns${suffix}`, defaultNS)
const defaultFile = `/${defaultLocaleStructure}.${localeExtension}`
const defaultNSPath = path.join(localePath, defaultFile)
const defaultNSExists = fs.existsSync(defaultNSPath)
const fallback = getFallbackForLng(
lng,
combinedConfig.fallbackLng
)
const defaultFallbackNSExists = fallback.some(f => {
const fallbackFile = defaultFile.replace(lng, f)
const defaultNSPath = path.join(localePath, fallbackFile)
return fs.existsSync(defaultNSPath)
})
if (
!defaultNSExists &&
!defaultFallbackNSExists &&
process.env.NODE_ENV !== 'production'
) {
throw new Error(
`Default namespace not found at ${defaultNSPath}`
)
}
} else if (typeof localePath === 'function') {
const defaultNSPath = localePath(lng, defaultNS, false)
const defaultNSExists = fs.existsSync(defaultNSPath)
const fallback = getFallbackForLng(
lng,
combinedConfig.fallbackLng
)
const defaultFallbackNSExists = fallback.some(f => {
const defaultNSPath = localePath(f, defaultNS, false)
return fs.existsSync(defaultNSPath)
})
if (
!defaultNSExists &&
!defaultFallbackNSExists &&
process.env.NODE_ENV !== 'production'
) {
throw new Error(
`Default namespace not found at ${defaultNSPath}`
)
}
}
}
//
// Set server side backend
//
if (typeof localePath === 'string') {
combinedConfig.backend = {
addPath: path.resolve(
process.cwd(),
`${localePath}/${localeStructure}.missing.${localeExtension}`
),
loadPath: path.resolve(
process.cwd(),
`${localePath}/${localeStructure}.${localeExtension}`
),
}
} else if (typeof localePath === 'function') {
combinedConfig.backend = {
addPath: (locale: string, namespace: string) =>
localePath(locale, namespace, true),
loadPath: (locale: string, namespace: string) =>
localePath(locale, namespace, false),
}
} else if (localePath) {
throw new Error(
`Unsupported localePath type: ${typeof localePath}`
)
}
//
// Set server side preload (namespaces)
//
if (!combinedConfig.ns && typeof lng !== 'undefined') {
if (typeof localePath === 'function') {
throw new Error(
'Must provide all namespaces in ns option if using a function as localePath'
)
}
const getNamespaces = (locales: string[]): string[] => {
const getLocaleNamespaces = (p: string) => {
let ret: string[] = []
if (!fs.existsSync(p)) return ret
fs.readdirSync(p).map((file: string) => {
const joinedP = path.join(p, file)
if (fs.statSync(joinedP).isDirectory()) {
const subRet = getLocaleNamespaces(joinedP).map(
n => `${file}/${n}`
)
ret = ret.concat(subRet)
return
}
ret.push(file.replace(`.${localeExtension}`, ''))
})
return ret
}
let namespacesByLocale
const r = combinedConfig.resources
if (!localePath && r) {
namespacesByLocale = locales.map(locale => Object.keys(r[locale]))
} else {
namespacesByLocale = locales.map(locale =>
getLocaleNamespaces(
path.resolve(process.cwd(), `${localePath}/${locale}`)
)
)
}
const allNamespaces = []
for (const localNamespaces of namespacesByLocale) {
allNamespaces.push(...localNamespaces)
}
return unique(allNamespaces)
}
if (
localeStructure.indexOf(`${prefix}lng${suffix}`) >
localeStructure.indexOf(`${prefix}ns${suffix}`)
) {
throw new Error(
'Must provide all namespaces in ns option if using a localeStructure that is not namespace-listable like lng/ns'
)
}
combinedConfig.ns = getNamespaces(
unique([
lng,
...getFallbackForLng(lng, combinedConfig.fallbackLng),
])
)
}
}
} else {
//
// Set client side backend, if there is no custom backend
//
if (!hasCustomBackend) {
if (typeof localePath === 'string') {
combinedConfig.backend = {
addPath: `${localePath}/${localeStructure}.missing.${localeExtension}`,
loadPath: `${localePath}/${localeStructure}.${localeExtension}`,
}
} else if (typeof localePath === 'function') {
combinedConfig.backend = {
addPath: (locale: string, namespace: string) =>
localePath(locale, namespace, true),
loadPath: (locale: string, namespace: string) =>
localePath(locale, namespace, false),
}
}
}
if (
typeof combinedConfig.ns !== 'string' &&
!Array.isArray(combinedConfig.ns)
) {
combinedConfig.ns = [defaultNS as string]
}
}
//
// Deep merge with overwrite - goes last
//
deepMergeObjects.forEach(obj => {
if (userConfig[obj]) {
combinedConfig[obj] = {
...combinedConfig[obj],
...userConfig[obj],
}
}
})
return combinedConfig as InternalConfig
}