This repository has been archived by the owner on Aug 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trextel.plugin.ts
270 lines (234 loc) · 7.92 KB
/
trextel.plugin.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
import { PluginObj } from '@babel/core'
import { NodePath, Visitor } from '@babel/traverse'
import {
CallExpression,
callExpression,
ExportAllDeclaration,
exportAllDeclaration,
ExportNamedDeclaration,
exportNamedDeclaration,
ImportDeclaration,
importDeclaration,
stringLiteral
} from '@babel/types'
import DEFAULTS from '@trext/config/defaults.config'
import { TrextelState } from '@trext/interfaces'
import { TrextNodePath } from '@trext/types'
import { isDirectorySync as isDirectory } from 'path-type'
import resolve from 'resolve-cwd'
/**
* @file Plugins - Trextel
* @module trext/plugins/Trextel
*/
/**
* [Babel plugin][1] that transforms import declarations and call expressions.
*
* @template F - Old file extension name(s)
* @template T - New file extension name(s)
*
* @implements {PluginObj<TrextelState<F, T>>}
*
* [1]: https://github.com/jamiebuilds/babel-handbook/blob/master/translations/en/plugin-handbook.md
*/
class Trextel<F extends string = string, T extends string = string>
implements PluginObj<TrextelState<F, T>>
{
/**
* @readonly
* @instance
* @property {TrextelState<F, T>.key} name - Plugin name
*/
readonly name: TrextelState<F, T>['key'] = 'Trextel'
/**
* Escapes special characters in `value`.
*
* @param {string} [value=''] - String to escape
* @return {string} Escaped string
*/
static escapeSpecials(value: string = ''): string {
return value.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replaceAll('-', '\\x2d')
}
/**
* Retrieves the source code from `nodePath`.
*
* @param {TrextNodePath} nodePath - Current node path
* @return {string | undefined} Declaration, call expression, or `undefined`
*/
static getCode(nodePath: TrextNodePath): string | undefined {
// Init source code value
let code: string | undefined
// Get source code value based on node type
switch (nodePath.node.type) {
case 'CallExpression':
// @ts-expect-error 'value' does not exist on type 'ArgumentPlaceholder'
code = nodePath.node.arguments[0]?.value
break
default:
code = nodePath.node.source?.value
break
}
return code
}
/**
* Transforms call expressions and import statements to use `options.to`.
*
* @template F - Old file extension name(s)
* @template T - New file extension name(s)
*
* @param {TrextNodePath} nodePath - Current node path
* @param {TrextelState<F, T>} state - Plugin state
* @return {void} Nothing when complete
*/
static transform<F extends string = string, T extends string = string>(
nodePath: TrextNodePath,
state: TrextelState<F, T>
): TrextNodePath | void {
// Get node
let node = nodePath.node
// Get source code
let code: string | undefined = Trextel.getCode(nodePath)
// Do nothing is missing source code
if (!code) return
// Merge options
const options = { ...DEFAULTS, ...state.opts }
// Get user options
const { absolute, direxts, from, mandatory, src, to } = options
// Check for absolute import
const absimport = !/^\./.test(code)
// Ignore absolute imports
if (absimport) {
if (absolute === false) return
if (typeof absolute !== 'boolean' && !absolute.test(code)) return
}
// Check for directory entry point
const dirix: boolean = ((): boolean => {
if (absimport) {
// ! Get possible fully specified index files (to account for symlinks)
const indices = direxts.map(ext => `${code}/index${ext}`)
// ! Add partially specified index (to maintain backwards compatibility)
indices.unshift(`${code}/index`)
return indices.map(index => !!resolve.silent(index)).includes(true)
}
return isDirectory(`${src}/${code.match(/\w.+/)?.[0]}`)
})()
// Ignore directory entry points if mandatory file extensions are disabled
if (dirix) {
const { type } = node
const $m = mandatory as Exclude<TrextelState<F, T>, boolean>
if (mandatory === false) return
if ($m['call'] === false && type.startsWith('Call')) return
if ($m['exportAll'] === false && type.startsWith('ExportAll')) return
if ($m['exportNamed'] === false && type.startsWith('ExportNamed')) return
if ($m['import'] === false && type.startsWith('Import')) return
code = `${code}/index`
} else if (absimport && resolve.silent(`${code}/package.json`)) return
// Get output extension
let $to = typeof to === 'function' ? to(nodePath) : to
if (!$to.startsWith('.')) $to = `.${$to}`
// Ignore already converted extensions
if (new RegExp(`\.${Trextel.escapeSpecials($to)}$`).test(code)) return
// Escape special characters in input extension
const $from = new RegExp(`\.${Trextel.escapeSpecials(from)}$|$`)
// Create string literal
const $code = stringLiteral(code.replace($from, $to))
// Transform call expression or import/export declarations
switch (node.type) {
case 'CallExpression':
node = callExpression(node.callee, [$code])
break
case 'ExportAllDeclaration':
node = exportAllDeclaration($code)
break
case 'ExportNamedDeclaration':
node = exportNamedDeclaration(node.declaration, node.specifiers, $code)
break
case 'ImportDeclaration':
node = importDeclaration(node.specifiers, $code)
break
default:
break
}
// Replace node
nodePath.replaceWith(node)
}
/**
* Transforms call expressions to use `options.to`.
*
* @param {NodePath<CallExpression>} nodePath - Current node path
* @param {TrextelState<F, T>} state - Plugin state
* @return {void} Nothing when complete
*/
CallExpression(
nodePath: NodePath<CallExpression>,
state: TrextelState<F, T>
): void {
const { arguments: args, callee } = nodePath.node
// Filter by callee name and type
if (callee.type !== 'Identifier' || callee.name !== 'require') return
// Do nothing for multiple args or if handling a non-string literal
if (args.length !== 1 || args[0]?.type !== 'StringLiteral') return
// Transform node
Trextel.transform(nodePath, state)
}
/**
* Transforms export all (`export *`) declarations to use `options.to`.
*
* @param {NodePath<ExportAllDeclaration>} nodePath - Current node path
* @param {TrextelState<F, T>} state - Plugin state
* @return {void} Nothing when complete
*/
ExportAllDeclaration(
nodePath: NodePath<ExportAllDeclaration>,
state: TrextelState<F, T>
): void {
Trextel.transform(nodePath, state)
}
/**
* Transforms named export (`export foo`) declarations to use `options.to`.
*
* @param {NodePath<ExportNamedDeclaration>} nodePath - Current node path
* @param {TrextelState<F, T>} state - Plugin state
* @return {void} Nothing when complete
*/
ExportNamedDeclaration(
nodePath: NodePath<ExportNamedDeclaration>,
state: TrextelState<F, T>
): void {
Trextel.transform(nodePath, state)
}
/**
* Transforms import declarations to use `options.to`.
*
* @param {NodePath<ImportDeclaration>} nodePath - Current node path
* @param {TrextelState<F, T>} state - Plugin state
* @return {void} Nothing when complete
*/
ImportDeclaration(
nodePath: NodePath<ImportDeclaration>,
state: TrextelState<F, T>
): void {
Trextel.transform(nodePath, state)
}
/**
* Returns the plugin object.
*
* @return {PluginObj<TrextelState<F, T>>} Plugin object
*/
get plugin(): PluginObj<TrextelState<F, T>> {
return { name: this.name, visitor: this.visitor }
}
/**
* Returns the plugin [visitor][1].
*
* @return {Visitor<TrextelState<F, T>>} Plugin visitor
*/
get visitor(): Visitor<TrextelState<F, T>> {
return {
CallExpression: this.CallExpression,
ExportAllDeclaration: this.ExportAllDeclaration,
ExportNamedDeclaration: this.ExportNamedDeclaration,
ImportDeclaration: this.ImportDeclaration
}
}
}
export default Trextel