forked from nuxt-modules/i18n
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
604 lines (506 loc) · 17.1 KB
/
utils.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
import { promises as fs, readFileSync as _readFileSync, constants as FS_CONSTANTS } from 'node:fs'
import { createHash } from 'node:crypto'
import { resolvePath } from '@nuxt/kit'
import { parse as parsePath, resolve, relative, normalize, join } from 'pathe'
import { parse as _parseCode } from '@babel/parser'
import { defu } from 'defu'
import { encodePath } from 'ufo'
import { resolveLockfile } from 'pkg-types'
// @ts-ignore
import { transform as stripType } from '@mizchi/sucrase'
import { isString, isRegExp, isFunction, isArray, isObject } from '@intlify/shared'
import { NUXT_I18N_MODULE_ID, TS_EXTENSIONS, EXECUTABLE_EXTENSIONS, NULL_HASH } from './constants'
import type { NuxtI18nOptions, LocaleInfo, VueI18nConfigPathInfo, LocaleType, LocaleFile } from './types'
import type { Nuxt, NuxtConfigLayer } from '@nuxt/schema'
import type { File } from '@babel/types'
import type { LocaleObject } from 'vue-i18n-routing'
import { genSafeVariableName } from 'knitwork'
const PackageManagerLockFiles = {
'npm-shrinkwrap.json': 'npm-legacy',
'package-lock.json': 'npm',
'yarn.lock': 'yarn',
'pnpm-lock.yaml': 'pnpm'
} as const
type LockFile = keyof typeof PackageManagerLockFiles
// prettier-ignore
type _PackageManager = typeof PackageManagerLockFiles[LockFile]
export type PackageManager = _PackageManager | 'unknown'
export async function getPackageManagerType(): Promise<PackageManager> {
try {
const parsed = parsePath(await resolveLockfile())
const lockfile = `${parsed.name}${parsed.ext}` as LockFile
if (lockfile == null) {
return 'unknown'
}
const type = PackageManagerLockFiles[lockfile]
return type == null ? 'unknown' : type
} catch (e) {
throw e
}
}
export function formatMessage(message: string) {
return `[${NUXT_I18N_MODULE_ID}]: ${message}`
}
export function getNormalizedLocales(locales: NuxtI18nOptions['locales']): LocaleObject[] {
locales = locales || []
const normalized: LocaleObject[] = []
for (const locale of locales) {
if (isString(locale)) {
normalized.push({ code: locale, iso: locale })
} else {
normalized.push(locale)
}
}
return normalized
}
const IMPORT_ID_CACHES = new Map<string, string>()
export const normalizeWithUnderScore = (name: string) => name.replace(/-/g, '_').replace(/\./g, '_').replace(/\//g, '_')
function convertToImportId(file: string) {
if (IMPORT_ID_CACHES.has(file)) {
return IMPORT_ID_CACHES.get(file)
}
const { dir, base } = parsePath(file)
const id = normalizeWithUnderScore(`${dir}/${base}`)
IMPORT_ID_CACHES.set(file, id)
return id
}
export async function resolveLocales(
path: string,
locales: LocaleObject[],
relativeBase: string
): Promise<LocaleInfo[]> {
const files = await Promise.all(locales.flatMap(x => getLocalePaths(x)).map(x => resolve(path, x)))
const find = (f: string) => files.find(file => file === resolve(path, f))
const localesResolved: LocaleInfo[] = []
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for (const { file, ...locale } of locales) {
const resolved: LocaleInfo = { ...locale, files: [], meta: undefined }
const files = getLocaleFiles(locale)
resolved.meta = files.map(file => {
const filePath = find(file.path) ?? ''
const isCached = filePath ? getLocaleType(filePath) !== 'dynamic' : true
const parsed = parsePath(filePath)
const importKey = join(parsed.root, parsed.dir, parsed.base)
const key = genSafeVariableName(`locale_${convertToImportId(importKey)}`)
return {
path: filePath,
loadPath: normalize(`${relativeBase}/${file.path}`),
type: getLocaleType(filePath),
hash: getHash(filePath),
parsed,
key,
file: {
path: file.path,
cache: file.cache ?? isCached
}
}
})
resolved.files = resolved.meta.map(meta => meta.file)
localesResolved.push(resolved)
}
return localesResolved
}
function getLocaleType(path: string): LocaleType {
const ext = parsePath(path).ext
if (EXECUTABLE_EXTENSIONS.includes(ext)) {
const code = readCode(path, ext)
const parsed = parseCode(code, path)
const analyzed = scanProgram(parsed.program)
if (analyzed === 'object') {
return 'static'
} else if (analyzed === 'function' || analyzed === 'arrow-function') {
return 'dynamic'
} else {
return 'unknown'
}
} else {
return 'static'
}
}
const PARSE_CODE_CACHES = new Map<string, ReturnType<typeof _parseCode>>()
function parseCode(code: string, path: string) {
if (PARSE_CODE_CACHES.has(path)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return PARSE_CODE_CACHES.get(path)!
}
const parsed = _parseCode(code, {
allowImportExportEverywhere: true,
sourceType: 'module'
})
PARSE_CODE_CACHES.set(path, parsed)
return parsed
}
function scanProgram(program: File['program'] /*, calleeName: string*/) {
let ret: false | 'object' | 'function' | 'arrow-function' = false
for (const node of program.body) {
if (node.type === 'ExportDefaultDeclaration') {
if (node.declaration.type === 'ObjectExpression') {
ret = 'object'
break
} else if (
node.declaration.type === 'CallExpression' &&
node.declaration.callee.type === 'Identifier' // &&
// node.declaration.callee.name === calleeName
) {
const [fnNode] = node.declaration.arguments
if (fnNode.type === 'FunctionExpression') {
ret = 'function'
break
} else if (fnNode.type === 'ArrowFunctionExpression') {
ret = 'arrow-function'
break
}
}
}
}
return ret
}
export function readCode(absolutePath: string, ext: string) {
let code = readFileSync(absolutePath)
if (TS_EXTENSIONS.includes(ext)) {
const out = stripType(code, {
transforms: ['jsx'],
keepUnusedImports: true
})
code = out.code
}
return code
}
export function getLayerRootDirs(nuxt: Nuxt) {
const layers = nuxt.options._layers
return layers.length > 1 ? layers.map(layer => layer.config.rootDir) : []
}
export async function tryResolve(id: string, targets: string[], pkgMgr: PackageManager, extension = '') {
for (const target of targets) {
if (await isExists(target + extension)) {
return target
}
}
throw new Error(`Cannot resolve ${id} on ${pkgMgr}! please install it on 'node_modules'`)
}
export async function writeFile(path: string, data: string) {
await fs.writeFile(path, data, { encoding: 'utf-8' })
}
export async function readFile(path: string) {
return await fs.readFile(path, { encoding: 'utf-8' })
}
export function readFileSync(path: string) {
return _readFileSync(path, { encoding: 'utf-8' })
}
export async function isExists(path: string) {
try {
await fs.access(path, FS_CONSTANTS.F_OK)
return true
} catch (e) {
return false
}
}
export async function resolveVueI18nConfigInfo(options: NuxtI18nOptions, buildDir: string, rootDir: string) {
const configPathInfo: Required<VueI18nConfigPathInfo> = {
relativeBase: relative(buildDir, rootDir),
relative: options.vueI18n ?? 'i18n.config',
absolute: '',
rootDir,
hash: NULL_HASH,
type: 'unknown',
meta: {
path: '',
loadPath: '',
type: 'unknown',
hash: NULL_HASH,
key: '',
parsed: { base: '', dir: '', ext: '', name: '', root: '' }
}
}
const absolutePath = await resolvePath(configPathInfo.relative, { cwd: rootDir, extensions: EXECUTABLE_EXTENSIONS })
if (!(await isExists(absolutePath))) return undefined
const parsed = parsePath(absolutePath)
const loadPath = join(configPathInfo.relativeBase, relative(rootDir, absolutePath))
configPathInfo.absolute = absolutePath
configPathInfo.type = getLocaleType(absolutePath)
configPathInfo.hash = getHash(loadPath)
const key = `${normalizeWithUnderScore(configPathInfo.relative)}_${configPathInfo.hash}`
configPathInfo.meta = {
path: absolutePath,
type: configPathInfo.type,
hash: configPathInfo.hash,
loadPath,
parsed,
key
}
return configPathInfo
}
export type PrerenderTarget = {
type: 'locale' | 'config'
path: string
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function toCode(code: any): string {
if (code === null) {
return `null`
}
if (code === undefined) {
return `undefined`
}
if (isString(code)) {
return JSON.stringify(code)
}
if (isRegExp(code) && code.toString) {
return code.toString()
}
if (isFunction(code) && code.toString) {
return `(${code.toString().replace(new RegExp(`^${code.name}`), 'function ')})`
}
if (isArray(code)) {
return `[${code.map(c => toCode(c)).join(`,`)}]`
}
if (isObject(code)) {
return stringifyObj(code)
}
return code + ``
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function stringifyObj(obj: Record<string, any>): string {
return `Object({${Object.entries(obj)
.map(([key, value]) => `${JSON.stringify(key)}:${toCode(value)}`)
.join(`,`)}})`
}
/**
* segment parser, forked from the below:
* - original repository url: https://github.com/nuxt/framework
* - code url: https://github.com/nuxt/framework/blob/main/packages/nuxt/src/pages/utils.ts
* - author: Nuxt Framework Team
* - license: MIT
*/
enum SegmentParserState {
initial,
static,
dynamic,
optional,
catchall
}
enum SegmentTokenType {
static,
dynamic,
optional,
catchall
}
interface SegmentToken {
type: SegmentTokenType
value: string
}
const PARAM_CHAR_RE = /[\w\d_.]/
export function parseSegment(segment: string) {
let state: SegmentParserState = SegmentParserState.initial
let i = 0
let buffer = ''
const tokens: SegmentToken[] = []
function consumeBuffer() {
if (!buffer) {
return
}
if (state === SegmentParserState.initial) {
throw new Error('wrong state')
}
tokens.push({
type:
state === SegmentParserState.static
? SegmentTokenType.static
: state === SegmentParserState.dynamic
? SegmentTokenType.dynamic
: state === SegmentParserState.optional
? SegmentTokenType.optional
: SegmentTokenType.catchall,
value: buffer
})
buffer = ''
}
while (i < segment.length) {
const c = segment[i]
switch (state) {
case SegmentParserState.initial:
buffer = ''
if (c === '[') {
state = SegmentParserState.dynamic
} else {
i--
state = SegmentParserState.static
}
break
case SegmentParserState.static:
if (c === '[') {
consumeBuffer()
state = SegmentParserState.dynamic
} else {
buffer += c
}
break
case SegmentParserState.catchall:
case SegmentParserState.dynamic:
case SegmentParserState.optional:
if (buffer === '...') {
buffer = ''
state = SegmentParserState.catchall
}
if (c === '[' && state === SegmentParserState.dynamic) {
state = SegmentParserState.optional
}
if (c === ']' && (state !== SegmentParserState.optional || buffer[buffer.length - 1] === ']')) {
if (!buffer) {
throw new Error('Empty param')
} else {
consumeBuffer()
}
state = SegmentParserState.initial
} else if (PARAM_CHAR_RE.test(c)) {
buffer += c
} else {
// eslint-disable-next-line no-console
// console.debug(`[pages]Ignored character "${c}" while building param "${buffer}" from "segment"`)
}
break
}
i++
}
if (state === SegmentParserState.dynamic) {
throw new Error(`Unfinished param "${buffer}"`)
}
consumeBuffer()
return tokens
}
export const resolveRelativeLocales = (
relativeFileResolver: (files: LocaleFile[]) => LocaleFile[],
locale: LocaleObject | string,
merged: LocaleObject | undefined
) => {
if (typeof locale === 'string') return merged ?? { iso: locale, code: locale }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { file, files, ...entry } = locale
const fileEntries = getLocaleFiles(locale)
const relativeFiles = relativeFileResolver(fileEntries)
const mergedLocaleObject = typeof merged === 'string' ? undefined : merged
return {
...entry,
...mergedLocaleObject,
// @ts-ignore
files: [...(relativeFiles ?? []), ...((mergedLocaleObject?.files ?? []) as LocaleObject)]
}
}
export const getLocalePaths = (locale: LocaleObject): string[] => {
if (locale.file != null) {
return [locale.file as unknown as LocaleFile].map(x => (typeof x === 'string' ? x : x.path))
}
if (locale.files != null) {
return [...locale.files].map(x => (typeof x === 'string' ? x : x.path))
}
return []
}
export const getLocaleFiles = (locale: LocaleObject | LocaleInfo): LocaleFile[] => {
if (locale.file != null) {
return [locale.file].map(x => (typeof x === 'string' ? { path: x, cache: undefined } : x))
}
if (locale.files != null) {
return [...locale.files].map(x => (typeof x === 'string' ? { path: x, cache: undefined } : x))
}
return []
}
export const localeFilesToRelative = (projectLangDir: string, layerLangDir: string = '', files: LocaleFile[] = []) => {
const absoluteFiles = files.map(file => ({ path: resolve(layerLangDir, file.path), cache: file.cache }))
const relativeFiles = absoluteFiles.map(file => ({ path: relative(projectLangDir, file.path), cache: file.cache }))
return relativeFiles
}
export const getProjectPath = (nuxt: Nuxt, ...target: string[]) => {
const projectLayer = nuxt.options._layers[0]
return resolve(projectLayer.config.rootDir, ...target)
}
export type LocaleConfig = {
projectLangDir: string
langDir?: string | null
locales?: string[] | LocaleObject[]
}
/**
* Generically merge LocaleObject locales
*
* @param configs prepared configs to resolve locales relative to project
* @param baseLocales optional array of locale objects to merge configs into
*/
export const mergeConfigLocales = (configs: LocaleConfig[], baseLocales: LocaleObject[] = []) => {
const mergedLocales = new Map<string, LocaleObject>()
baseLocales.forEach(locale => mergedLocales.set(locale.code, locale))
const getLocaleCode = (val: string | LocaleObject) => (typeof val === 'string' ? val : val.code)
for (const { locales, langDir, projectLangDir } of configs) {
if (locales == null) continue
for (const locale of locales) {
const code = getLocaleCode(locale)
const filesResolver = (files: LocaleFile[]) => localeFilesToRelative(projectLangDir, langDir ?? '', files)
const resolvedLocale = resolveRelativeLocales(filesResolver, locale, mergedLocales.get(code))
if (resolvedLocale != null) mergedLocales.set(code, resolvedLocale)
}
}
return Array.from(mergedLocales.values())
}
/**
* Merges project layer locales with registered i18n modules
*/
export const mergeI18nModules = async (options: NuxtI18nOptions, nuxt: Nuxt) => {
if (options) options.i18nModules = []
const registerI18nModule = (config: Pick<NuxtI18nOptions, 'langDir' | 'locales'>) => {
if (config.langDir == null) return
options?.i18nModules?.push(config)
}
await nuxt.callHook('i18n:registerModule', registerI18nModule)
const modules = options?.i18nModules ?? []
const projectLangDir = getProjectPath(nuxt, nuxt.options.rootDir)
if (modules.length > 0) {
const baseLocales: LocaleObject[] = []
const layerLocales = options.locales ?? []
for (const locale of layerLocales) {
if (typeof locale !== 'object') continue
baseLocales.push({ ...locale, file: undefined, files: getLocaleFiles(locale) })
}
const mergedLocales = mergeConfigLocales(
modules.map(x => ({ ...x, projectLangDir })),
baseLocales
)
options.locales = mergedLocales
}
}
export function getRoutePath(tokens: SegmentToken[]): string {
return tokens.reduce((path, token) => {
// prettier-ignore
return (
path +
(token.type === SegmentTokenType.optional
? `:${token.value}?`
: token.type === SegmentTokenType.dynamic
? `:${token.value}`
: token.type === SegmentTokenType.catchall
? `:${token.value}(.*)*`
: encodePath(token.value))
)
}, '/')
}
export function getHash(text: Buffer | string): string {
return createHash('sha256').update(text).digest('hex').substring(0, 8)
}
export function getLayerI18n(configLayer: NuxtConfigLayer) {
const layerInlineOptions = (configLayer.config.modules || []).find(
(mod): mod is [string, NuxtI18nOptions] | undefined =>
isArray(mod) &&
typeof mod[0] === 'string' &&
[NUXT_I18N_MODULE_ID, `${NUXT_I18N_MODULE_ID}-edge`].includes(mod[0])
)?.[1]
if (configLayer.config.i18n) {
return defu(configLayer.config.i18n, layerInlineOptions)
}
return layerInlineOptions
}
export const applyOptionOverrides = (options: NuxtI18nOptions, nuxt: Nuxt) => {
const project = nuxt.options._layers[0]
const { overrides, ...mergedOptions } = options
if (overrides) {
delete options.overrides
project.config.i18n = defu(overrides, project.config.i18n)
Object.assign(options, defu(overrides, mergedOptions))
}
}