-
-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathdata-functions-augment.ts
More file actions
244 lines (225 loc) · 7.97 KB
/
data-functions-augment.ts
File metadata and controls
244 lines (225 loc) · 7.97 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
import type { types as Babel } from "@babel/core"
import type { ParseResult } from "@babel/parser"
import type { NodePath } from "@babel/traverse"
import { gen, parse, t, trav } from "./babel"
const SERVER_COMPONENT_EXPORTS = ["loader", "action"]
const CLIENT_COMPONENT_EXPORTS = ["clientLoader", "clientAction"]
const ALL_EXPORTS = [...SERVER_COMPONENT_EXPORTS, ...CLIENT_COMPONENT_EXPORTS]
const transform = (ast: ParseResult<Babel.File>, routeId: string) => {
const serverHocs: Array<[string, Babel.Identifier]> = []
const clientHocs: Array<[string, Babel.Identifier]> = []
const imports: Array<[string, Babel.Identifier]> = []
function getServerHocId(path: NodePath, hocName: string) {
const uid = path.scope.generateUidIdentifier(hocName)
const hasHoc = serverHocs.find(([name]) => name === hocName)
if (hasHoc) {
return uid
}
serverHocs.push([hocName, uid])
return uid
}
function getClientHocId(path: NodePath, hocName: string) {
const uid = path.scope.generateUidIdentifier(hocName)
const hasHoc = clientHocs.find(([name]) => name === hocName)
if (hasHoc) {
return uid
}
clientHocs.push([hocName, uid])
return uid
}
function uppercaseFirstLetter(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
const transformations: Array<() => void> = []
const importDeclarations: Babel.ImportDeclaration[] = []
trav(ast, {
ImportDeclaration(path) {
const specifiers = path.node.specifiers
for (const specifier of specifiers) {
if (!t.isImportSpecifier(specifier) || !t.isIdentifier(specifier.imported)) {
continue
}
const name = specifier.imported.name
if (!ALL_EXPORTS.includes(name)) {
continue
}
const isReimported = specifier.local.name !== name
const uniqueName = isReimported ? specifier.local : path.scope.generateUidIdentifier(name)
imports.push([name, uniqueName])
specifier.local = uniqueName
// Replace the import specifier with a new one
if (!isReimported) {
path.scope.rename(name, uniqueName.name)
}
}
},
ExportDeclaration(path) {
if (path.isExportNamedDeclaration()) {
const decl = path.get("declaration")
if (decl.isVariableDeclaration()) {
for (const varDeclarator of decl.get("declarations")) {
const id = varDeclarator.get("id")
const init = varDeclarator.get("init")
const expr = init.node
if (!expr) return
if (!id.isIdentifier()) return
const { name } = id.node
if (!ALL_EXPORTS.includes(name)) return
const uid = CLIENT_COMPONENT_EXPORTS.includes(name)
? getClientHocId(path, `with${uppercaseFirstLetter(name)}Wrapper`)
: getServerHocId(path, `with${uppercaseFirstLetter(name)}Wrapper`)
init.replaceWith(t.callExpression(uid, [expr, t.stringLiteral(routeId)]))
}
return
}
if (decl.isFunctionDeclaration()) {
const { id } = decl.node
if (!id) return
const { name } = id
if (!ALL_EXPORTS.includes(name)) return
const uid = CLIENT_COMPONENT_EXPORTS.includes(name)
? getClientHocId(path, `with${uppercaseFirstLetter(name)}Wrapper`)
: getServerHocId(path, `with${uppercaseFirstLetter(name)}Wrapper`)
decl.replaceWith(
t.variableDeclaration("const", [
t.variableDeclarator(
t.identifier(name),
t.callExpression(uid, [toFunctionExpression(decl.node), t.stringLiteral(routeId)])
),
])
)
}
}
},
ExportNamedDeclaration(path) {
const specifiers = path.node.specifiers
for (const specifier of specifiers) {
if (!(t.isExportSpecifier(specifier) && t.isIdentifier(specifier.exported))) {
return
}
const name = specifier.exported.name
if (!ALL_EXPORTS.includes(name)) {
return
}
const uid = CLIENT_COMPONENT_EXPORTS.includes(name)
? getClientHocId(path, `with${uppercaseFirstLetter(name)}Wrapper`)
: getServerHocId(path, `with${uppercaseFirstLetter(name)}Wrapper`)
const binding = path.scope.getBinding(name)
if (path.node.source) {
// Special condition: export { loader, action } from "./path"
const source = path.node.source.value
importDeclarations.push(
t.importDeclaration(
[t.importSpecifier(t.identifier(`_${name}`), t.identifier(name))],
t.stringLiteral(source)
)
)
transformations.push(() => {
path.insertBefore(
t.exportNamedDeclaration(
t.variableDeclaration("const", [
t.variableDeclarator(
t.identifier(name),
t.callExpression(uid, [t.identifier(`_${name}`), t.stringLiteral(routeId)])
),
])
)
)
})
// Remove the specifier from the exports and add a manual export
transformations.push(() => {
const remainingSpecifiers = path.node.specifiers.filter(
(exportSpecifier) => !(t.isIdentifier(exportSpecifier.exported) && exportSpecifier.exported.name === name)
)
path.replaceWith(t.exportNamedDeclaration(null, remainingSpecifiers, path.node.source))
const newRemainingSpecifiers = path.node.specifiers.length
if (newRemainingSpecifiers === 0) {
path.remove()
}
})
} else if (binding?.path.isFunctionDeclaration()) {
// Replace the function declaration with a wrapped version
binding.path.replaceWith(
t.variableDeclaration("const", [
t.variableDeclarator(
t.identifier(name),
t.callExpression(uid, [toFunctionExpression(binding.path.node), t.stringLiteral(routeId)])
),
])
)
} else if (binding?.path.isVariableDeclarator()) {
// Wrap the variable declarator's initializer
const init = binding.path.get("init")
if (init.node) {
init.replaceWith(t.callExpression(uid, [init.node, t.stringLiteral(routeId)]))
}
} else {
transformations.push(() => {
const existingImport = imports.find(([existingName]) => existingName === name)
const uniqueName = existingImport?.[1].name ?? path.scope.generateUidIdentifier(name).name
const remainingSpecifiers = path.node.specifiers.filter(
(exportSpecifier) => !(t.isIdentifier(exportSpecifier.exported) && exportSpecifier.exported.name === name)
)
path.replaceWith(t.exportNamedDeclaration(null, remainingSpecifiers, path.node.source))
// Insert the wrapped export after the modified export statement
path.insertAfter(
t.exportNamedDeclaration(
t.variableDeclaration("const", [
t.variableDeclarator(
t.identifier(name),
t.callExpression(uid, [t.identifier(uniqueName), t.stringLiteral(routeId)])
),
]),
[]
)
)
const newRemainingSpecifiers = path.node.specifiers.length
if (newRemainingSpecifiers === 0) {
path.remove()
}
})
}
}
},
})
for (const transformation of transformations) {
transformation()
}
if (importDeclarations.length > 0) {
ast.program.body.unshift(...importDeclarations)
}
if (serverHocs.length > 0) {
ast.program.body.unshift(
t.importDeclaration(
serverHocs.map(([name, identifier]) => t.importSpecifier(identifier, t.identifier(name))),
t.stringLiteral("react-router-devtools/server")
)
)
}
if (clientHocs.length > 0) {
ast.program.body.unshift(
t.importDeclaration(
clientHocs.map(([name, identifier]) => t.importSpecifier(identifier, t.identifier(name))),
t.stringLiteral("react-router-devtools/client")
)
)
}
const didTransform = clientHocs.length > 0 || serverHocs.length > 0
return didTransform
}
function toFunctionExpression(decl: Babel.FunctionDeclaration) {
return t.functionExpression(decl.id, decl.params, decl.body, decl.generator, decl.async)
}
export function augmentDataFetchingFunctions(code: string, routeId: string, id: string) {
const [filePath] = id.split("?")
try {
const ast = parse(code, { sourceType: "module" })
const didTransform = transform(ast, routeId)
if (!didTransform) {
return { code }
}
return gen(ast, { sourceMaps: true, filename: id, sourceFileName: filePath })
} catch (e) {
return { code }
}
}