Open History to see the last commit
1import MagicString from 'magic-string'
2import { is } from 'yuku-ast'
3import { analyzeModule, unwrapExpression } from '@tanstack/router-utils'
4import type * as t from '@yuku-toolchain/types'
5import type { TransformOptions, TransformResult } from './types'
6β
7const routeConstructors = ['createFileRoute', 'createLazyFileRoute'] as const
8β
9type RouteConstructorName = (typeof routeConstructors)[number]
10type SupportedRouteId = t.StringLiteral | t.TemplateLiteral
11type NamedImport = {
12 imported: string
13 local: string
14 importKind?: 'type' | 'typeof' | 'value'
15}
16β
17type ParsedImportDeclaration = {
18 declaration: t.ImportDeclaration
19 defaultImport?: string
20 namespace?: string
21 named: Array<NamedImport>
22 moduleName: string
23 quote: '"' | "'"
24 semicolon: boolean
25}
26β
27type RouteImportAnalysis =
28 | { kind: 'ok' }
29 | {
30 kind: 'rename'
31 imported: t.Identifier
32 local: t.Identifier
33 next: RouteConstructorName
34 }
35 | { kind: 'normalize' }
36β
37type RouteCall = {
38 callee: t.Identifier & { name: RouteConstructorName }
39 routeIdArg: SupportedRouteId
40 optionsArg: t.CallExpression['arguments'][number] | undefined
41}
42β
43type RouteCallAnalysis = {
44 calls: Array<RouteCall>
45 hasUnsupportedRouteId: boolean
46 hasMalformedRouteCall: boolean
47}
48β
49export function transform({
50 ctx,
51 source,
52 filename,
53 node,
54}: TransformOptions): TransformResult {
55 let ast: ReturnType<typeof analyzeModule>
56β
57 try {
58 ast = analyzeModule({ code: source, filename })
59 } catch (error) {
60 return {
61 result: 'error',
62 error,
63 }
64 }
65β
66 const exportedRouteNames = getExportedRouteNames(ast.ast.body)
67β
68 if (exportedRouteNames.size === 0) {
69 return { result: 'no-route-export' }
70 }
71β
72 const {
73 calls: routeCalls,
74 hasUnsupportedRouteId,
75 hasMalformedRouteCall,
76 } = findExportedRouteCalls(ast.ast.body, exportedRouteNames)
77β
78 if (routeCalls.length === 0 && hasMalformedRouteCall) {
79 return {
80 result: 'error',
81 error: new Error(
82 `expected Route export in ${ctx.routeId} to use createFileRoute('/path')({...}) or createLazyFileRoute('/path')({...})`,
83 ),
84 }
85 }
86β
87 if (routeCalls.length === 0 && hasUnsupportedRouteId) {
88 return {
89 result: 'error',
90 error: new Error(
91 `expected route id to be a string literal or plain template literal in ${ctx.routeId}`,
92 ),
93 }
94 }
95β
96 if (routeCalls.length === 0) {
97 return { result: 'not-modified' }
98 }
99β
100 if (routeCalls.length > 1) {
101 return {
102 result: 'error',
103 error: new Error(
104 `expected exactly one createFileRoute/createLazyFileRoute call in ${ctx.routeId}`,
105 ),
106 }
107 }
108β
109 const routeCall = routeCalls[0]!
110 const routeIdQuote = getRouteIdQuote(source, routeCall.routeIdArg)
111β
112 const createFileRouteProps = getCreateFileRouteProps(routeCall.optionsArg)
113 if (createFileRouteProps) {
114 node.createFileRouteProps = createFileRouteProps
115 }
116β
117 const expectedCallee = getExpectedRouteConstructor(ctx.lazy)
118 const expectedRouteId = `${routeIdQuote}${ctx.routeId}${routeIdQuote}`
119 const currentRouteId = source.slice(
120 routeCall.routeIdArg.start,
121 routeCall.routeIdArg.end,
122 )
123 const targetModule = `@tanstack/${ctx.target}-router`
124 const imports = parseTargetImports(ast.ast.body, source, targetModule)
125β
126 const s = new MagicString(source)
127 let modified = false
128β
129 if (routeCall.callee.name !== expectedCallee) {
130 s.update(routeCall.callee.start, routeCall.callee.end, expectedCallee)
131 modified = true
132 }
133β
134 if (currentRouteId !== expectedRouteId) {
135 s.update(
136 routeCall.routeIdArg.start,
137 routeCall.routeIdArg.end,
138 expectedRouteId,
139 )
140 modified = true
141 }
142β
143 if (
144 updateRouteImports({
145 imports,
146 source,
147 s,
148 targetModule,
149 required: expectedCallee,
150 lineEnding: getLineEnding(source),
151 })
152 ) {
153 modified = true
154 }
155β
156 if (!modified) {
157 return { result: 'not-modified' }
158 }
159β
160 return {
161 result: 'modified',
162 output: s.toString(),
163 }
164}
165β
166function getExportedRouteNames(body: t.Program['body']) {
167 const exportedRouteNames = new Set<string>()
168β
169 for (const statement of body) {
170 if (!is.ExportNamedDeclaration(statement) || statement.source) {
171 continue
172 }
173β
174 if (is.VariableDeclaration(statement.declaration)) {
175 for (const declarator of statement.declaration.declarations) {
176 if (is.Identifier(declarator.id) && declarator.id.name === 'Route') {
177 exportedRouteNames.add('Route')
178 }
179 }
180 }
181β
182 for (const specifier of statement.specifiers) {
183 if (
184 !is.ExportSpecifier(specifier) ||
185 getExportedName(specifier.exported) !== 'Route'
186 ) {
187 continue
188 }
189β
190 const localName = getLocalBindingName(specifier.local)
191 if (localName) {
192 exportedRouteNames.add(localName)
193 }
194 }
195 }
196β
197 return exportedRouteNames
198}
199β
200function findExportedRouteCalls(
201 body: t.Program['body'],
202 exportedRouteNames: Set<string>,
203): RouteCallAnalysis {
204 const calls: Array<RouteCall> = []
205 let hasUnsupportedRouteId = false
206 let hasMalformedRouteCall = false
207β
208 for (const statement of body) {
209 const declaration = getVariableDeclaration(statement)
210 if (!declaration) {
211 continue
212 }
213β
214 for (const declarator of declaration.declarations) {
215 if (
216 !is.Identifier(declarator.id) ||
217 !exportedRouteNames.has(declarator.id.name)
218 ) {
219 continue
220 }
221β
222 const init = getRouteConstructorInit(declarator.init)
223 if (!init) {
224 if (isDirectRouteConstructorCall(declarator.init)) {
225 hasMalformedRouteCall = true
226 }
227 continue
228 }
229β
230 const routeIdArg = unwrapNode(init.innerCall.arguments[0])
231 if (isSupportedRouteId(routeIdArg)) {
232 calls.push({
233 callee: init.callee,
234 routeIdArg,
235 optionsArg: unwrapNode(init.outerCall.arguments[0]),
236 })
237 } else {
238 hasUnsupportedRouteId = true
239 }
240 }
241 }
242β
243 return { calls, hasUnsupportedRouteId, hasMalformedRouteCall }
244}
245β
246function getVariableDeclaration(statement: t.ProgramStatement) {
247 const declaration = is.ExportNamedDeclaration(statement)
248 ? statement.declaration
249 : statement
250β
251 return is.VariableDeclaration(declaration) ? declaration : null
252}
253β
254function getExportedName(node: t.Identifier | t.StringLiteral) {
255 return is.Identifier(node) ? node.name : node.value
256}
257β
258function getLocalBindingName(node: t.Identifier | t.StringLiteral) {
259 return is.Identifier(node) ? node.name : null
260}
261β
262function getRouteConstructorInit(expression: t.Expression | null | undefined) {
263 if (!expression) {
264 return null
265 }
266 expression = unwrapExpression(expression)
267 if (!is.CallExpression(expression)) {
268 return null
269 }
270 const innerCall = unwrapNode(expression.callee)
271 if (!is.CallExpression(innerCall)) {
272 return null
273 }
274β
275 const callee = unwrapNode(innerCall.callee)
276 if (!is.Identifier(callee) || !isRouteConstructor(callee)) {
277 return null
278 }
279β
280 return {
281 callee,
282 outerCall: expression,
283 innerCall,
284 }
285}
286β
287function isDirectRouteConstructorCall(
288 expression: t.Expression | null | undefined,
289) {
290 expression = expression ? unwrapExpression(expression) : expression
291 if (!expression || !is.CallExpression(expression)) {
292 return false
293 }
294 const callee = unwrapNode(expression.callee)
295 return is.Identifier(callee) && isRouteConstructor(callee)
296}
297β
298/**
299 * Parentheses and TypeScript-only wrappers do not change the wrapped value, so
300 * route call parts are read through them.
301 */
302function unwrapNode<TNode extends t.Node | undefined>(
303 node: TNode,
304): TNode | t.Expression {
305 return node && is.Expression(node) ? unwrapExpression(node) : node
306}
307β
308function isRouteConstructor(callee: t.Identifier): callee is t.Identifier & {
309 name: RouteConstructorName
310} {
311 return routeConstructors.includes(callee.name as RouteConstructorName)
312}
313β
314function isSupportedRouteId(
315 arg: t.CallExpression['arguments'][number] | undefined,
316): arg is SupportedRouteId {
317 return (
318 !!arg &&
319 (is.StringLiteral(arg) ||
320 (is.TemplateLiteral(arg) && arg.expressions.length === 0))
321 )
322}
323β
324function getRouteIdQuote(
325 source: string,
326 arg: SupportedRouteId,
327): '"' | "'" | '`' {
328 const raw = source.slice(arg.start, arg.end)
329β
330 if (raw.startsWith("'")) {
331 return "'"
332 }
333 if (raw.startsWith('"')) {
334 return '"'
335 }
336 return '`'
337}
338β
339function getCreateFileRouteProps(
340 arg: t.CallExpression['arguments'][number] | undefined,
341) {
342 if (!arg || !is.ObjectExpression(arg)) {
343 return undefined
344 }
345β
346 const props = new Set<string>()
347β
348 for (const property of arg.properties) {
349 if (!is.Property(property) || property.computed) {
350 continue
351 }
352β
353 if (is.Identifier(property.key)) {
354 props.add(property.key.name)
355 continue
356 }
357β
358 if (is.StringLiteral(property.key)) {
359 props.add(property.key.value)
360 }
361 }
362β
363 return props
364}
365β
366function parseTargetImports(
367 body: t.Program['body'],
368 source: string,
369 targetModule: string,
370) {
371 const imports: Array<ParsedImportDeclaration> = []
372β
373 for (const statement of body) {
374 if (
375 !is.ImportDeclaration(statement) ||
376 statement.importKind === 'type' ||
377 statement.source.value !== targetModule
378 ) {
379 continue
380 }
381β
382 const rawSource = source.slice(statement.source.start, statement.source.end)
383 const importStatement = source.slice(statement.start, statement.end)
384β
385 imports.push({
386 declaration: statement,
387 defaultImport: statement.specifiers.find((specifier) =>
388 is.ImportDefaultSpecifier(specifier),
389 )?.local.name,
390 namespace: statement.specifiers.find((specifier) =>
391 is.ImportNamespaceSpecifier(specifier),
392 )?.local.name,
393 named: statement.specifiers
394 .filter((specifier): specifier is t.ImportSpecifier =>
395 is.ImportSpecifier(specifier),
396 )
397 .map((specifier) => ({
398 imported: is.Identifier(specifier.imported)
399 ? specifier.imported.name
400 : specifier.imported.value,
401 local: specifier.local.name,
402 importKind: specifier.importKind ?? undefined,
403 })),
404 moduleName: statement.source.value,
405 quote: rawSource[0] as '"' | "'",
406 semicolon: importStatement.trimEnd().endsWith(';'),
407 })
408 }
409β
410 return imports
411}
412β
413function updateRouteImports({
414 imports,
415 source,
416 s,
417 targetModule,
418 required,
419 lineEnding,
420}: {
421 imports: Array<ParsedImportDeclaration>
422 source: string
423 s: MagicString
424 targetModule: string
425 required: RouteConstructorName
426 lineEnding: '\r\n' | '\n' | '\r'
427}) {
428 const analysis = analyzeRouteImports(imports, required)
429β
430 if (analysis.kind === 'ok') {
431 return false
432 }
433β
434 if (analysis.kind === 'rename') {
435 s.update(analysis.imported.start, analysis.imported.end, analysis.next)
436 s.update(analysis.local.start, analysis.local.end, analysis.next)
437 return true
438 }
439β
440 return normalizeRouteImports({
441 imports,
442 source,
443 s,
444 targetModule,
445 required,
446 lineEnding,
447 })
448}
449β
450function analyzeRouteImports(
451 imports: Array<ParsedImportDeclaration>,
452 required: RouteConstructorName,
453): RouteImportAnalysis {
454 const opposite = getOtherRouteConstructor(required)
455 let requiredCount = 0
456 let oppositeCount = 0
457 let renameCandidate:
458 | {
459 imported: t.Identifier
460 local: t.Identifier
461 next: RouteConstructorName
462 }
463 | undefined
464β
465 for (const declaration of imports) {
466 for (const specifier of declaration.declaration.specifiers) {
467 if (!is.ImportSpecifier(specifier)) {
468 continue
469 }
470β
471 const imported = specifier.imported
472 if (!is.Identifier(imported)) {
473 return { kind: 'normalize' }
474 }
475β
476 if (!isRouteConstructorName(imported.name)) {
477 continue
478 }
479β
480 if (specifier.local.name !== imported.name) {
481 return { kind: 'normalize' }
482 }
483β
484 if (imported.name === required) {
485 requiredCount++
486 continue
487 }
488β
489 if (imported.name === opposite) {
490 oppositeCount++
491 renameCandidate = {
492 imported,
493 local: specifier.local,
494 next: required,
495 }
496 }
497 }
498 }
499β
500 if (requiredCount === 1 && oppositeCount === 0) {
501 return { kind: 'ok' }
502 }
503β
504 if (requiredCount === 0 && oppositeCount === 1 && renameCandidate) {
505 return {
506 kind: 'rename',
507 ...renameCandidate,
508 }
509 }
510β
511 return { kind: 'normalize' }
512}
513β
514function normalizeRouteImports({
515 imports,
516 source,
517 s,
518 targetModule,
519 required,
520 lineEnding,
521}: {
522 imports: Array<ParsedImportDeclaration>
523 source: string
524 s: MagicString
525 targetModule: string
526 required: RouteConstructorName
527 lineEnding: '\r\n' | '\n' | '\r'
528}) {
529 const owner =
530 imports.find((declaration) =>
531 hasNamedImport(declaration.named, required),
532 ) ?? imports.find((declaration) => !declaration.namespace)
533β
534 let modified = false
535β
536 for (const declaration of imports) {
537 const named = normalizeNamedImports({
538 named: declaration.named,
539 required,
540 isOwner: declaration === owner,
541 })
542β
543 if (sameNamedImports(declaration.named, named)) {
544 continue
545 }
546β
547 const replacement = renderImportDeclaration({
548 ...declaration,
549 named,
550 })
551β
552 if (replacement === null) {
553 s.remove(
554 declaration.declaration.start,
555 getRemovalEnd(source, declaration.declaration.end),
556 )
557 modified = true
558 continue
559 }
560β
561 s.update(
562 declaration.declaration.start,
563 declaration.declaration.end,
564 replacement,
565 )
566 modified = true
567 }
568β
569 if (!owner) {
570 const quote = imports[0]?.quote ?? "'"
571 const semicolon = imports[0]?.semicolon ?? false
572 s.prepend(
573 `import { ${required} } from ${quote}${targetModule}${quote}${semicolon ? ';' : ''}${lineEnding}`,
574 )
575 modified = true
576 }
577β
578 return modified
579}
580β
581function normalizeNamedImports({
582 named,
583 required,
584 isOwner,
585}: {
586 named: Array<NamedImport>
587 required: RouteConstructorName
588 isOwner: boolean
589}) {
590 const banned = getOtherRouteConstructor(required)
591 const nextNamed: Array<NamedImport> = []
592 const seen = new Set<string>()
593β
594 for (const specifier of named) {
595 if (specifier.imported === banned) {
596 continue
597 }
598β
599 if (
600 specifier.local === required &&
601 (specifier.imported !== required || !isOwner)
602 ) {
603 continue
604 }
605β
606 const key = `${specifier.importKind ?? 'value'}:${specifier.imported}:${specifier.local}`
607 if (seen.has(key)) {
608 continue
609 }
610β
611 seen.add(key)
612 nextNamed.push(specifier)
613 }
614β
615 if (isOwner && !hasNamedImport(nextNamed, required)) {
616 nextNamed.push({ imported: required, local: required })
617 }
618β
619 return nextNamed
620}
621β
622function getExpectedRouteConstructor(lazy: boolean): RouteConstructorName {
623 return lazy ? 'createLazyFileRoute' : 'createFileRoute'
624}
625β
626function getOtherRouteConstructor(
627 constructor: RouteConstructorName,
628): RouteConstructorName {
629 return constructor === 'createFileRoute'
630 ? 'createLazyFileRoute'
631 : 'createFileRoute'
632}
633β
634function hasNamedImport(
635 named: Array<NamedImport>,
636 required: RouteConstructorName,
637) {
638 return named.some(
639 (specifier) =>
640 specifier.imported === required &&
641 specifier.local === required &&
642 specifier.importKind !== 'type',
643 )
644}
645β
646function sameNamedImports(left: Array<NamedImport>, right: Array<NamedImport>) {
647 return (
648 left.length === right.length &&
649 left.every(
650 (specifier, index) =>
651 specifier.imported === right[index]!.imported &&
652 specifier.local === right[index]!.local &&
653 specifier.importKind === right[index]!.importKind,
654 )
655 )
656}
657β
658function isRouteConstructorName(value: string): value is RouteConstructorName {
659 return routeConstructors.includes(value as RouteConstructorName)
660}
661β
662function renderImportDeclaration(importDeclaration: {
663 defaultImport?: string
664 namespace?: string
665 named: Array<NamedImport>
666 moduleName: string
667 quote: '"' | "'"
668 semicolon: boolean
669}) {
670 const parts: Array<string> = []
671β
672 if (importDeclaration.defaultImport) {
673 parts.push(importDeclaration.defaultImport)
674 }
675β
676 if (importDeclaration.namespace) {
677 parts.push(`* as ${importDeclaration.namespace}`)
678 }
679β
680 if (importDeclaration.named.length > 0) {
681 parts.push(
682 `{ ${importDeclaration.named
683 .map(
684 (specifier) =>
685 `${specifier.importKind === 'type' ? 'type ' : ''}${specifier.imported === specifier.local ? specifier.imported : `${specifier.imported} as ${specifier.local}`}`,
686 )
687 .join(', ')} }`,
688 )
689 }
690β
691 if (parts.length === 0) {
692 return null
693 }
694β
695 return `import ${parts.join(', ')} from ${importDeclaration.quote}${importDeclaration.moduleName}${importDeclaration.quote}${importDeclaration.semicolon ? ';' : ''}`
696}
697β
698function getLineEnding(source: string): '\r\n' | '\n' | '\r' {
699 if (source.includes('\r\n')) {
700 return '\r\n'
701 }
702β
703 if (source.includes('\n')) {
704 return '\n'
705 }
706β
707 if (source.includes('\r')) {
708 return '\r'
709 }
710β
711 return '\n'
712}
713β
714function getRemovalEnd(source: string, end: number) {
715 let pos = end
716 while (pos < source.length && (source[pos] === ' ' || source[pos] === '\t')) {
717 pos++
718 }
719β
720 if (source[pos] === '\r' && source[pos + 1] === '\n') {
721 return pos + 2
722 }
723β
724 if (source[pos] === '\n' || source[pos] === '\r') {
725 return pos + 1
726 }
727β
728 return end
729}