diff --git a/packages/router-plugin/src/planners/decisions.ts b/packages/router-plugin/src/planners/decisions.ts index d1d8bc0b95..a47acffaba 100644 --- a/packages/router-plugin/src/planners/decisions.ts +++ b/packages/router-plugin/src/planners/decisions.ts @@ -4,6 +4,7 @@ * once and shared by the `route-split` planner (which applies them) and the * `route-hmr` planner (which hoists only what stays). */ +import { walk } from '@tanstack/router-utils/compiler' import { splitGroupingsSchema } from '../core/config' import { defaultCodeSplitGroupings } from '../core/constants' import { @@ -65,6 +66,7 @@ export type NotSplitReason = | 'ordered-effect' | 'hydrate-writer' | 'env-declared' + | 'this-reference' export interface NotSplit { key: string @@ -455,6 +457,18 @@ function computeSplitPlan( if (isFallbackLiteral(target.value) || isAlreadyLazy(ctx, target.value)) { continue } + if (readsOwnThis(unwrapTs(target.value))) { + // #8688: the router calls a method or function-expression callback as + // a method of the options object; a split chunk's detached call would + // change its `this` (J2.8: informed, never broken) + notSplit.push({ + key, + reason: 'this-reference', + range: target.region, + name: null, + }) + continue + } const shorthandSym = target.shape === 'shorthand' ? identifierSymbol(ctx, target.value) @@ -534,9 +548,47 @@ function describeReason(reason: NotSplitReason): string { return 'it writes a binding captured by a hydration boundary.' case 'env-declared': return 'its value stays in the route module (declared by a top-level call or destructuring, or one with an exported binding it writes); a split chunk could only import it.' + case 'this-reference': + return 'it reads `this`, the route options object it is called on, which a split chunk would not see. Write it as an arrow function or read the route instead.' } } +/** + * Whether a function expression's own body (or parameters) reads `this`, + * not that of a nested function, class or object method inside it (#8688). + * Arrow functions have the module's `this` wherever they evaluate. + */ +function readsOwnThis(fn: Node): boolean { + if (fn.type !== 'FunctionExpression') { + return false + } + let found = false + walk(fn, { + enter: (n, wctx) => { + if (found) { + wctx.stop() + return + } + if (n === fn) { + return + } + if ( + n.type === 'FunctionExpression' || + n.type === 'FunctionDeclaration' || + n.type === 'ClassBody' + ) { + wctx.skip() + return + } + if (n.type === 'ThisExpression') { + found = true + wctx.stop() + } + }, + }) + return found +} + /** The ranges of the module-level units declaring a symbol. */ function declaringRanges(ctx: PlanContext, sym: SymbolId): Array { const { t1 } = ctx diff --git a/packages/router-plugin/tests/code-splitter-imported-options.test.ts b/packages/router-plugin/tests/code-splitter-imported-options.test.ts index ffe20067f7..a595c672c3 100644 --- a/packages/router-plugin/tests/code-splitter-imported-options.test.ts +++ b/packages/router-plugin/tests/code-splitter-imported-options.test.ts @@ -282,6 +282,8 @@ export const Route = createFileRoute('/x')({ 'page-component.tsx': `export const page = Object.freeze(() =>

MARK_X_PAGE

)\n`, }, routeId: '/x', + // route HMR on: the development markers of the route's components + hmr: true, }, ) await expectValidModules(route) diff --git a/packages/router-plugin/tests/code-splitter-route-options.test.ts b/packages/router-plugin/tests/code-splitter-route-options.test.ts index 8fe790c21b..29cc6348d9 100644 --- a/packages/router-plugin/tests/code-splitter-route-options.test.ts +++ b/packages/router-plugin/tests/code-splitter-route-options.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' import { expectNoProblems } from '@tanstack/compiler-test-utils/diagnostic-channel' +import { expectDiagnostic } from '@tanstack/compiler-test-utils/diagnostics' import { expectValidModules, head, holdsMarker, loadRoute } from './route-app' import { readsImport, servedImports } from './served-code' @@ -585,3 +586,55 @@ export const Route = createRootRouteWithContext()({ expect(await route.run(`return render('component')`)).toBe('

root

') }) }) + +// Issue #8688: the router calls a route callback as a method of the options +// object (`options.loader(...)`), so a method or function-expression callback +// may read `this`. A split chunk's `lazyFn` wrapper calls the chunk's export +// detached (`this` undefined): such a callback stays in the route module, +// with a warning naming the file (SPEC J2.8: informed, never broken). An +// arrow function has the module's `this` wherever it evaluates and splits. +describe('route callbacks reading this (#8688)', () => { + it.each([ + [ + 'a method', + `loader() { return this !== undefined && 'loader' in this ? 'MARK_THIS' : 'MARK_OTHER' },`, + ], + [ + 'a function expression', + `loader: function () { return this !== undefined && 'loader' in this ? 'MARK_THIS' : 'MARK_OTHER' },`, + ], + ])('keeps %s in the route module and warns', async (_name, option) => { + const route = await loadRoute( + `${head}export const Route = createFileRoute('/')({ + codeSplitGroupings: [['loader'], ['component']], + ${option} + component: () =>

page

, +}) +`, + ) + await expectValidModules(route) + expect(await route.isLazy('loader')).toBe(false) + expect(await route.isLazy('component')).toBe(true) + expect(await route.run('return options.loader()')).toBe('MARK_THIS') + expectDiagnostic(await route.diagnostics(), { + severity: 'warning', + file: 'route.tsx', + root: route.host.root, + }) + }) + + it('splits a method whose nested functions read their own this', async () => { + const route = await loadRoute( + `${head}export const Route = createFileRoute('/')({ + codeSplitGroupings: [['loader'], ['component']], + loader() { return [1].map(function () { return this === undefined ? 'MARK_OWN' : 'MARK_OTHER' }) }, + component: () =>

page

, +}) +`, + ) + await expectValidModules(route) + expect(await route.isLazy('loader')).toBe(true) + expect(await route.run('return options.loader()')).toEqual(['MARK_OWN']) + expectNoProblems(await route.diagnostics()) + }) +})