Open History to see the last commit
1import * as babel from '@babel/core'
2import { isIdentifier, isVariableDeclarator } from '@babel/types'
3import { codeFrameColumns } from '@babel/code-frame'
4import {
5 deadCodeElimination,
6 findReferencedIdentifiers,
7} from 'babel-dead-code-elimination'
8import path from 'pathe'
9import { generateFromAst, parseAst } from '@tanstack/router-utils'
10import type { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils'
11β
12export interface DirectiveFn {
13 nodePath: SupportedFunctionPath
14 functionName: string
15 functionId: string
16 extractedFilename: string
17 filename: string
18 chunkName: string
19}
20β
21export type SupportedFunctionPath =
22 | babel.NodePath<babel.types.FunctionDeclaration>
23 | babel.NodePath<babel.types.FunctionExpression>
24 | babel.NodePath<babel.types.ArrowFunctionExpression>
25β
26export type GenerateFunctionIdFn = (opts: {
27 filename: string
28 functionName: string
29 extractedFilename: string
30}) => string
31β
32export type ReplacerFn = (opts: {
33 fn: string
34 extractedFilename: string
35 filename: string
36 functionId: string
37 isSourceFn: boolean
38}) => string
39β
40// const debug = process.env.TSR_VITE_DEBUG === 'true'
41β
42export type CompileDirectivesOpts = ParseAstOptions & {
43 directive: string
44 getRuntimeCode?: (opts: {
45 directiveFnsById: Record<string, DirectiveFn>
46 }) => string
47 generateFunctionId: GenerateFunctionIdFn
48 replacer: ReplacerFn
49 filename: string
50 root: string
51 isDirectiveSplitParam: boolean
52 directiveSplitParam: string
53}
54β
55export function compileDirectives(opts: CompileDirectivesOpts): {
56 compiledResult: GeneratorResult
57 directiveFnsById: Record<string, DirectiveFn>
58} {
59 const ast = parseAst(opts)
60 const refIdents = findReferencedIdentifiers(ast)
61 const directiveFnsById = findDirectives(ast, {
62 ...opts,
63 directiveSplitParam: opts.directiveSplitParam,
64 isDirectiveSplitParam: opts.isDirectiveSplitParam,
65 })
66β
67 // Add runtime code if there are directives
68 if (Object.keys(directiveFnsById).length > 0) {
69 if (opts.getRuntimeCode) {
70 const runtimeImport = babel.template.statement(
71 opts.getRuntimeCode({ directiveFnsById }),
72 )()
73 ast.program.body.unshift(runtimeImport)
74 }
75 }
76β
77 // If we are in the source file, we need to remove all exports
78 // then make sure that all of our functions are exported under their
79 // directive name
80 if (opts.isDirectiveSplitParam) {
81 safeRemoveExports(ast)
82β
83 // Export a single object with all of the functions
84 // e.g. export { directiveFn1, directiveFn2 }
85 ast.program.body.push(
86 babel.types.exportNamedDeclaration(
87 undefined,
88 Object.values(directiveFnsById).map((fn) =>
89 babel.types.exportSpecifier(
90 babel.types.identifier(fn.functionName),
91 babel.types.identifier(fn.functionName),
92 ),
93 ),
94 ),
95 )
96 }
97β
98 deadCodeElimination(ast, refIdents)
99β
100 const compiledResult = generateFromAst(ast, {
101 sourceMaps: true,
102 sourceFileName: opts.filename,
103 filename: opts.filename,
104 })
105β
106 return {
107 compiledResult,
108 directiveFnsById,
109 }
110}
111β
112function findNearestVariableName(
113 path: babel.NodePath,
114 directive: string,
115): string {
116 let currentPath: babel.NodePath | null = path
117 const nameParts: Array<string> = []
118β
119 while (currentPath) {
120 const name = (() => {
121 // Check for named function expression
122 if (
123 babel.types.isFunctionExpression(currentPath.node) &&
124 currentPath.node.id
125 ) {
126 return currentPath.node.id.name
127 }
128β
129 // Handle method chains
130 if (babel.types.isCallExpression(currentPath.node)) {
131 const current = currentPath.node.callee
132 const chainParts: Array<string> = []
133β
134 // Get the nearest method name (if it's a method call)
135 if (babel.types.isMemberExpression(current)) {
136 if (babel.types.isIdentifier(current.property)) {
137 chainParts.unshift(current.property.name)
138 }
139β
140 // Get the base callee
141 let base = current.object
142 while (!babel.types.isIdentifier(base)) {
143 if (babel.types.isCallExpression(base)) {
144 base = base.callee as babel.types.Expression
145 } else if (babel.types.isMemberExpression(base)) {
146 base = base.object
147 } else {
148 break
149 }
150 }
151 if (babel.types.isIdentifier(base)) {
152 chainParts.unshift(base.name)
153 }
154 } else if (babel.types.isIdentifier(current)) {
155 chainParts.unshift(current.name)
156 }
157β
158 if (chainParts.length > 0) {
159 return chainParts.join('_')
160 }
161 }
162β
163 // Rest of the existing checks...
164 if (babel.types.isFunctionDeclaration(currentPath.node)) {
165 return currentPath.node.id?.name
166 }
167β
168 if (babel.types.isIdentifier(currentPath.node)) {
169 return currentPath.node.name
170 }
171β
172 if (
173 isVariableDeclarator(currentPath.node) &&
174 isIdentifier(currentPath.node.id)
175 ) {
176 return currentPath.node.id.name
177 }
178β
179 if (
180 babel.types.isClassMethod(currentPath.node) ||
181 babel.types.isObjectMethod(currentPath.node)
182 ) {
183 throw new Error(
184 `"${directive}" in ClassMethod or ObjectMethod not supported`,
185 )
186 }
187β
188 return ''
189 })()
190β
191 if (name) {
192 nameParts.unshift(name)
193 }
194β
195 currentPath = currentPath.parentPath
196 }
197β
198 return nameParts.length > 0 ? nameParts.join('_') : 'anonymous'
199}
200β
201function makeIdentifierSafe(identifier: string): string {
202 return identifier
203 .replace(/[^a-zA-Z0-9_$]/g, '_') // Replace unsafe chars with underscore
204 .replace(/^[0-9]/, '_$&') // Prefix leading number with underscore
205 .replace(/^\$/, '_$') // Prefix leading $ with underscore
206 .replace(/_{2,}/g, '_') // Collapse multiple underscores
207 .replace(/^_|_$/g, '') // Trim leading/trailing underscores
208}
209β
210export function findDirectives(
211 ast: babel.types.File,
212 opts: ParseAstOptions & {
213 directive: string
214 replacer?: ReplacerFn
215 generateFunctionId: GenerateFunctionIdFn
216 directiveSplitParam: string
217 filename: string
218 root: string
219 isDirectiveSplitParam: boolean
220 },
221): Record<string, DirectiveFn> {
222 const directiveFnsById: Record<string, DirectiveFn> = {}
223 const functionNameSet: Set<string> = new Set()
224β
225 let programPath: babel.NodePath<babel.types.Program>
226β
227 babel.traverse(ast, {
228 Program(path) {
229 programPath = path
230 },
231 })
232β
233 // Does the file have the directive in the program body?
234 const hasFileDirective = ast.program.directives.some(
235 (directive) => directive.value.value === opts.directive,
236 )
237 const compileDirectiveOpts = {
238 isDirectiveSplitParam: opts.isDirectiveSplitParam,
239 }
240β
241 // If the entire file has a directive, we need to compile all of the functions that are
242 // exported by the file.
243 if (hasFileDirective) {
244 // Find all of the exported functions
245 // They must be either function declarations or const function/anonymous function declarations
246 babel.traverse(ast, {
247 ExportDefaultDeclaration(path) {
248 if (babel.types.isFunctionDeclaration(path.node.declaration)) {
249 compileDirective(
250 path.get('declaration') as SupportedFunctionPath,
251 compileDirectiveOpts,
252 )
253 }
254 },
255 ExportNamedDeclaration(path) {
256 if (babel.types.isFunctionDeclaration(path.node.declaration)) {
257 compileDirective(
258 path.get('declaration') as SupportedFunctionPath,
259 compileDirectiveOpts,
260 )
261 }
262 },
263 ExportDeclaration(path) {
264 if (
265 babel.types.isExportNamedDeclaration(path.node) &&
266 babel.types.isVariableDeclaration(path.node.declaration) &&
267 (babel.types.isFunctionExpression(
268 path.node.declaration.declarations[0]?.init,
269 ) ||
270 babel.types.isArrowFunctionExpression(
271 path.node.declaration.declarations[0]?.init,
272 ))
273 ) {
274 compileDirective(
275 path.get(
276 'declaration.declarations.0.init',
277 ) as SupportedFunctionPath,
278 compileDirectiveOpts,
279 )
280 }
281 },
282 })
283 } else {
284 // Find all directives
285 babel.traverse(ast, {
286 DirectiveLiteral(nodePath) {
287 if (nodePath.node.value === opts.directive) {
288 const directiveFn = nodePath.findParent((p) => p.isFunction())
289β
290 if (!directiveFn) return
291β
292 // Handle class and object methods which are not supported
293 const isClassMethod = directiveFn.isClassMethod()
294 const isObjectMethod = directiveFn.isObjectMethod()
295β
296 if (isClassMethod || isObjectMethod) {
297 throw codeFrameError(
298 opts.code,
299 directiveFn.node.loc,
300 `"${opts.directive}" in ${isClassMethod ? 'class' : isObjectMethod ? 'object method' : ''} not supported`,
301 )
302 }
303β
304 // If the function is inside another block that isn't the program,
305 // Error out. This is not supported.
306 const nearestBlock = directiveFn.findParent(
307 (p) => (p.isBlockStatement() || p.isScopable()) && !p.isProgram(),
308 )
309β
310 if (nearestBlock) {
311 throw codeFrameError(
312 opts.code,
313 nearestBlock.node.loc,
314 `"${opts.directive}" cannot be nested in other blocks or functions`,
315 )
316 }
317β
318 if (
319 !directiveFn.isFunctionDeclaration() &&
320 !directiveFn.isFunctionExpression() &&
321 !(
322 directiveFn.isArrowFunctionExpression() &&
323 babel.types.isBlockStatement(directiveFn.node.body)
324 )
325 ) {
326 throw codeFrameError(
327 opts.code,
328 directiveFn.node.loc,
329 `"${opts.directive}" must be function declarations or function expressions`,
330 )
331 }
332β
333 compileDirective(directiveFn, compileDirectiveOpts)
334 }
335 },
336 })
337 }
338β
339 return directiveFnsById
340β
341 function compileDirective(
342 directiveFn: SupportedFunctionPath,
343 compileDirectiveOpts: { isDirectiveSplitParam: boolean },
344 ) {
345 // Move the function to program level while preserving its position
346 // in the program body
347 const programBody = programPath.node.body
348β
349 // Remove the directive directive from the function body
350 if (
351 babel.types.isFunction(directiveFn.node) &&
352 babel.types.isBlockStatement(directiveFn.node.body)
353 ) {
354 directiveFn.node.body.directives =
355 directiveFn.node.body.directives.filter(
356 (directive) => directive.value.value !== opts.directive,
357 )
358 }
359β
360 // if the directive function is a top-level function, we need to create a const declaration
361 // using the same name as the function and replace the function with the variable declaration
362 // that points to the function
363 if (directiveFn.parentPath.isProgram()) {
364 if (!babel.types.isFunctionDeclaration(directiveFn.node)) {
365 throw new Error('Top level functions must be function declarations')
366 }
367β
368 const index = programBody.indexOf(directiveFn.node)
369β
370 // First get the name of the function
371 const originalFunctionName = directiveFn.node.id!.name
372β
373 // Now turn the function into an anonymous function
374 directiveFn.node.id = null
375β
376 const variableDeclaration = babel.types.variableDeclaration('const', [
377 babel.types.variableDeclarator(
378 babel.types.identifier(originalFunctionName),
379 babel.types.toExpression(directiveFn.node as any),
380 ),
381 ])
382β
383 directiveFn.replaceWith(variableDeclaration)
384β
385 directiveFn = programPath.get(
386 `body.${index}.declarations.0.init`,
387 ) as SupportedFunctionPath
388 }
389β
390 // Find the nearest variable name
391 let functionName = findNearestVariableName(directiveFn, opts.directive)
392β
393 const incrementFunctionNameVersion = (functionName: string) => {
394 const [realReferenceName, count] = functionName.split(/_(\d+)$/)
395 const resolvedCount = Number(count || '0')
396 const suffix = `_${resolvedCount + 1}`
397 return makeIdentifierSafe(realReferenceName!) + suffix
398 }
399β
400 while (functionNameSet.has(functionName)) {
401 functionName = incrementFunctionNameVersion(functionName)
402 }
403β
404 functionNameSet.add(functionName)
405β
406 while (programPath.scope.hasBinding(functionName)) {
407 functionName = incrementFunctionNameVersion(functionName)
408 programPath.scope.crawl()
409 }
410β
411 functionNameSet.add(functionName)
412β
413 const topParent =
414 directiveFn.findParent((p) => !!p.parentPath?.isProgram()) || directiveFn
415β
416 const topParentIndex = programBody.indexOf(topParent.node as any)
417β
418 // If the function has a parent that isn't the program,
419 // we need to replace it with an identifier and
420 // hoist the function to the top level as a const declaration
421 if (directiveFn.parentPath.isProgram()) {
422 throw new Error(
423 'Top level functions should have already been compiled to variable declarations by this point',
424 )
425 }
426 // Then place the function at the top level
427 programBody.splice(
428 topParentIndex,
429 0,
430 babel.types.variableDeclaration('const', [
431 babel.types.variableDeclarator(
432 babel.types.identifier(functionName),
433 babel.types.toExpression(directiveFn.node as any),
434 ),
435 ]),
436 )
437β
438 // If it's an exported named function, we need to swap it with an
439 // export const originalFunctionName = functionName
440 if (
441 (babel.types.isExportNamedDeclaration(directiveFn.parentPath.node) ||
442 (compileDirectiveOpts.isDirectiveSplitParam &&
443 babel.types.isExportDefaultDeclaration(
444 directiveFn.parentPath.node,
445 ))) &&
446 (babel.types.isFunctionDeclaration(directiveFn.node) ||
447 babel.types.isFunctionExpression(directiveFn.node)) &&
448 babel.types.isIdentifier(directiveFn.node.id)
449 ) {
450 const originalFunctionName = directiveFn.node.id.name
451 programBody.splice(
452 topParentIndex + 1,
453 0,
454 babel.types.exportNamedDeclaration(
455 babel.types.variableDeclaration('const', [
456 babel.types.variableDeclarator(
457 babel.types.identifier(originalFunctionName),
458 babel.types.identifier(functionName),
459 ),
460 ]),
461 ),
462 )
463β
464 directiveFn.remove()
465 } else {
466 directiveFn.replaceWith(babel.types.identifier(functionName))
467 }
468β
469 directiveFn = programPath.get(
470 `body.${topParentIndex}.declarations.0.init`,
471 ) as SupportedFunctionPath
472β
473 const [baseFilename, ..._searchParams] = opts.filename.split('?') as [
474 string,
475 ...Array<string>,
476 ]
477 const searchParams = new URLSearchParams(_searchParams.join('&'))
478 searchParams.set(opts.directiveSplitParam, '')
479β
480 const extractedFilename = `${baseFilename}?${searchParams.toString()}`
481β
482 // Relative to have constant functionId regardless of the machine
483 // that we are executing
484 const relativeFilename = path.relative(opts.root, baseFilename)
485 const functionId = opts.generateFunctionId({
486 filename: relativeFilename,
487 functionName,
488 extractedFilename,
489 })
490 // If a replacer is provided, replace the function with the replacer
491 if (opts.replacer) {
492 const replacer = opts.replacer({
493 fn: '$$fn$$',
494 extractedFilename,
495 filename: opts.filename,
496 functionId,
497 isSourceFn: !!opts.directiveSplitParam,
498 })
499β
500 const replacement = babel.template.expression(replacer, {
501 placeholderPattern: false,
502 placeholderWhitelist: new Set(['$$fn$$']),
503 })({
504 ...(replacer.includes('$$fn$$')
505 ? { $$fn$$: babel.types.toExpression(directiveFn.node) }
506 : {}),
507 })
508β
509 directiveFn.replaceWith(replacement)
510 }
511β
512 // Finally register the directive to
513 // our map of directives
514 directiveFnsById[functionId] = {
515 nodePath: directiveFn,
516 functionName,
517 functionId,
518 extractedFilename,
519 filename: opts.filename,
520 chunkName: fileNameToChunkName(opts.root, extractedFilename),
521 }
522 }
523}
524β
525function codeFrameError(
526 code: string,
527 loc:
528 | {
529 start: { line: number; column: number }
530 end: { line: number; column: number }
531 }
532 | undefined
533 | null,
534 message: string,
535) {
536 if (!loc) {
537 return new Error(`${message} at unknown location`)
538 }
539β
540 const frame = codeFrameColumns(
541 code,
542 {
543 start: loc.start,
544 end: loc.end,
545 },
546 {
547 highlightCode: true,
548 message,
549 },
550 )
551β
552 return new Error(frame)
553}
554β
555const safeRemoveExports = (ast: babel.types.File) => {
556 ast.program.body = ast.program.body.flatMap((node) => {
557 if (
558 babel.types.isExportNamedDeclaration(node) ||
559 babel.types.isExportDefaultDeclaration(node)
560 ) {
561 if (
562 babel.types.isFunctionDeclaration(node.declaration) ||
563 babel.types.isClassDeclaration(node.declaration) ||
564 babel.types.isVariableDeclaration(node.declaration)
565 ) {
566 // do not remove export if it is an anonymous function / class, otherwise this would produce a syntax error
567 if (
568 babel.types.isFunctionDeclaration(node.declaration) ||
569 babel.types.isClassDeclaration(node.declaration)
570 ) {
571 if (!node.declaration.id) {
572 return node
573 }
574 }
575 return node.declaration
576 } else if (node.declaration === null) {
577 // remove e.g. `export { RouteComponent as component }`
578 return []
579 }
580 }
581 return node
582 })
583}
584β
585function fileNameToChunkName(root: string, fileName: string) {
586 // Replace anything that can't go into an import statement
587 return fileName.replace(root, '').replace(/[^a-zA-Z0-9_]/g, '_')
588}