/
transform.ts
158 lines (135 loc) · 3.83 KB
/
transform.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
import MagicString from 'magic-string'
import { ImportInfo, TransformOptions, Resolver } from '../types'
const excludeRE = [
// imported from other module
/\bimport\s*(.+?)\s*from\b/g,
// defined as function
/\bfunction\s*([\w_$]+?)\s*\(/g,
// defined as local variable
/\b(?:const|let|var)\s+?(\[[\s\S]*?\]|\{[\s\S]*?\}|[\s\S]+?)\s*?[=;\n]/g,
]
const matchRE = /(?<![\w_$]\.)([\w_$]+?)[^\w_${]/g
const importAsRE = /^.*\sas\s+/
const seperatorRE = /[,[\]{}\n]/g
const multilineCommentsRE = /\/\*\s(.|[\r\n])*?\*\//gm
const singlelineCommentsRE = /\/\/\s.*/g
const quotesRE = [
/(["'])((?:\\\1|(?!\1)|.|\r)*?)\1/gm,
/([`])((?:\\\1|(?!\1)|.|\n|\r)*?)\1/gm,
]
function stripeCommentsAndStrings(code: string) {
return code
.replace(multilineCommentsRE, '')
.replace(singlelineCommentsRE, '')
.replace(quotesRE[0], '""')
.replace(/\$\{(.*)\}/g, '` + $1 + `')
.replace(quotesRE[1], '``')
}
export function transform(
code: string,
id: string,
{
imports,
sourceMap,
resolvers,
resolvedImports = {},
ignore = [],
}: TransformOptions,
) {
const striped = stripeCommentsAndStrings(code)
const identifiers = new Set(Array.from(striped.matchAll(matchRE)).map(i => i[1]))
ignore.forEach((i) => {
if (typeof i === 'string') {
identifiers.delete(i)
}
// regex
else {
identifiers.forEach((id) => {
if (id.match(i))
identifiers.delete(id)
})
}
})
// nothing matched, skip
if (!identifiers.size)
return null
// remove those already defined
for (const regex of excludeRE) {
Array.from(striped.matchAll(regex))
.flatMap(i => [
...(i[1]?.split(seperatorRE) || []),
...(i[2]?.split(seperatorRE) || []),
])
.map(i => i.replace(importAsRE, '').trim())
.forEach(i => identifiers.delete(i))
}
// nothing matched, skip
if (!identifiers.size)
return null
const modules: Record<string, ImportInfo[]> = {}
// group by module name
Array.from(identifiers).forEach((name) => {
let info = getOwn(resolvedImports, name) || getOwn(imports, name)
if (!info && resolvers?.length) {
const resolved = firstNonNullResult(resolvers, name)
if (resolved) {
if (typeof resolved === 'string') {
info = {
module: resolved,
name,
from: 'default',
}
}
else {
info = resolved
}
resolvedImports[name] = info
}
}
if (!info || !info.module)
return
if (!modules[info.module])
modules[info.module] = []
modules[info.module].push(info)
})
if (!Object.keys(modules).length)
return
// stringify import
const importStatements = Object.entries(modules)
.map(([moduleName, names]) => {
const imports: string[] = []
const namedImports: string[] = []
names
.forEach(({ name, from }) => {
if (from === '*')
imports.push(`* as ${name}`)
else if (from === 'default')
imports.push(name)
else
namedImports.push(from ? `${from} as ${name}` : name)
})
if (namedImports.length)
imports.push(`{ ${namedImports.join(', ')} }`)
return `import ${imports.join(', ')} from '${moduleName}';`
})
.join('')
const s = new MagicString(code)
s.prependLeft(0, importStatements)
return {
code: s.toString(),
map: sourceMap
? s.generateMap({ source: id, includeContent: true })
: null,
}
}
function firstNonNullResult(array: Resolver[], name: string) {
for (let i = 0; i < array.length; i++) {
const res = array[i](name)
if (res)
return res
}
}
const hasOwnProperty = Object.prototype.hasOwnProperty
function getOwn<T, K extends keyof T>(object: T, key: K) {
return hasOwnProperty.call(object, key) ? object[key] : undefined
}