/
estree-util-specifiers-to-declarations.js
90 lines (81 loc) · 2.76 KB
/
estree-util-specifiers-to-declarations.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* @typedef {import('estree-jsx').AssignmentProperty} AssignmentProperty
* @typedef {import('estree-jsx').ExportSpecifier} ExportSpecifier
* @typedef {import('estree-jsx').Expression} Expression
* @typedef {import('estree-jsx').Identifier} Identifier
* @typedef {import('estree-jsx').ImportDefaultSpecifier} ImportDefaultSpecifier
* @typedef {import('estree-jsx').ImportNamespaceSpecifier} ImportNamespaceSpecifier
* @typedef {import('estree-jsx').ImportSpecifier} ImportSpecifier
* @typedef {import('estree-jsx').VariableDeclarator} VariableDeclarator
*/
import {create} from './estree-util-create.js'
/**
* @param {Array<ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier>} specifiers
* @param {Expression} init
* @returns {Array<VariableDeclarator>}
*/
export function specifiersToDeclarations(specifiers, init) {
let index = -1
/** @type {Array<VariableDeclarator>} */
const declarations = []
/** @type {Array<ImportSpecifier | ImportDefaultSpecifier | ExportSpecifier>} */
const otherSpecifiers = []
// Can only be one according to JS syntax.
/** @type {ImportNamespaceSpecifier | undefined} */
let importNamespaceSpecifier
while (++index < specifiers.length) {
const specifier = specifiers[index]
if (specifier.type === 'ImportNamespaceSpecifier') {
importNamespaceSpecifier = specifier
} else {
otherSpecifiers.push(specifier)
}
}
if (importNamespaceSpecifier) {
/** @type {VariableDeclarator} */
const declarator = {
type: 'VariableDeclarator',
id: importNamespaceSpecifier.local,
init
}
create(importNamespaceSpecifier, declarator)
declarations.push(declarator)
}
declarations.push({
type: 'VariableDeclarator',
id: {
type: 'ObjectPattern',
properties: otherSpecifiers.map((specifier) => {
/** @type {Identifier} */
let key =
specifier.type === 'ImportSpecifier'
? specifier.imported
: specifier.type === 'ExportSpecifier'
? specifier.exported
: {type: 'Identifier', name: 'default'}
let value = specifier.local
// Switch them around if we’re exporting.
if (specifier.type === 'ExportSpecifier') {
value = key
key = specifier.local
}
/** @type {AssignmentProperty} */
const property = {
type: 'Property',
kind: 'init',
shorthand: key.name === value.name,
method: false,
computed: false,
key,
value
}
create(specifier, property)
return property
})
},
init: importNamespaceSpecifier
? {type: 'Identifier', name: importNamespaceSpecifier.local.name}
: init
})
return declarations
}