forked from intlify/bundle-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjs.ts
More file actions
419 lines (388 loc) · 13 KB
/
js.ts
File metadata and controls
419 lines (388 loc) · 13 KB
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
/**
* Code generator for i18n js resource
*/
import { isBoolean, isNumber, isString } from '@intlify/shared'
import { generate as generateJavaScript } from 'escodegen'
import { parseSync as parseJavaScript } from 'oxc-parser'
import { walk } from 'oxc-walker'
import {
createCodeGenerator,
generateMessageFunction,
generateResourceAst,
mapLinesColumns
} from './codegen'
import type { Node } from 'oxc-parser'
import type { RawSourceMap } from 'source-map-js'
import type { CodeGenerator, CodeGenFunction, CodeGenOptions, CodeGenResult } from './codegen'
export class DynamicResourceError extends Error {}
/**
* @internal
*/
export const DEFAULT_OPTIONS: CodeGenOptions = {
type: 'plain',
filename: 'vue-i18n-loader.js',
inSourceMap: undefined,
locale: '',
isGlobal: false,
sourceMap: false,
env: 'development',
forceStringify: false,
onError: undefined,
onWarn: undefined,
strictMessage: true,
escapeHtml: false,
allowDynamic: false,
jit: false
}
/**
* @internal
*/
export function generate(
targetSource: string | Buffer,
options: CodeGenOptions
): CodeGenResult<Node> {
const value = Buffer.isBuffer(targetSource) ? targetSource.toString() : targetSource
const _options = Object.assign({}, DEFAULT_OPTIONS, options, { source: value })
const generator = createCodeGenerator(_options)
const { program: ast } = parseJavaScript(_options.filename ?? '', value, {
sourceType: 'module',
lang: 'js'
})
const exportResult = scanAst(ast)
if (!_options.allowDynamic) {
if (!exportResult) {
throw new Error(`You need to define an object as the locale message with 'export default'.`)
}
if (exportResult !== 'object') {
// using custom error to gracefully deal with error in virtual file
throw new DynamicResourceError(
`You need to define an object as the locale message with 'export default'.`
)
}
} else {
if (!exportResult) {
throw new Error(`You need to define 'export default' that will return the locale messages.`)
}
if (exportResult !== 'object') {
/**
* NOTE:
* If `allowDynamic` is `true`, do not transform the code by this function, return it as is.
* This means that the user **must transform locale messages ownself**.
* Especially at the production, you need to do locale messages pre-compiling.
*/
return {
ast,
code: value,
map: _options.inSourceMap
}
}
}
const codeMaps = _generate(generator, ast, _options)
const { code, map } = generator.context()
// prettier-ignore
const newMap = map
? mapLinesColumns((map as any).toJSON(), codeMaps, _options.inSourceMap) || null
: null
return {
ast,
code,
map: newMap != null ? newMap : undefined
}
}
function scanAst(ast: Node) {
if (ast.type !== 'Program') {
throw new Error('Invalid AST: does not have Program node')
}
for (const node of ast.body) {
if (node.type !== 'ExportDefaultDeclaration') continue
switch (node.declaration.type) {
case 'ObjectExpression':
return 'object'
case 'FunctionDeclaration':
return 'function'
case 'ArrowFunctionExpression':
return 'arrow-function'
// we need to optimize top-level variables to support this
// case 'Identifier':
// return 'object'
}
}
return false
}
function _generate(
generator: CodeGenerator,
node: Node,
options: CodeGenOptions = {}
): Map<string, RawSourceMap> {
const propsCountStack = [] as number[]
const pathStack = [] as string[]
const itemsCountStack = [] as number[]
const skipStack = [] as boolean[]
const { forceStringify } = generator.context()
const codeMaps = new Map<string, RawSourceMap>()
const { type, sourceMap, isGlobal, locale, jit } = options
const _codegenFn: CodeGenFunction = jit ? generateResourceAst : generateMessageFunction
function codegenFn(value: string) {
const { code, map } = _codegenFn(value, options, pathStack)
sourceMap && map != null && codeMaps.set(value, map)
return code
}
const componentNamespace = '_Component'
const variableDeclarations: string[] = []
// slice and reuse imports and top-level variable declarations as-is
// NOTE: this prevents optimization/compilation of top-level variables, we may be able to add support for this
walk(node, {
// @ts-ignore
enter(node, parent) {
if (parent?.type != null) this.skip()
switch (node.type) {
case 'ExportDefaultDeclaration':
this.skip()
break
case 'ImportDeclaration':
// @ts-expect-error mismatching types
generator.push(options.source?.slice(node.start, node.end))
generator.newline()
break
case 'VariableDeclaration':
// @ts-expect-error mismatching types
generator.push(options.source?.slice(node.start, node.end))
generator.newline()
variableDeclarations.push(
// @ts-expect-error mismatching types
...node.declarations.map(x => `\`${x.id.name}\``)
)
break
}
}
})
if (variableDeclarations.length > 0) {
options?.onWarn?.(
`\nVariable declarations are not optimized - found ${variableDeclarations.join(', ')}`
)
}
walk(node, {
/**
* NOTE:
* force cast to Node of `estree-walker@3.x`,
* because `estree-walker@3.x` is not dual packages,
* so it's support only esm only ...
*/
// @ts-ignore
enter(node, parent) {
// skip imports and top-level variable declarations
if (parent?.type === 'Program') {
switch (node.type) {
case 'ImportDeclaration':
case 'VariableDeclaration':
case 'VariableDeclarator':
this.skip()
}
} else if (parent?.type === 'ArrayExpression') {
const lastIndex = itemsCountStack.length - 1
const currentCount = parent.elements.length - itemsCountStack[lastIndex]
pathStack.push(currentCount.toString())
itemsCountStack[lastIndex] = --itemsCountStack[lastIndex]
} else if (parent?.type === 'ObjectExpression') {
const lastIndex = propsCountStack.length - 1
propsCountStack[lastIndex] = --propsCountStack[lastIndex]
}
switch (node.type) {
case 'Program':
if (type === 'plain') {
generator.push(`const resource = `)
} else if (type === 'sfc') {
const localeName = JSON.stringify(locale ?? '""')
const variableName = !isGlobal ? '__i18n' : '__i18nGlobal'
generator.push(`export default function (Component) {`)
generator.indent()
generator.pushline(`const ${componentNamespace} = Component`)
generator.pushline(
`${componentNamespace}.${variableName} = ${componentNamespace}.${variableName} || []`
)
generator.push(`${componentNamespace}.${variableName}.push({`)
generator.indent()
generator.pushline(`"locale": ${localeName},`)
generator.push(`"resource": `)
}
break
case 'ObjectExpression':
generator.push('{')
generator.indent()
propsCountStack.push(node.properties.length)
break
case 'ArrayExpression':
generator.push('[')
generator.indent()
itemsCountStack.push(node.elements.length)
break
case 'Property':
if (parent?.type !== 'ObjectExpression') break
if (node.key.type !== 'Literal' && node.key.type !== 'Identifier') break
// prettier-ignore
const name = node.key.type === 'Literal'
? String(node.key.value)
: node.key.name
const strName = JSON.stringify(name)
if (isJSONablePrimitiveLiteral(node.value)) {
generator.push(`${strName}: `)
pathStack.push(name)
const value = getValue(node.value) as string
const strValue = JSON.stringify(value)
if (
(node.value.type === 'Literal' && isString(node.value.value)) ||
node.value.type === 'TemplateLiteral'
) {
generator.push(codegenFn(value), node.value, value)
} else if (forceStringify) {
generator.push(codegenFn(strValue), node.value, strValue)
} else {
generator.push(strValue)
}
skipStack.push(false)
} else if (
node.value.type === 'ArrayExpression' ||
node.value.type === 'ObjectExpression'
) {
generator.push(`${strName}: `)
pathStack.push(name)
skipStack.push(false)
} else if (
node.value.type === 'FunctionExpression' ||
node.value.type === 'ArrowFunctionExpression'
) {
generator.push(`${strName}: `)
pathStack.push(name)
const code = generateJavaScript(node.value, {
format: { compact: true }
})
generator.push(code, node.value, code)
skipStack.push(false)
} else {
const skipProperty = 'regex' in node.value
if (!skipProperty && node.type === 'Property') {
const identifierName =
(node.value.type === 'Identifier' && String(node.value.name)) ||
(node.value.type === 'Literal' && String(node.value.value))
generator.push(`${strName}: ${identifierName || name}`)
skipStack.push(false)
} else {
// for Regex, function, etc.
skipStack.push(true)
}
}
break
case 'SpreadElement':
const spreadIdentifier =
(node.argument.type === 'Identifier' && String(node.argument.name)) ||
(node.argument.type === 'Literal' && String(node.argument.value))
generator.push(`...${spreadIdentifier}`)
break
default:
if (parent?.type === 'ArrayExpression') {
if (isJSONablePrimitiveLiteral(node)) {
const value = getValue(node) as string
const strValue = JSON.stringify(value)
if (
(node.type === 'Literal' && isString(node.value)) ||
node.type === 'TemplateLiteral'
) {
generator.push(codegenFn(value), node, value)
} else if (forceStringify) {
generator.push(codegenFn(strValue), node, strValue)
} else {
generator.push(strValue)
}
skipStack.push(false)
} else {
// for Regex, function, etc.
skipStack.push(true)
}
}
break
}
},
// @ts-ignore
leave(node: Node, parent: Node) {
switch (node.type) {
case 'Program':
if (type === 'plain') {
generator.push('\n')
generator.push('export default resource')
} else if (type === 'sfc') {
generator.deindent()
generator.push('})')
generator.deindent()
generator.pushline('}')
}
break
case 'ObjectExpression':
if (propsCountStack[propsCountStack.length - 1] === 0) {
pathStack.pop()
propsCountStack.pop()
}
generator.deindent()
generator.push('}')
break
case 'ArrayExpression':
if (itemsCountStack[itemsCountStack.length - 1] === 0) {
pathStack.pop()
itemsCountStack.pop()
}
generator.deindent()
generator.push(']')
break
default:
break
}
// if not last obj property or array value
if (parent?.type === 'ArrayExpression' || parent?.type === 'ObjectExpression') {
const stackArr = node.type === 'Property' ? propsCountStack : itemsCountStack
if (stackArr[stackArr.length - 1] !== 0) {
pathStack.pop()
!skipStack.pop() && generator.pushline(',')
}
}
}
})
return codeMaps
}
function isJSONablePrimitiveLiteral(node: Node): boolean {
return (
(node.type === 'Literal' &&
(isString(node.value) ||
isNumber(node.value) ||
isBoolean(node.value) ||
node.value === null)) ||
node.type === 'TemplateLiteral'
)
// NOTE: the following code is same the above code
/*
if (node.type === 'Literal') {
if (
isString(node.value) ||
isNumber(node.value) ||
isBoolean(node.value) ||
node.value === null
) {
return true
} else if (isRegExp(node.value)) {
return false
} else {
return false
}
} else if (node.type === 'TemplateLiteral') {
return true
} else {
return false
}
*/
}
function getValue(node: Node) {
// prettier-ignore
return node.type === 'Literal'
? node.value
: node.type === 'TemplateLiteral'
? node.quasis.map(quasi => quasi.value.cooked).join('')
: undefined
}