-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
directive.ts
451 lines (412 loc) · 13.7 KB
/
directive.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
import path from 'node:path'
import createDebug from 'debug'
import { isBoolean } from '@intlify/shared'
import { transformVTDirective } from '@intlify/vue-i18n-extensions'
import { analyze as analyzeScope } from '@typescript-eslint/scope-manager'
import {
parse,
simpleTraverse,
AST_NODE_TYPES
} from '@typescript-eslint/typescript-estree'
// @ts-expect-error -- FIXME: missing types
import eslintUitls from '@eslint-community/eslint-utils'
import {
resolveNamespace,
getVitePlugin,
checkVuePlugin,
normalizePath
} from '../utils'
import { parseVueRequest, getVuePluginOptions, getDescriptor } from '../vue'
import type { TranslationSignatureResolver } from '@intlify/vue-i18n-extensions'
import type { Scope } from '@typescript-eslint/scope-manager'
import {
ParserServicesWithTypeInformation,
TSESTree
} from '@typescript-eslint/typescript-estree'
import type { UnpluginOptions, RollupPlugin } from 'unplugin'
import type {
VuePluginResolvedOptions,
TranslationDirectiveResolveIndetifier
} from '../vue'
import type { ResolvedOptions } from './options'
type Node = Parameters<
ParserServicesWithTypeInformation['getSymbolAtLocation']
>[0]
const debug = createDebug(resolveNamespace('directive'))
export function directivePlugin({
optimizeTranslationDirective,
translationIdentifiers
}: ResolvedOptions): UnpluginOptions {
let vuePlugin: RollupPlugin | null = null
let vuePluginOptions: VuePluginResolvedOptions | null = null
const excludeLangs = ['pug', 'jsx', 'tsx']
return {
name: resolveNamespace('directive'),
enforce: 'pre',
vite: {
config(config) {
// @ts-expect-error -- TODO
vuePlugin = getVitePlugin(config, 'vite:vue')
if (!checkVuePlugin(vuePlugin!)) {
return
}
if (optimizeTranslationDirective) {
vuePlugin!.api.options = resolveVueOptions(
vuePlugin!,
optimizeTranslationDirective,
translationIdentifiers
)
debug(`vite:vue options['template']:`, vuePlugin!.api.options)
}
},
configResolved(config) {
vuePlugin = getVitePlugin(config, 'vite:vue')
if (!checkVuePlugin(vuePlugin)) {
return
}
}
},
async transform(code, id) {
if (id.endsWith('.vue')) {
const { filename, query } = parseVueRequest(id)
if (!excludeLangs.includes(query.lang ?? '')) {
// lazy load vue plugin options
if (vuePluginOptions == null) {
vuePluginOptions = getVuePluginOptions(vuePlugin!)
}
if (vuePluginOptions?.compiler) {
analyzeIdentifiers(
getDescriptor(filename, code, vuePluginOptions),
vuePluginOptions,
translationIdentifiers
)
return {
code,
map: { version: 3, mappings: '', sources: [] } as any
}
}
}
}
}
}
}
function resolveVueOptions(
vuePlugin: RollupPlugin,
optimizeTranslationDirective: ResolvedOptions['optimizeTranslationDirective'],
translationIdentifiers: ResolvedOptions['translationIdentifiers']
): any {
const vueOptions = vuePlugin.api.options
vueOptions.template ||= {}
vueOptions.template.compilerOptions ||= {}
vueOptions.template.compilerOptions.directiveTransforms ||= {}
/**
* NOTE:
* This is a custom translation signature resolver for Vue SFC.
* The resolver works by this plugin.
* That is analyzing the identifier of the `t` function exposed by `useI18n` in vue-i18n.
* The analyzed identifier is replaced by the directive transform of the Vue compiler.
*/
const translationSignatureResolver: TranslationSignatureResolver = (
context,
baseResolver
) => {
const { filename } = context
const vuePluginOptions = getVuePluginOptions(vuePlugin)
const normalizedFilename = normalizePath(
path.relative(vuePluginOptions.root, filename)
)
const resolveIdentifier = translationIdentifiers.get(normalizedFilename)
debug('resolved vue-i18n Identifier', resolveIdentifier)
if (resolveIdentifier == null) {
return undefined
}
if (resolveIdentifier.type === 'identifier') {
return baseResolver(context, resolveIdentifier.key)
} else {
// object
const resolvedSignature = baseResolver(context, resolveIdentifier.key)
return resolveIdentifier?.style === 'script-setup'
? `${resolvedSignature}.t`
: resolvedSignature
}
}
vueOptions.template.compilerOptions.directiveTransforms.t =
transformVTDirective({
translationSignatures: isBoolean(optimizeTranslationDirective)
? translationSignatureResolver
: optimizeTranslationDirective
})
return vueOptions
}
function analyzeIdentifiers(
descriptor: ReturnType<typeof getDescriptor>,
{ root }: VuePluginResolvedOptions,
translationIdentifiers: Map<string, TranslationDirectiveResolveIndetifier>
) {
const source = descriptor.scriptSetup?.content || descriptor.script?.content
debug('getDescriptor content', source)
if (!source) {
return
}
const ast = parse(source, { range: true })
simpleTraverse(ast, {
enter(node, parent) {
if (parent) {
node.parent = parent
}
}
})
const scopeManager = analyzeScope(ast, { sourceType: 'module' })
const scope = getScope(scopeManager, ast)
const importLocalName = getImportLocalName(scope, 'vue-i18n', 'useI18n')
if (importLocalName == null) {
return
}
debug('importLocalName', importLocalName)
const resolvedIdentifier = getVueI18nIdentifier(scope, importLocalName!)
if (resolvedIdentifier) {
const normalizedFilename = normalizePath(
path.relative(root, descriptor.filename)
)
debug('set vue-i18n resolved identifier: ', resolvedIdentifier)
translationIdentifiers.set(normalizedFilename, resolvedIdentifier)
}
}
function getScope(manager: ReturnType<typeof analyzeScope>, node: Node): Scope {
const scope = manager.acquire(node, true)
if (scope) {
if (scope.type === 'function-expression-name') {
return scope.childScopes[0]
}
return scope
}
return manager.scopes[0]
}
function getImportLocalName(
scope: Scope,
source: string,
imported: string
): string | null {
const importDecl = getImportDeclaration(scope, source)
if (importDecl) {
const specifierNode = importDecl.specifiers.find(
specifierNode =>
isImportedIdentifierInImportClause(specifierNode) &&
specifierNode.imported.name === imported
)
return specifierNode ? specifierNode.local.name : null
}
return null
}
function getImportDeclaration(scope: Scope, source: string) {
const tracker = new eslintUitls.ReferenceTracker(scope)
const traceMap = {
[source]: {
[eslintUitls.ReferenceTracker.ESM]: true,
[eslintUitls.ReferenceTracker.READ]: true
}
}
const refs = Array.from(tracker.iterateEsmReferences(traceMap)) satisfies {
path: string
node: Node
}[]
return refs.length ? (refs[0].node as TSESTree.ImportDeclaration) : null
}
function isImportedIdentifierInImportClause(
node: TSESTree.ImportClause
): node is TSESTree.ImportClause & { imported: TSESTree.Identifier } {
return 'imported' in node
}
function getVueI18nIdentifier(scope: Scope, local: string) {
// Get the CallExpression and ReturnStatement needed for analysis from scope.
const { callExpression, returnStatement } =
getCallExpressionAndReturnStatement(scope, local)
// If CallExpression cannot get, `useI18n` will not be called and exit from this function
if (callExpression == null) {
return null
}
// Get the AST Nodes from `id` prop on VariableDeclarator
// e.g. `const { t } = useI18n()`
// VariableDeclarator Node: `{ t } = useI18n()`
// expeted AST Nodes: `{ t }`
const id = getVariableDeclarationIdFrom(callExpression)
if (id == null) {
return null
}
// parse variable id from AST Nodes
const variableIdPairs = parseVariableId(id)
debug('variableIdPairs:', variableIdPairs)
// parse variable id from RestStatement Node
const returnVariableIdPairs = parseReturnStatement(returnStatement)
debug('returnVariableIdPairs:', returnVariableIdPairs)
// resolve identifier
return resolveIdentifier(variableIdPairs, returnVariableIdPairs)
}
const EMPTY_NODE_RETURN = {
callExpression: null,
returnStatement: null
} as const
function getCallExpressionAndReturnStatement(
scope: Scope,
local: string
):
| {
callExpression: TSESTree.CallExpression | null
returnStatement: TSESTree.ReturnStatement | null
}
| typeof EMPTY_NODE_RETURN {
// TODO: missing types (eslint-utils)
const variable = eslintUitls.findVariable(scope, local)
if (variable == null) {
return EMPTY_NODE_RETURN
}
// @ts-expect-error -- FIXME: missing types (eslint-utils)
const callExpressionRef = variable.references.find(ref => {
return ref.identifier.parent?.type === AST_NODE_TYPES.CallExpression
})
if (callExpressionRef == null) {
return EMPTY_NODE_RETURN
}
let returnStatement: TSESTree.ReturnStatement | null = null
if (
callExpressionRef.from.type === 'function' &&
callExpressionRef.from.block.type === AST_NODE_TYPES.FunctionExpression &&
callExpressionRef.from.block.parent.type === AST_NODE_TYPES.Property &&
callExpressionRef.from.block.parent.key.type ===
AST_NODE_TYPES.Identifier &&
callExpressionRef.from.block.parent.key.name === 'setup'
) {
returnStatement = callExpressionRef.from.block.body.body.find(
(statement: Node) => {
return statement.type === AST_NODE_TYPES.ReturnStatement
}
) as TSESTree.ReturnStatement | null
}
return {
callExpression: callExpressionRef.identifier
.parent as TSESTree.CallExpression,
returnStatement
}
}
function getVariableDeclarationIdFrom(node: TSESTree.CallExpression) {
if (node.parent?.type !== AST_NODE_TYPES.VariableDeclarator) {
return null
}
return node.parent.id as TSESTree.Identifier | TSESTree.ObjectPattern
}
type VariableIdPair = {
key: string | null
value: string | null
}
function parseVariableId(
node: TSESTree.Identifier | TSESTree.ObjectPattern
): VariableIdPair[] {
if (node.type === AST_NODE_TYPES.Identifier) {
// Identifier
// e.g `const i18n = useI18n()`
// [{ key: 'i18n', value: null }]
return [{ key: node.name, value: null }]
} else {
// ObjectPattern
// e.g `const { t, d: datetime } = useI18n()`
// [{ key: 't', value: 't' }, { key: 'd', value: 'datetime' }]
const props = node.properties.filter(
// ignore RestElement
prop => prop.type === AST_NODE_TYPES.Property
) as TSESTree.Property[]
const pairs = [] as { key: string | null; value: string | null }[]
for (const prop of props) {
if (
prop?.key.type === AST_NODE_TYPES.Identifier &&
prop?.value.type === AST_NODE_TYPES.Identifier
) {
pairs.push({ key: prop.key.name, value: prop.value.name })
}
}
return pairs
}
}
function parseReturnStatement(
node: TSESTree.ReturnStatement | null
): VariableIdPair[] {
const pairs = [] as VariableIdPair[]
if (node == null || node.argument == null) {
return pairs
}
if (node.argument.type === AST_NODE_TYPES.ObjectExpression) {
// ObjectExpression
for (const prop of node.argument.properties) {
if (prop.type === AST_NODE_TYPES.Property) {
if (
prop.key.type === AST_NODE_TYPES.Identifier &&
prop.value.type === AST_NODE_TYPES.Identifier
) {
// Identifier
// e.g `return { t, d: datetime }`
// [{ key: 't', value: 't' }, { key: 'd', value: 'datetime' }]
pairs.push({ key: prop.key.name, value: prop.value.name })
} else if (
prop.key.type === AST_NODE_TYPES.Identifier &&
prop.value.type === AST_NODE_TYPES.MemberExpression &&
prop.value.object.type === AST_NODE_TYPES.Identifier &&
prop.value.property.type === AST_NODE_TYPES.Identifier
) {
// MemberExpression
// e.g `return { t: i18n.t }`
// [{ key: 't', value: 'i18n.t' }]
pairs.push({
key: prop.key.name,
value: `${prop.value.object.name}.${prop.value.property.name}`
})
}
}
}
return pairs
} else if (node.argument.type === AST_NODE_TYPES.Identifier) {
// Identifier
// e.g `return i18n`
return pairs
} else {
// other AST Nodes
return pairs
}
}
function resolveIdentifier(
localVariables: VariableIdPair[],
returnVariable: VariableIdPair[]
): TranslationDirectiveResolveIndetifier | null {
if (returnVariable.length === 0) {
// for `<script setup>`
const variable = localVariables.find(pair => pair.key === 't')
if (variable && variable.value) {
return { type: 'identifier', key: variable.value }
}
const identifierOnly = localVariables.find(pair => pair.value === null)
if (identifierOnly && identifierOnly.key) {
return { type: 'object', key: identifierOnly.key, style: 'script-setup' }
}
return null
} else {
// for `setup() {}` hook
const variable = localVariables.find(pair => pair.key === 't')
if (variable && variable.value) {
const returnVar = returnVariable.find(
pair => pair.value === variable.value
)
if (returnVar && returnVar.key) {
return { type: 'identifier', key: returnVar.key }
}
}
const identifierOnly = localVariables.find(pair => pair.value === null)
if (identifierOnly && identifierOnly.key) {
const targetKey = identifierOnly.key
const returnVar = returnVariable.find(pair =>
pair.value?.startsWith(targetKey)
)
if (returnVar && returnVar.key) {
return { type: 'object', key: returnVar.key, style: 'setup-hook' }
}
}
return null
}
}