Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

compilers.ts

1,389 lines44.6 KB

1import { b, bindingIdentifiers, is, isIdentifierName, walk } from 'yuku-ast'
2import { BindingFlags } from 'yuku-analyzer'
3import {
4 analyzeModule,
5 cloneModuleAst,
6 collectModuleReferences,
7 createIdentifier,
8 expandTransitively,
9 generateModule,
10 keepFilePragmas,
11 linkGeneratedReference,
12 moduleDeclarationGraph,
13 parseStatements,
14 removeUnusedBindings,
15 unwrapExport,
16 unwrapExpression,
17} from '@tanstack/router-utils'
18import { tsrShared, tsrSplit } from '../constants'
19import { createRouteHmrStatement } from '../hmr'
20import { getObjectPropertyKeyName, getUniqueProgramIdentifier } from '../utils'
21import { getFrameworkOptions } from './framework-options'
22import type { Binding, Module } from 'yuku-analyzer'
23import type {
24 Expression,
25 Node,
26 ObjectExpression,
27 ObjectProperty,
28 Program,
29 ProgramStatement,
30 StringLiteral,
31} from '@yuku-toolchain/types'
32import type { AnalyzeModuleOptions } from '@tanstack/router-utils'
33import type {
34 CodeSplitCompilerPlugin,
35 CompileCodeSplitReferenceRouteOptions,
36 ReferenceRouteCompilerPluginContext,
37} from './plugins'
38import type { CodeSplitGroupings, SplitRouteIdentNodes } from '../constants'
39import type { SplitNodeMeta } from './types'
40​
41const splitKeys: Array<SplitRouteIdentNodes> = [
42 'loader',
43 'component',
44 'pendingComponent',
45 'errorComponent',
46 'notFoundComponent',
48const factoryNames = new Set([
49 'createFileRoute',
50 'createRoute',
51 'createRootRoute',
52 'createRootRouteWithContext',
53])
54​
55function splitMeta(key: SplitRouteIdentNodes): SplitNodeMeta {
56 const capitalized = `${key[0]!.toUpperCase()}${key.slice(1)}`
57 return {
58 routeIdent: key,
59 localImporterIdent: `$$split${capitalized}Importer`,
60 splitStrategy: key === 'loader' ? 'lazyFn' : 'lazyRouteComponent',
61 localExporterIdent: `Split${capitalized}`,
62 exporterIdent: key,
63 }
65​
66function bareFilename(filename: string) {
67 return filename.split('?')[0]!
69​
70function splitFilename(filename: string, grouping: Array<string>) {
71 return `${bareFilename(filename)}?${tsrSplit}=${createIdentifier(grouping)}`
73​
74export function addSharedSearchParamToFilename(filename: string) {
75 return `${bareFilename(filename)}?${tsrShared}=1`
77​
78type RouteDefinition = {
79 options: ObjectExpression
80 factory: string
81 /** The factory call that receives the options */
82 call: Node
83 statement: Node
85​
86/** Source syntax and semantic identities are immutable across all output chunks. */
87export type RouteModuleAnalysis = {
88 module: Module
89 routes: Array<RouteDefinition>
90 /**
91 * The route of the module, which route HMR updates: the one the exported
92 * `Route` holds, else the first one.
93 */
94 moduleRoute: RouteDefinition | undefined
95 /**
96 * The module's `Route` is not created by a module-scope factory call, but a
97 * function or block calls a route factory: it creates the module's route,
98 * which can be neither split nor updated by route HMR.
99 */
100 routeCreatedInFunction: boolean
101 graph: ReturnType<typeof moduleDeclarationGraph>
102 /**
103 * Declaration dependencies without the `Route` singleton. Split and shared
104 * modules import `Route` rather than declare it, so reading it never brings
105 * the dependencies of every route option along.
106 */
107 chunkDependencies: Map<Binding, Set<Binding>>
108 exported: Map<Binding, Array<string>>
110​
111type SourceOptions = AnalyzeModuleOptions & { analysis?: RouteModuleAnalysis }
112​
113function resolveExpression(
114 module: Module,
115 node: Node | null | undefined,
116 seen = new Set<Binding>(),
117): Node | undefined {
118 if (!node) {
119 return undefined
120 }
121 if (is.Expression(node)) {
122 node = unwrapExpression(node)
123 }
124 if (is.Identifier(node)) {
125 const binding = module.bindingOf(node)
126 if (!binding || seen.has(binding)) {
127 return undefined
128 }
129 seen.add(binding)
130 let declaration: Node | null | undefined = binding.declarations[0]
131 while (
132 declaration &&
133 !is.VariableDeclarator(declaration) &&
134 !is.Program(declaration)
135 ) {
136 declaration = module.parentOf(declaration)
137 }
138 if (is.VariableDeclarator(declaration) && is.Identifier(declaration.id)) {
139 return resolveExpression(module, declaration.init, seen)
140 }
141 return undefined
142 }
143 return node
145​
146export function analyzeRouteModule(
147 options: AnalyzeModuleOptions,
148): RouteModuleAnalysis {
149 const module = analyzeModule(options)
150 const routes: Array<RouteDefinition> = []
151 const { exports: moduleExports } = module
152 const routeIdentifier = moduleExports.find(
153 (entry) => entry.name === 'Route' && !entry.typeOnly,
154 )?.local?.declarations[0]
155 const routeDeclarator = routeIdentifier && module.parentOf(routeIdentifier)
156 const routeInit = is.VariableDeclarator(routeDeclarator)
157 ? routeDeclarator.init && unwrapExpression(routeDeclarator.init)
158 : undefined
159 let moduleRoute: RouteDefinition | undefined
160 // A factory call inside a function or block, and one at module scope that
161 // initializes the exported `Route`
162 let nestedFactoryCall: Node | undefined
163 let routeFactoryCall: Node | undefined
164 const seen = new Set<Node>()
165 module.walk({
166 CallExpression(node) {
167 const outerCallee = unwrapExpression(node.callee)
168 const callee = unwrapExpression(
169 is.CallExpression(outerCallee) ? outerCallee.callee : outerCallee,
170 )
171 if (!is.Identifier(callee) || !factoryNames.has(callee.name)) {
172 return
173 }
174 // A factory call inside a function or block can close over local
175 // bindings, so its options cannot be split or hoisted to module scope.
176 if (module.scopeOf(node) !== module.rootScope) {
177 nestedFactoryCall ??= node
178 return
179 }
180 let statement: Node = node
181 let parent = module.parentOf(statement)
182 while (parent && !is.Program(parent)) {
183 if (parent === routeDeclarator) {
184 routeFactoryCall ??= node
185 }
186 statement = parent
187 parent = module.parentOf(statement)
188 }
189 const options = resolveExpression(module, node.arguments[0])
190 if (!is.ObjectExpression(options) || seen.has(options)) {
191 return
192 }
193 seen.add(options)
194 const route = { options, factory: callee.name, call: node, statement }
195 routes.push(route)
196 if (node === routeInit) {
197 moduleRoute = route
198 }
199 },
200 })
201 const exported = new Map<Binding, Array<string>>()
202 for (const entry of moduleExports) {
203 if (entry.local && entry.name !== null && !entry.typeOnly) {
204 const names = exported.get(entry.local) ?? []
205 if (!names.includes(entry.name)) {
206 names.push(entry.name)
207 }
208 exported.set(entry.local, names)
209 }
210 }
211 const graph = moduleDeclarationGraph(module)
212 const chunkDependencies = new Map<Binding, Set<Binding>>()
213 for (const [binding, dependencies] of graph.dependencies) {
214 if (binding.name !== 'Route') {
215 chunkDependencies.set(
216 binding,
217 new Set(
218 [...dependencies].filter((dependency) => dependency.name !== 'Route'),
219 ),
220 )
221 }
222 }
223 return {
224 module,
225 routes,
226 moduleRoute: moduleRoute ?? routes[0],
227 routeCreatedInFunction: !!nestedFactoryCall && !routeFactoryCall,
228 graph,
229 chunkDependencies,
230 exported,
231 }
233​
234function sourceAnalysis(options: SourceOptions) {
235 return options.analysis ?? analyzeRouteModule(options)
237​
238function isFallback(value: Expression) {
239 value = unwrapExpression(value)
240 return (
241 (is.Literal(value) &&
242 (value.value === null || typeof value.value === 'boolean')) ||
243 (is.Identifier(value) && value.name === 'undefined')
244 )
246​
247function properties(route: RouteDefinition) {
248 return route.options.properties.filter(
249 (property): property is ObjectProperty => is.Property(property),
250 )
252​
253/** The properties the runtime object keeps: a later duplicate key wins. */
254function runtimeProperties(route: RouteDefinition) {
255 const all = properties(route)
256 return all.filter((property, index) => {
257 const key = getObjectPropertyKeyName(property)
258 return (
259 !key ||
260 !all
261 .slice(index + 1)
262 .some((later) => getObjectPropertyKeyName(later) === key)
263 )
264 })
266​
267function isDataProperty(property: ObjectProperty) {
268 return !property.method && property.kind === 'init'
270​
271/**
272 * The property whose value a split moves into its chunk: the route option
273 * itself, or the `handler` of a loader in object form, since the router reads
274 * the other keys of that object (`staleReloadMode`) from the route options.
275 * Undefined when the option keeps its value in the route module.
276 */
277function splitProperty(key: string, property: ObjectProperty) {
278 const value = unwrapExpression(property.value)
279 if (key !== 'loader' || !is.ObjectExpression(value)) {
280 return property
281 }
282 // The last `handler` wins, unless a spread or a computed key may override it
283 for (let index = value.properties.length - 1; index >= 0; index--) {
284 const candidate = value.properties[index]!
285 if (!is.Property(candidate) || candidate.computed) {
286 return undefined
287 }
288 if (getObjectPropertyKeyName(candidate) === 'handler') {
289 return isDataProperty(candidate) && !isFallback(candidate.value)
290 ? candidate
291 : undefined
292 }
293 }
294 return undefined
296​
297/** Assign each initializer and its dependencies to the chunks that consume it. */
298export function computeSharedBindings(
299 options: SourceOptions & { codeSplitGroupings: CodeSplitGroupings },
300): Set<string> {
301 const analysis = sourceAnalysis(options)
302 const { module, graph, chunkDependencies } = analysis
303 const groupsByBinding = new Map<Binding, Set<number>>()
304 // Only a top-level declaration with a runtime value can move to the shared
305 // module: an ambient one is provided by the environment and erased with types
306 const locals = new Set(
307 [...graph.declarations.keys()].filter(
308 (binding) =>
309 binding.name !== 'Route' &&
310 !binding.has(BindingFlags.Import | BindingFlags.Ambient),
311 ),
312 )
313 for (const route of analysis.routes) {
314 if (route.factory !== 'createFileRoute') {
315 continue
316 }
317 for (const property of properties(route)) {
318 const key = getObjectPropertyKeyName(property)
319 if (!key || key === 'codeSplitGroupings' || isFallback(property.value)) {
320 continue
321 }
322 const group = isDataProperty(property)
323 ? options.codeSplitGroupings.findIndex((keys) =>
324 keys.includes(key as SplitRouteIdentNodes),
325 )
326 : -1
327 const split = group === -1 ? undefined : splitProperty(key, property)
328 // What stays in the route module belongs to the reference group (-1)
329 const parts: Array<[Node, number]> =
330 split === property
331 ? [[property.value, group]]
332 : !split
333 ? [[property.value, -1]]
334 : [
335 [split.value, group],
336 ...(
337 unwrapExpression(property.value) as ObjectExpression
338 ).properties
339 .filter((other) => other !== split)
340 .map((other): [Node, number] => [other, -1]),
341 ]
342 for (const [node, partGroup] of parts) {
343 const references = expandTransitively(
344 collectModuleReferences(module, node),
345 chunkDependencies,
346 )
347 for (const binding of references) {
348 if (!locals.has(binding)) {
349 continue
350 }
351 const groups = groupsByBinding.get(binding) ?? new Set<number>()
352 groups.add(partGroup)
353 groupsByBinding.set(binding, groups)
354 }
355 }
356 }
357 }
358 const shared = new Set<Binding>()
359 for (const [binding, groups] of groupsByBinding) {
360 if (groups.size > 1) {
361 shared.add(binding)
362 }
363 }
364 // A destructured initializer belongs to one module even when its individual
365 // bindings are used in different chunks.
366 for (const siblings of graph.declarationSymbols.values()) {
367 const groups = new Set(
368 [...siblings].flatMap((binding) => [
369 ...(groupsByBinding.get(binding) ?? []),
370 ]),
371 )
372 if (
373 groups.size > 1 ||
374 [...siblings].some((binding) => shared.has(binding))
375 ) {
376 for (const binding of siblings) {
377 if (locals.has(binding)) {
378 shared.add(binding)
379 }
380 }
381 }
382 }
383 const forbidden = new Set(
384 module.rootScope.bindings.filter((binding) => binding.name === 'Route'),
385 )
386 let changed = true
387 while (changed) {
388 changed = false
389 for (const [binding, dependencies] of graph.dependencies) {
390 if (
391 !forbidden.has(binding) &&
392 [...dependencies].some((dependency) => forbidden.has(dependency))
393 ) {
394 forbidden.add(binding)
395 changed = true
396 }
397 }
398 for (const siblings of graph.declarationSymbols.values()) {
399 if ([...siblings].some((binding) => forbidden.has(binding))) {
400 for (const binding of siblings) {
401 if (!forbidden.has(binding)) {
402 forbidden.add(binding)
403 changed = true
404 }
405 }
406 }
407 }
408 }
409 return new Set(
410 [...shared]
411 .filter((binding) => !forbidden.has(binding))
412 .map((binding) => binding.name),
413 )
415​
416function identifier(name: string) {
417 return b.Identifier({ name })
419function reference(name: string, binding?: Binding) {
420 const node = identifier(name)
421 linkGeneratedReference(node, binding ?? name)
422 return node
424function string(value: string) {
425 return b.Literal({ value, raw: JSON.stringify(value) }) as StringLiteral
427function moduleName(name: string) {
428 return isIdentifierName(name) ? identifier(name) : string(name)
430function imports(
431 names: Array<{ local: string; imported: string }>,
432 source: string,
433) {
434 return b.ImportDeclaration({
435 source: string(source),
436 attributes: [],
437 phase: null,
438 specifiers: names.map(({ local, imported }) =>
439 b.ImportSpecifier({
440 local: identifier(local),
441 imported: moduleName(imported),
442 }),
443 ),
444 })
446function exports(
447 names: Array<{ local: string; exported: string; binding?: Binding }>,
448 source: string | null = null,
449) {
450 return b.ExportNamedDeclaration({
451 declaration: null,
452 source: source === null ? null : string(source),
453 attributes: [],
454 specifiers: names.map(({ local, exported, binding }) =>
455 b.ExportSpecifier({
456 local: source === null ? reference(local, binding) : moduleName(local),
457 exported: moduleName(exported),
458 }),
459 ),
460 })
462function variable(name: string, init: Expression) {
463 return b.VariableDeclaration({
464 kind: 'const',
465 declarations: [b.VariableDeclarator({ id: identifier(name), init })],
466 })
468function call(name: string, args: Array<Expression>) {
469 return b.CallExpression({
470 callee: reference(name),
471 arguments: args,
472 optional: false,
473 })
475​
476function prepend(program: Program, ...statements: Array<ProgramStatement>) {
477 const firstStatement = program.body.findIndex(
478 (statement) => !is.Directive(statement),
479 )
480 program.body.splice(
481 firstStatement === -1 ? program.body.length : firstStatement,
482 0,
483 ...statements,
484 )
486​
487/** Print a module emitted for a route file, led by the file's pragmas. */
488function generateRouteModule(
489 analysis: RouteModuleAnalysis,
490 program: Program,
491 filename: string,
492) {
493 keepFilePragmas(analysis.module.ast, program)
494 return generateModule(program, {
495 source: analysis.module.source,
496 filename,
497 })
499​
500function createOutput(analysis: RouteModuleAnalysis) {
501 const { program, originalNodes } = cloneModuleAst(analysis.module)
502 const copies = new Map<Node, Node>()
503 walk(program, {
504 enter(node) {
505 copies.set(originalNodes.get(node)!, node)
506 },
507 })
508 const renameBinding = (node: Node, name: string) => {
509 const original = originalNodes.get(node)
510 const binding = original ? analysis.module.bindingOf(original) : null
511 if (!binding) {
512 return
513 }
514 const declarationExports = new Map<Node, typeof analysis.module.exports>()
515 for (const entry of analysis.module.exports) {
516 if (!entry.local || entry.name === null || entry.typeOnly) {
517 continue
518 }
519 let statement: Node = entry.node
520 let parent = analysis.module.parentOf(statement)
521 while (parent && !is.Program(parent)) {
522 statement = parent
523 parent = analysis.module.parentOf(statement)
524 }
525 if (is.ExportNamedDeclaration(statement) && statement.declaration) {
526 const entries = declarationExports.get(statement) ?? []
527 declarationExports.set(statement, [...entries, entry])
528 }
529 }
530 const aliasedNames = new Set<string>()
531 for (const [statement, entries] of declarationExports) {
532 const copy = copies.get(statement)
533 if (
534 !entries.some((entry) => entry.local === binding) ||
535 !is.ExportNamedDeclaration(copy) ||
536 !copy.declaration
537 ) {
538 continue
539 }
540 const index = program.body.indexOf(copy)
541 if (index !== -1) {
542 const uniqueEntries = entries.filter((entry) => {
543 if (aliasedNames.has(entry.name!)) {
544 return false
545 }
546 aliasedNames.add(entry.name!)
547 return true
548 })
549 const aliases = exports(
550 uniqueEntries.map((entry) => ({
551 local: entry.local!.name,
552 exported: entry.name!,
553 binding: entry.local!,
554 })),
555 )
556 for (const [index, entry] of uniqueEntries.entries()) {
557 originalNodes.set(aliases.specifiers[index]!.local, entry.node)
558 }
559 program.body.splice(
560 index,
561 1,
562 copy.declaration,
563 ...(uniqueEntries.length ? [aliases] : []),
564 )
565 }
566 }
567 walk(program, {
568 enter(candidate, context) {
569 if (!is.Identifier(candidate) && !is.JSXIdentifier(candidate)) {
570 return
571 }
572 const source = originalNodes.get(candidate)
573 if (source && analysis.module.bindingOf(source) === binding) {
574 candidate.name = name
575 const parent = context.parent
576 if (
577 is.Property(parent) &&
578 parent.shorthand &&
579 is.Identifier(parent.key) &&
580 is.Identifier(parent.value) &&
581 parent.key.name !== parent.value.name
582 ) {
583 parent.shorthand = false
584 }
585 }
586 },
587 })
588 }
589 return { program, originalNodes, copies, renameBinding }
591​
592/** Split modules export only their own split values; keep local declarations. */
593function withoutExportSyntax(
594 statement: ProgramStatement,
595): Array<ProgramStatement> {
596 if (is.ExportNamedDeclaration(statement)) {
597 return statement.declaration
598 ? [unwrapExport(statement, statement.declaration)]
599 : []
600 }
601 if (is.ExportDefaultDeclaration(statement)) {
602 const { declaration } = statement
603 // An anonymous default declaration has no binding that could be used here
604 return (is.FunctionDeclaration(declaration) ||
605 is.ClassDeclaration(declaration)) &&
606 declaration.id
607 ? [unwrapExport(statement, declaration)]
608 : []
609 }
610 if (is.ExportAllDeclaration(statement)) {
611 return []
612 }
613 return [statement]
615​
616function removeDeclarations(program: Program, names: Set<string>) {
617 const removedDefaultExports = new Set<Node>()
618 walk(program, {
619 enter(node, context) {
620 if (
621 (is.TSEnumDeclaration(node) ||
622 is.TSModuleDeclaration(node) ||
623 is.TSDeclareFunction(node)) &&
624 node.id &&
625 is.Identifier(node.id) &&
626 names.has(node.id.name) &&
627 (is.Program(context.parent) ||
628 is.ExportNamedDeclaration(context.parent))
629 ) {
630 context.remove()
631 }
632 },
633 VariableDeclarator(node, context) {
634 const container = context.ancestors().at(-2)
635 if (!is.Program(container) && !is.ExportNamedDeclaration(container)) {
636 return
637 }
638 if (bindingIdentifiers(node.id).every((id) => names.has(id.name))) {
639 context.remove()
640 }
641 },
642 FunctionDeclaration(node, context) {
643 if (
644 node.id &&
645 names.has(node.id.name) &&
646 (is.Program(context.parent) ||
647 is.ExportNamedDeclaration(context.parent) ||
648 is.ExportDefaultDeclaration(context.parent))
649 ) {
650 if (is.ExportDefaultDeclaration(context.parent)) {
651 removedDefaultExports.add(context.parent)
652 }
653 context.remove()
654 }
655 },
656 ClassDeclaration(node, context) {
657 if (
658 node.id &&
659 names.has(node.id.name) &&
660 (is.Program(context.parent) ||
661 is.ExportNamedDeclaration(context.parent) ||
662 is.ExportDefaultDeclaration(context.parent))
663 ) {
664 if (is.ExportDefaultDeclaration(context.parent)) {
665 removedDefaultExports.add(context.parent)
666 }
667 context.remove()
668 }
669 },
670 leave(node, context) {
671 if (
672 (is.VariableDeclaration(node) && node.declarations.length === 0) ||
673 (is.ExportNamedDeclaration(node) &&
674 !node.declaration &&
675 node.specifiers.length === 0 &&
676 !node.source) ||
677 removedDefaultExports.has(node)
678 ) {
679 context.remove()
680 }
681 },
682 })
684​
685function addSharedImports(
686 program: Program,
687 shared: Set<string> | undefined,
688 filename: string,
689) {
690 if (shared?.size) {
691 removeDeclarations(program, shared)
692 prepend(
693 program,
694 imports(
695 [...shared].map((name) => ({ local: name, imported: name })),
696 addSharedSearchParamToFilename(filename),
697 ),
698 )
699 }
701​
702export function compileCodeSplitReferenceRoute(
703 options: SourceOptions &
704 CompileCodeSplitReferenceRouteOptions & {
705 compilerPlugins?: Array<CodeSplitCompilerPlugin>
706 /** Reports a problem with the route file to the bundler */
707 warn?: (message: string) => void
708 },
709) {
710 const analysis = sourceAnalysis(options)
711 const output = createOutput(analysis)
712 const { program, originalNodes, copies, renameBinding } = output
713 const framework = getFrameworkOptions(options.targetFramework)
714 const lazyImports = new Map<string, string>()
715 const knownExported = new Set<string>()
716 let modified = false
717 for (const route of analysis.routes) {
718 const routeOptions = copies.get(route.options) as ObjectExpression
719 const insertionStatement = copies.get(route.statement) as ProgramStatement
720 const context: ReferenceRouteCompilerPluginContext = {
721 program,
722 module: analysis.module,
723 originalNodes,
724 renameBinding,
725 routeOptions,
726 createRouteFn: route.factory,
727 opts: options,
728 insertBefore(nodes) {
729 // renameBinding unwraps an `export` declaration it renames
730 const index = program.body.findIndex(
731 (statement) =>
732 statement === insertionStatement ||
733 (is.ExportNamedDeclaration(insertionStatement) &&
734 statement === insertionStatement.declaration),
735 )
736 program.body.splice(index, 0, ...nodes)
737 },
738 }
739 for (const plugin of options.compilerPlugins ?? []) {
740 modified = !!plugin.onRouteOptions?.(context)?.modified || modified
741 }
742 if (options.deleteNodes?.size) {
743 routeOptions.properties = routeOptions.properties.filter((property) => {
744 const remove =
745 is.Property(property) &&
746 options.deleteNodes!.has(getObjectPropertyKeyName(property) ?? '')
747 modified ||= remove
748 return !remove
749 })
750 }
751 if (route.factory === 'createFileRoute') {
752 for (const prop of routeOptions.properties) {
753 if (!is.Property(prop) || !isDataProperty(prop)) {
754 continue
755 }
756 const key = getObjectPropertyKeyName(prop) as SplitRouteIdentNodes
757 const group = options.codeSplitGroupings.find((keys) =>
758 keys.includes(key),
759 )
760 if (!group || !splitKeys.includes(key) || isFallback(prop.value)) {
761 continue
762 }
763 const target = splitProperty(key, prop)
764 if (!target) {
765 continue
766 }
767 const original = originalNodes.get(unwrapExpression(target.value))
768 const binding =
769 original && is.Identifier(original)
770 ? analysis.module.bindingOf(original)
771 : null
772 if (binding && analysis.exported.has(binding)) {
773 knownExported.add(binding.name)
774 continue
775 }
776 const meta = splitMeta(key)
777 let lazy = lazyImports.get(meta.splitStrategy)
778 if (!lazy) {
779 lazy = getUniqueProgramIdentifier(program, meta.splitStrategy).name
780 prepend(
781 program,
782 imports(
783 [{ local: lazy, imported: meta.splitStrategy }],
784 framework.package,
785 ),
786 )
787 lazyImports.set(meta.splitStrategy, lazy)
788 }
789 meta.localImporterIdent = getUniqueProgramIdentifier(
790 program,
791 meta.localImporterIdent,
792 ).name
793 prepend(
794 program,
795 variable(
796 meta.localImporterIdent,
797 b.ArrowFunctionExpression({
798 id: null,
799 generator: false,
800 async: false,
801 expression: true,
802 params: [],
803 body: b.ImportExpression({
804 source: string(splitFilename(options.filename, group)),
805 options: null,
806 phase: null,
807 }),
808 }),
809 ),
810 )
811 let value: Expression | undefined = undefined
812 for (const plugin of options.compilerPlugins ?? []) {
813 value =
814 plugin.onSplitRouteProperty?.({
815 ...context,
816 prop: target,
817 splitNodeMeta: meta,
818 lazyRouteComponentIdent: lazy,
819 }) ?? undefined
820 if (value) {
821 break
822 }
823 }
824 target.value =
825 value ??
826 call(lazy, [
827 reference(meta.localImporterIdent),
828 string(meta.exporterIdent),
829 ])
830 target.shorthand = false
831 modified = true
832 }
833 } else {
834 for (const plugin of options.compilerPlugins ?? []) {
835 modified = !!plugin.onUnsplittableRoute?.(context)?.modified || modified
836 }
837 }
838 if (options.addHmr && route === analysis.moduleRoute) {
839 for (const plugin of options.compilerPlugins ?? []) {
840 plugin.onAddHmr?.(context)
841 }
842 const stableKeys = [
843 ...new Set(
844 (options.compilerPlugins ?? []).flatMap(
845 (plugin) => plugin.getStableRouteOptionKeys?.() ?? [],
846 ),
847 ),
848 ]
849 program.body.push(
850 ...createRouteHmrStatement(stableKeys, {
851 hmrStyle: options.hmrStyle ?? 'vite',
852 targetFramework: options.targetFramework,
853 routeId: options.hmrRouteId,
854 }),
855 )
856 modified = true
857 }
858 }
859 // Reported before an unmodified module returns: an exported option that is
860 // the only one to split leaves the module as is in a production build.
861 const notExportableMessage = knownExported.size
862 ? createNotExportableMessage(options.filename, knownExported)
863 : undefined
864 if (notExportableMessage) {
865 options.warn?.(notExportableMessage)
866 }
867 if (!modified) {
868 return null
869 }
870 if (options.sharedBindings?.size) {
871 program.body = program.body.filter((statement) => {
872 if (
873 is.ExportNamedDeclaration(statement) &&
874 !statement.source &&
875 !statement.declaration
876 ) {
877 statement.specifiers = statement.specifiers.filter(
878 (specifier) =>
879 !is.Identifier(specifier.local) ||
880 !options.sharedBindings!.has(specifier.local.name),
881 )
882 return statement.specifiers.length > 0
883 }
884 return !(
885 is.ExportDefaultDeclaration(statement) &&
886 is.Identifier(statement.declaration) &&
887 options.sharedBindings!.has(statement.declaration.name)
888 )
889 })
890 }
891 addSharedImports(program, options.sharedBindings, options.filename)
892 const sharedExports = [...analysis.exported]
893 .filter(([binding]) => options.sharedBindings?.has(binding.name))
894 .flatMap(([binding, names]) =>
895 names.map((name) => ({ local: binding.name, exported: name })),
896 )
897 if (sharedExports.length) {
898 program.body.push(
899 exports(sharedExports, addSharedSearchParamToFilename(options.filename)),
900 )
901 }
902 removeUnusedBindings(analysis.module, program, originalNodes)
903 // The browser console shows it too, where the terminal output may be unseen
904 if (notExportableMessage && process.env.NODE_ENV !== 'production') {
905 prepend(
906 program,
907 ...parseStatements(
908 `console.warn(${JSON.stringify(notExportableMessage)})`,
909 ),
910 )
911 }
912 return generateRouteModule(analysis, program, options.filename)
914​
915export function compileCodeSplitVirtualRoute(
916 options: SourceOptions & {
917 splitTargets: Array<SplitRouteIdentNodes>
918 filename: string
919 sharedBindings?: Set<string>
920 compilerPlugins?: Array<CodeSplitCompilerPlugin>
921 },
922) {
923 const analysis = sourceAnalysis(options)
924 const { program, originalNodes, copies, renameBinding } =
925 createOutput(analysis)
926 if (!analysis.routes.some((route) => route.factory === 'createFileRoute')) {
927 return generateRouteModule(analysis, program, options.filename)
928 }
929 const generatedExports: Array<ProgramStatement> = []
930 const splitReferences = new Set<Binding>()
931 for (const route of analysis.routes) {
932 if (route.factory !== 'createFileRoute') {
933 continue
934 }
935 for (const property of runtimeProperties(route)) {
936 if (!isDataProperty(property)) {
937 continue
938 }
939 const key = getObjectPropertyKeyName(property) as SplitRouteIdentNodes
940 if (!options.splitTargets.includes(key) || isFallback(property.value)) {
941 continue
942 }
943 const target = splitProperty(key, property)
944 if (!target) {
945 continue
946 }
947 const propertyValue = unwrapExpression(target.value)
948 const binding = is.Identifier(propertyValue)
949 ? analysis.module.bindingOf(propertyValue)
950 : null
951 if (binding && analysis.exported.has(binding)) {
952 continue
953 }
954 for (const reference of collectModuleReferences(
955 analysis.module,
956 propertyValue,
957 )) {
958 splitReferences.add(reference)
959 }
960 const value = copies.get(propertyValue) as Expression
961 const meta = splitMeta(key)
962 if (is.Identifier(value)) {
963 const declaration = binding
964 ? analysis.graph.declarations.get(binding)
965 : undefined
966 const splitNode = declaration ? copies.get(declaration) : undefined
967 if (splitNode) {
968 for (const plugin of options.compilerPlugins ?? []) {
969 plugin.onVirtualRouteSplitNode?.({
970 program,
971 renameBinding,
972 splitNode,
973 splitNodeMeta: meta,
974 })
975 }
976 }
977 generatedExports.push(
978 exports([
979 { local: value.name, exported: key, binding: binding ?? undefined },
980 ]),
981 )
982 } else {
983 const name = getUniqueProgramIdentifier(
984 program,
985 meta.localExporterIdent,
986 ).name
987 generatedExports.push(
988 variable(name, value),
989 exports([{ local: name, exported: key }]),
990 )
991 }
992 }
993 ;(copies.get(route.options) as ObjectExpression).properties = []
994 }
995 const importedExports = exportsImportedBySplitModule(
996 analysis,
997 splitReferences,
998 options.sharedBindings,
999 )
1000 program.body = program.body.flatMap(withoutExportSyntax)
1001 removeDeclarations(
1002 program,
1003 new Set(importedExports.map(([binding]) => binding.name)),
1005 if (importedExports.length) {
1006 prepend(
1007 program,
1008 imports(
1009 importedExports.map(([binding, names]) => ({
1010 local: binding.name,
1011 imported: names[0]!,
1012 })),
1013 bareFilename(options.filename),
1014 ),
1017 addSharedImports(program, options.sharedBindings, options.filename)
1018 program.body.push(...generatedExports)
1019 removeUnusedBindings(analysis.module, program, originalNodes)
1020 stripUnownedExpressions(analysis.module, program, originalNodes)
1021 return generateRouteModule(analysis, program, options.filename)
1023​
1024/**
1025 * User exports, including the Route singleton, that a split module imports from
1026 * the reference module instead of initializing a second copy. Imports keep their
1027 * source, a destructuring that also declares private bindings stays whole, and
1028 * shared bindings come from the shared module. Exported variables are always
1029 * imported so that every module sees one context or store instance. An
1030 * exported function or class that depends on a private binding the split
1031 * module declares itself is declared alongside it, so that both observe one
1032 * module state.
1033 */
1034function exportsImportedBySplitModule(
1035 analysis: RouteModuleAnalysis,
1036 splitReferences: Set<Binding>,
1037 sharedBindings: Set<string> | undefined,
1038) {
1039 const { graph, exported, chunkDependencies } = analysis
1040 const siblingsOf = (binding: Binding) => {
1041 const declaration = graph.declarations.get(binding)
1042 return declaration ? graph.declarationSymbols.get(declaration) : undefined
1044 const isShared = (binding: Binding) => !!sharedBindings?.has(binding.name)
1045 const dependenciesUntil = (stop: (binding: Binding) => boolean) =>
1046 new Map([...chunkDependencies].filter(([binding]) => !stop(binding)))
1047 const privateDependencies = dependenciesUntil(isShared)
1048 const imported = new Set(
1049 [...exported.keys()].filter((binding) => {
1050 const siblings = siblingsOf(binding)
1051 return (
1052 !binding.has(BindingFlags.Import) &&
1053 !isShared(binding) &&
1054 !!siblings &&
1055 [...siblings].every((sibling) => exported.has(sibling))
1057 }),
1059 let changed = true
1060 while (changed) {
1061 changed = false
1062 const declared = expandTransitively(
1063 splitReferences,
1064 dependenciesUntil(
1065 (binding) => imported.has(binding) || isShared(binding),
1066 ),
1068 for (const binding of imported) {
1069 // Every module reads one instance of an exported variable
1070 if (is.VariableDeclarator(graph.declarations.get(binding))) {
1071 continue
1073 const dependencies = expandTransitively(
1074 chunkDependencies.get(binding) ?? new Set<Binding>(),
1075 privateDependencies,
1077 if (
1078 [...dependencies].some(
1079 (dependency) =>
1080 declared.has(dependency) &&
1081 graph.declarations.has(dependency) &&
1082 !dependency.has(BindingFlags.Import) &&
1083 !imported.has(dependency) &&
1084 !isShared(dependency),
1086 ) {
1087 for (const sibling of siblingsOf(binding)!) {
1088 imported.delete(sibling)
1090 changed = true
1094 return [...exported].filter(([binding]) => imported.has(binding))
1096​
1097function stripUnownedExpressions(
1098 module: Module,
1099 program: Program,
1100 originalNodes: WeakMap<Node, Node>,
1101) {
1102 const localNames = new Set<string>()
1103 for (const statement of program.body) {
1104 if (is.VariableDeclaration(statement)) {
1105 for (const declaration of statement.declarations) {
1106 for (const id of bindingIdentifiers(declaration.id)) {
1107 localNames.add(id.name)
1110 } else if (
1111 (is.FunctionDeclaration(statement) || is.ClassDeclaration(statement)) &&
1112 statement.id
1113 ) {
1114 localNames.add(statement.id.name)
1117 program.body = program.body.filter((statement) => {
1118 if (is.Directive(statement) || !is.ExpressionStatement(statement)) {
1119 return true
1121 const original = originalNodes.get(statement)
1122 return (
1123 !!original &&
1124 [...collectModuleReferences(module, original)].some((binding) =>
1125 localNames.has(binding.name),
1128 })
1129 if (program.body.every((statement) => is.Directive(statement))) {
1130 program.body = []
1133​
1134export function compileCodeSplitSharedRoute(
1135 options: SourceOptions & { sharedBindings: Set<string>; filename: string },
1136) {
1137 const analysis = sourceAnalysis(options)
1138 const { program, originalNodes } = createOutput(analysis)
1139 const keep = expandTransitively(
1140 new Set(
1141 analysis.module.rootScope.bindings.filter(
1142 (binding) =>
1143 binding.name !== 'Route' && options.sharedBindings.has(binding.name),
1144 ),
1145 ),
1146 analysis.graph.dependencies,
1148 const names = new Set([...keep].map((binding) => binding.name))
1149 const remove = new Set(
1150 analysis.module.rootScope.bindings
1151 .filter((binding) => !names.has(binding.name))
1152 .map((binding) => binding.name),
1154 program.body = program.body
1155 .flatMap(withoutExportSyntax)
1156 .filter(
1157 (statement) =>
1158 is.Declaration(statement) ||
1159 is.ImportDeclaration(statement) ||
1160 is.Directive(statement),
1162 removeDeclarations(program, remove)
1163 program.body.push(
1164 exports(
1165 [...options.sharedBindings]
1166 .sort()
1167 .map((name) => ({ local: name, exported: name })),
1168 ),
1170 removeUnusedBindings(analysis.module, program, originalNodes)
1171 return generateRouteModule(analysis, program, options.filename)
1173​
1174export function detectCodeSplitGroupingsFromRoute(options: SourceOptions): {
1175 groupings: CodeSplitGroupings | undefined
1176} {
1177 const analysis = sourceAnalysis(options)
1178 for (const route of analysis.routes) {
1179 if (
1180 route.factory !== 'createFileRoute' &&
1181 route.factory !== 'createRoute'
1182 ) {
1183 continue
1185 for (const property of properties(route)) {
1186 if (computedKeyName(property) === 'codeSplitGroupings') {
1187 throw new Error(
1188 `[tanstack-router] The codeSplitGroupings of the route in "${options.filename}" use a computed key, so they cannot be read. Use a static key: codeSplitGroupings: [...]`,
1191 if (getObjectPropertyKeyName(property) !== 'codeSplitGroupings') {
1192 continue
1194 const value = unwrapExpression(property.value)
1195 if (!is.ArrayExpression(value)) {
1196 throw new Error(
1197 'You must provide an array of arrays for the codeSplitGroupings.',
1200 return {
1201 groupings: value.elements.map((element) => {
1202 const group = is.Expression(element)
1203 ? unwrapExpression(element)
1204 : element
1205 if (!is.ArrayExpression(group)) {
1206 throw new Error(
1207 'You must provide arrays with codeSplitGroupings options.',
1210 return group.elements.map((element) => {
1211 const item = is.Expression(element)
1212 ? unwrapExpression(element)
1213 : element
1214 if (!is.Literal(item) || typeof item.value !== 'string') {
1215 throw new Error(
1216 'You must provide a string literal for the codeSplitGroupings',
1219 return item.value as SplitRouteIdentNodes
1220 })
1221 }),
1225 return { groupings: undefined }
1227​
1228function createNotExportableMessage(
1229 filename: string,
1230 identifiers: Set<string>,
1231) {
1232 return [
1233 `[tanstack-router] These exports from "${filename}" will not be code-split and will increase your bundle size:`,
1234 ...[...identifiers].map((name) => `- ${name}`),
1235 'For the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file.',
1236 ].join('\n')
1238​
1239export function createRouteInFunctionMessage(filename: string) {
1240 return `[tanstack-router] The route in "${filename}" is created inside a function. Route factories are not supported, so it will not be code-split or hot-updated. Create it at module level: export const Route = createFileRoute('/path')({ ... })`
1242​
1243/** The string literal of a computed key (`['component']`). */
1244function computedKeyName(property: ObjectProperty) {
1245 return property.computed &&
1246 is.Literal(property.key) &&
1247 typeof property.key.value === 'string'
1248 ? property.key.value
1249 : undefined
1251​
1252/** `file:line:column` of a node of the route module, the column 1-based. */
1253function sourceLocation(analysis: RouteModuleAnalysis, node: Node) {
1254 const lines = analysis.module.source.slice(0, node.start).split(/\r\n?|\n/)
1255 return `${analysis.module.path}:${lines.length}:${lines.at(-1)!.length + 1}`
1257​
1258/**
1259 * The error of a route file that creates more than one file route: their split
1260 * chunks would export the same options, and only one route can be the file's.
1261 */
1262export function createDuplicateFileRouteMessage(
1263 analysis: RouteModuleAnalysis,
1264 filename: string,
1265) {
1266 const fileRoutes = analysis.routes.filter(
1267 (route) => route.factory === 'createFileRoute',
1269 if (fileRoutes.length < 2) {
1270 return undefined
1272 return [
1273 `[tanstack-router] "${filename}" calls createFileRoute ${fileRoutes.length} times:`,
1274 ...fileRoutes.map((route) => `- ${sourceLocation(analysis, route.call)}`),
1275 'A route file creates exactly one file route. Move the other routes into their own route files, or create them with createRoute.',
1276 ].join('\n')
1278​
1279/**
1280 * Route file patterns the code splitter and route HMR leave alone without
1281 * failing: an aliased or namespaced route factory is not recognized, and
1282 * route options it cannot read statically are not split. Options are only
1283 * checked when `codeSplitGroupings` would split them.
1284 */
1285export function getRouteModuleWarnings(
1286 analysis: RouteModuleAnalysis,
1287 filename: string,
1288 codeSplitGroupings: CodeSplitGroupings,
1289): Array<string> {
1290 const { module } = analysis
1291 const warnings: Array<string> = []
1292 for (const entry of module.imports) {
1293 if (entry.typeOnly || !entry.local) {
1294 continue
1296 if (
1297 entry.kind === 'named' &&
1298 entry.name &&
1299 factoryNames.has(entry.name) &&
1300 entry.local.name !== entry.name
1301 ) {
1302 warnings.push(
1303 `[tanstack-router] "${filename}" imports ${entry.name} as ${entry.local.name}. Route factories are only recognized by their own name, so this route will not be code-split or hot-updated. Import it without renaming: import { ${entry.name} } from '${entry.specifier}'`,
1305 continue
1307 if (entry.kind !== 'namespace') {
1308 continue
1310 const members = new Set<string>()
1311 for (const reference of entry.local.references) {
1312 const parent = module.parentOf(reference.node)
1313 if (
1314 is.MemberExpression(parent) &&
1315 parent.object === reference.node &&
1316 !parent.computed &&
1317 is.Identifier(parent.property) &&
1318 factoryNames.has(parent.property.name)
1319 ) {
1320 members.add(parent.property.name)
1323 for (const member of members) {
1324 warnings.push(
1325 `[tanstack-router] "${filename}" calls ${entry.local.name}.${member} through a namespace import. Route factories are only recognized when imported by name, so this route will not be code-split or hot-updated. Import it by name: import { ${member} } from '${entry.specifier}'`,
1329 const splitOptions = new Set<string>(codeSplitGroupings.flat())
1330 for (const route of analysis.routes) {
1331 if (route.factory !== 'createFileRoute') {
1332 continue
1334 const all = route.options.properties
1335 all.forEach((property, index) => {
1336 // A later static key overrides it at runtime
1337 const overridden = (key: string) =>
1338 all
1339 .slice(index + 1)
1340 .some(
1341 (later) =>
1342 is.Property(later) && getObjectPropertyKeyName(later) === key,
1344 if (is.SpreadElement(property)) {
1345 const spread = resolveExpression(module, property.argument)
1346 if (!is.ObjectExpression(spread)) {
1347 return
1349 const keys = spread.properties
1350 .filter((candidate) => is.Property(candidate))
1351 .map((candidate) => getObjectPropertyKeyName(candidate))
1352 .filter(
1353 (key): key is string =>
1354 !!key &&
1355 (key === 'codeSplitGroupings' || splitOptions.has(key)) &&
1356 !overridden(key),
1358 if (keys.length) {
1359 warnings.push(
1360 `[tanstack-router] The route options at ${sourceLocation(analysis, property)} spread ${keys.join(', ')} from another object. Spread options are not read by the code splitter, so ${keys.includes('codeSplitGroupings') ? 'these codeSplitGroupings are ignored and ' : ''}${keys.some((key) => key !== 'codeSplitGroupings') ? 'these options will not be code-split' : 'the default groupings apply'}. Write them in the route options object itself.`,
1363 return
1365 const computed = computedKeyName(property)
1366 if (computed !== undefined) {
1367 if (splitOptions.has(computed) && !overridden(computed)) {
1368 warnings.push(
1369 `[tanstack-router] The "${computed}" route option at ${sourceLocation(analysis, property)} uses a computed key, so it will not be code-split. Use a static key: ${computed}: ...`,
1372 return
1374 const key = getObjectPropertyKeyName(property)
1375 if (
1376 key &&
1377 splitOptions.has(key) &&
1378 !isDataProperty(property) &&
1379 !overridden(key)
1380 ) {
1381 const form = property.method ? 'a method' : `a ${property.kind}ter`
1382 warnings.push(
1383 `[tanstack-router] The "${key}" route option at ${sourceLocation(analysis, property)} is ${form}, so it will not be code-split. Write it as a property: ${key}: () => ...`,
1386 })
1388 return warnings