-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
69 lines (54 loc) · 1.79 KB
/
index.js
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
import stringReplaceAsync from 'string-replace-async'
import stringify from '~/common/stringify'
import preparePlural from '~/common/Plural'
import pluralInliner from './inliner'
const pluralArgsRegex = /[\s\n]*,[\s\n]*/
export default ({
namespace,
lang,
supported,
dictionary,
defaultLang,
plurals,
}) => {
const customKeyRegexp = new RegExp(`.*${namespace}`)
const moduleNamespace = `${namespace}_methods`
const pluralRegexp = new RegExp(`[\\w.]*(?:\\(\\.*?\\)\\s*=>\\s*)?${namespace}(?:\\.(\\w*))?(?:\\(([\\s\\S]*?)\\))?`, 'ig')
const replacer = async (match, prop, string) => {
if (!(prop || string)) return match
if (prop === 'supported') return JSON.stringify((supported || [lang]).sort())
if (prop === 'current') return JSON.stringify(lang)
const { methods, keys } = await dictionary()
if (methods[prop]) {
return match.replace(customKeyRegexp, moduleNamespace)
}
const [value, pluralKey, currLang] = string.trim().split(pluralArgsRegex)
const key = pluralKey.slice(1, -1)
try {
const {
arity,
plural,
pluralArr,
} = preparePlural({
keys,
key,
lang,
plurals,
defaultLang: currLang ? currLang.slice(1, -1) : defaultLang,
})
return pluralInliner({
arity,
pluralArr,
plural: plural.replace(/n/g, `Math.abs(${value})`),
}).replace(/\$\{(.*?)\}/, '$1')
} catch (e) {
throw Error(`module-i18n loader error for in '${match}'. ${e.message}`)
}
}
return async (source) => {
const result = await stringReplaceAsync(await source, pluralRegexp, replacer)
return result.includes(moduleNamespace)
? `const ${moduleNamespace} = ${stringify((await dictionary()).methods)};\n`.concat(result)
: result
}
}