@tanstack/router-plugin 1.167.12 → 1.167.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/core/code-splitter/compilers.cjs +5 -4
- package/dist/cjs/core/code-splitter/compilers.cjs.map +1 -1
- package/dist/cjs/core/code-splitter/compilers.d.cts +2 -10
- package/dist/cjs/core/code-splitter/plugins/framework-plugins.cjs +2 -2
- package/dist/cjs/core/code-splitter/plugins/framework-plugins.cjs.map +1 -1
- package/dist/cjs/core/code-splitter/plugins/framework-plugins.d.cts +1 -0
- package/dist/cjs/core/code-splitter/plugins/react-refresh-ignored-route-exports.cjs +12 -6
- package/dist/cjs/core/code-splitter/plugins/react-refresh-ignored-route-exports.cjs.map +1 -1
- package/dist/cjs/core/code-splitter/plugins/react-refresh-ignored-route-exports.d.cts +3 -1
- package/dist/cjs/core/code-splitter/plugins/react-stable-hmr-split-route-components.cjs +12 -7
- package/dist/cjs/core/code-splitter/plugins/react-stable-hmr-split-route-components.cjs.map +1 -1
- package/dist/cjs/core/code-splitter/plugins/react-stable-hmr-split-route-components.d.cts +3 -1
- package/dist/cjs/core/code-splitter/plugins.d.cts +2 -0
- package/dist/cjs/core/config.cjs +4 -1
- package/dist/cjs/core/config.cjs.map +1 -1
- package/dist/cjs/core/config.d.cts +25 -0
- package/dist/cjs/core/hmr-hot-expression.cjs +27 -0
- package/dist/cjs/core/hmr-hot-expression.cjs.map +1 -0
- package/dist/cjs/core/hmr-hot-expression.d.cts +6 -0
- package/dist/cjs/core/route-autoimport-plugin.cjs +2 -2
- package/dist/cjs/core/route-hmr-statement.cjs +13 -10
- package/dist/cjs/core/route-hmr-statement.cjs.map +1 -1
- package/dist/cjs/core/route-hmr-statement.d.cts +3 -1
- package/dist/cjs/core/router-code-splitter-plugin.cjs +7 -10
- package/dist/cjs/core/router-code-splitter-plugin.cjs.map +1 -1
- package/dist/cjs/core/router-hmr-plugin.cjs +6 -2
- package/dist/cjs/core/router-hmr-plugin.cjs.map +1 -1
- package/dist/cjs/esbuild.d.cts +12 -0
- package/dist/cjs/index.d.cts +1 -1
- package/dist/cjs/rspack.cjs +3 -2
- package/dist/cjs/rspack.cjs.map +1 -1
- package/dist/cjs/rspack.d.cts +6 -135
- package/dist/cjs/vite.d.cts +15 -0
- package/dist/cjs/webpack.cjs +3 -2
- package/dist/cjs/webpack.cjs.map +1 -1
- package/dist/cjs/webpack.d.cts +6 -135
- package/dist/esm/core/code-splitter/compilers.d.ts +2 -10
- package/dist/esm/core/code-splitter/compilers.js +4 -3
- package/dist/esm/core/code-splitter/compilers.js.map +1 -1
- package/dist/esm/core/code-splitter/plugins/framework-plugins.d.ts +1 -0
- package/dist/esm/core/code-splitter/plugins/framework-plugins.js +2 -2
- package/dist/esm/core/code-splitter/plugins/framework-plugins.js.map +1 -1
- package/dist/esm/core/code-splitter/plugins/react-refresh-ignored-route-exports.d.ts +3 -1
- package/dist/esm/core/code-splitter/plugins/react-refresh-ignored-route-exports.js +11 -5
- package/dist/esm/core/code-splitter/plugins/react-refresh-ignored-route-exports.js.map +1 -1
- package/dist/esm/core/code-splitter/plugins/react-stable-hmr-split-route-components.d.ts +3 -1
- package/dist/esm/core/code-splitter/plugins/react-stable-hmr-split-route-components.js +11 -6
- package/dist/esm/core/code-splitter/plugins/react-stable-hmr-split-route-components.js.map +1 -1
- package/dist/esm/core/code-splitter/plugins.d.ts +2 -0
- package/dist/esm/core/config.d.ts +25 -0
- package/dist/esm/core/config.js +4 -1
- package/dist/esm/core/config.js.map +1 -1
- package/dist/esm/core/hmr-hot-expression.d.ts +6 -0
- package/dist/esm/core/hmr-hot-expression.js +23 -0
- package/dist/esm/core/hmr-hot-expression.js.map +1 -0
- package/dist/esm/core/route-autoimport-plugin.js +1 -1
- package/dist/esm/core/route-hmr-statement.d.ts +3 -1
- package/dist/esm/core/route-hmr-statement.js +13 -10
- package/dist/esm/core/route-hmr-statement.js.map +1 -1
- package/dist/esm/core/router-code-splitter-plugin.js +7 -10
- package/dist/esm/core/router-code-splitter-plugin.js.map +1 -1
- package/dist/esm/core/router-hmr-plugin.js +6 -2
- package/dist/esm/core/router-hmr-plugin.js.map +1 -1
- package/dist/esm/esbuild.d.ts +12 -0
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/rspack.d.ts +6 -135
- package/dist/esm/rspack.js +3 -2
- package/dist/esm/rspack.js.map +1 -1
- package/dist/esm/vite.d.ts +15 -0
- package/dist/esm/webpack.d.ts +6 -135
- package/dist/esm/webpack.js +3 -2
- package/dist/esm/webpack.js.map +1 -1
- package/package.json +4 -4
- package/src/core/code-splitter/compilers.ts +8 -12
- package/src/core/code-splitter/plugins/framework-plugins.ts +7 -2
- package/src/core/code-splitter/plugins/react-refresh-ignored-route-exports.ts +12 -4
- package/src/core/code-splitter/plugins/react-stable-hmr-split-route-components.ts +14 -5
- package/src/core/code-splitter/plugins.ts +2 -0
- package/src/core/config.ts +9 -0
- package/src/core/hmr-hot-expression.ts +31 -0
- package/src/core/route-hmr-statement.ts +31 -22
- package/src/core/router-code-splitter-plugin.ts +8 -14
- package/src/core/router-hmr-plugin.ts +10 -1
- package/src/index.ts +1 -0
- package/src/rspack.ts +17 -2
- package/src/webpack.ts +17 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-refresh-ignored-route-exports.cjs","names":[],"sources":["../../../../../src/core/code-splitter/plugins/react-refresh-ignored-route-exports.ts"],"sourcesContent":["import * as template from '@babel/template'\nimport * as t from '@babel/types'\nimport { getUniqueProgramIdentifier } from '../../utils'\nimport type { ReferenceRouteCompilerPlugin } from '../plugins'\n\nconst
|
|
1
|
+
{"version":3,"file":"react-refresh-ignored-route-exports.cjs","names":[],"sources":["../../../../../src/core/code-splitter/plugins/react-refresh-ignored-route-exports.ts"],"sourcesContent":["import * as template from '@babel/template'\nimport * as t from '@babel/types'\nimport { createHmrHotExpressionAst } from '../../hmr-hot-expression'\nimport { getUniqueProgramIdentifier } from '../../utils'\nimport type { ReferenceRouteCompilerPlugin } from '../plugins'\n\nconst buildReactRefreshIgnoredRouteExportsStatements = template.statements(\n `\nconst hot = %%hotExpression%%\nif (hot && typeof window !== 'undefined') {\n ;(hot.data ??= {})\n const tsrReactRefresh = window.__TSR_REACT_REFRESH__ ??= (() => {\n const ignoredExportsById = new Map()\n const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports\n\n window.__getReactRefreshIgnoredExports = (ctx) => {\n const ignoredExports = previousGetIgnoredExports?.(ctx) ?? []\n const moduleIgnored = ignoredExportsById.get(ctx.id) ?? []\n return [...ignoredExports, ...moduleIgnored]\n }\n\n return {\n ignoredExportsById,\n }\n })()\n\n tsrReactRefresh.ignoredExportsById.set(%%moduleId%%, ['Route'])\n}\n`,\n { syntacticPlaceholders: true },\n)\n\n/**\n * A trivial component-shaped export that gives `@vitejs/plugin-react` a valid\n * Fast Refresh boundary. Without at least one non-ignored component export,\n * the module would be invalidated (full page reload) on every update even\n * though our custom route HMR handler already manages the update.\n */\nconst buildRefreshAnchorStatement = template.statement(\n `export function %%anchorName%%() { return null }`,\n { syntacticPlaceholders: true },\n)\n\nexport function createReactRefreshIgnoredRouteExportsPlugin(opts?: {\n hotExpression?: string\n}): ReferenceRouteCompilerPlugin {\n return {\n name: 'react-refresh-ignored-route-exports',\n onAddHmr(ctx) {\n const anchorName = getUniqueProgramIdentifier(\n ctx.programPath,\n 'TSRFastRefreshAnchor',\n )\n\n ctx.programPath.pushContainer(\n 'body',\n buildReactRefreshIgnoredRouteExportsStatements({\n hotExpression: createHmrHotExpressionAst(\n opts?.hotExpression ?? ctx.opts.hmrHotExpression,\n ),\n moduleId: t.stringLiteral(ctx.opts.id),\n }),\n )\n\n ctx.programPath.pushContainer(\n 'body',\n buildRefreshAnchorStatement({ anchorName }),\n )\n\n return { modified: true }\n },\n }\n}\n"],"mappings":";;;;;;;;AAMA,IAAM,iDAAiD,gBAAS,WAC9D;;;;;;;;;;;;;;;;;;;;;GAsBA,EAAE,uBAAuB,MAAM,CAChC;;;;;;;AAQD,IAAM,8BAA8B,gBAAS,UAC3C,oDACA,EAAE,uBAAuB,MAAM,CAChC;AAED,SAAgB,4CAA4C,MAE3B;AAC/B,QAAO;EACL,MAAM;EACN,SAAS,KAAK;GACZ,MAAM,aAAa,cAAA,2BACjB,IAAI,aACJ,uBACD;AAED,OAAI,YAAY,cACd,QACA,+CAA+C;IAC7C,eAAe,2BAAA,0BACb,MAAM,iBAAiB,IAAI,KAAK,iBACjC;IACD,UAAU,aAAE,cAAc,IAAI,KAAK,GAAG;IACvC,CAAC,CACH;AAED,OAAI,YAAY,cACd,QACA,4BAA4B,EAAE,YAAY,CAAC,CAC5C;AAED,UAAO,EAAE,UAAU,MAAM;;EAE5B"}
|
|
@@ -1,2 +1,4 @@
|
|
|
1
1
|
import { ReferenceRouteCompilerPlugin } from '../plugins.cjs';
|
|
2
|
-
export declare function createReactRefreshIgnoredRouteExportsPlugin(
|
|
2
|
+
export declare function createReactRefreshIgnoredRouteExportsPlugin(opts?: {
|
|
3
|
+
hotExpression?: string;
|
|
4
|
+
}): ReferenceRouteCompilerPlugin;
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
const require_runtime = require("../../../_virtual/_rolldown/runtime.cjs");
|
|
2
|
+
const require_hmr_hot_expression = require("../../hmr-hot-expression.cjs");
|
|
2
3
|
const require_utils = require("../../utils.cjs");
|
|
3
|
-
let _babel_types = require("@babel/types");
|
|
4
|
-
_babel_types = require_runtime.__toESM(_babel_types);
|
|
5
4
|
let _babel_template = require("@babel/template");
|
|
6
5
|
_babel_template = require_runtime.__toESM(_babel_template);
|
|
6
|
+
let _babel_types = require("@babel/types");
|
|
7
|
+
_babel_types = require_runtime.__toESM(_babel_types);
|
|
7
8
|
//#region src/core/code-splitter/plugins/react-stable-hmr-split-route-components.ts
|
|
8
9
|
function capitalizeIdentifier(str) {
|
|
9
10
|
return str[0].toUpperCase() + str.slice(1);
|
|
@@ -12,13 +13,16 @@ function createHotDataKey(exportName) {
|
|
|
12
13
|
return `tsr-split-component:${exportName}`;
|
|
13
14
|
}
|
|
14
15
|
var buildStableSplitComponentStatements = _babel_template.statements(`
|
|
15
|
-
const %%stableComponentIdent%% =
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
16
|
+
const %%stableComponentIdent%% = (() => {
|
|
17
|
+
const hot = %%hotExpression%%
|
|
18
|
+
const hotData = hot ? (hot.data ??= {}) : undefined
|
|
19
|
+
return hotData?.[%%hotDataKey%%] ?? %%lazyRouteComponentIdent%%(%%localImporterIdent%%, %%exporterIdent%%)
|
|
20
|
+
})()
|
|
21
|
+
if (%%hotExpression%%) {
|
|
22
|
+
((%%hotExpression%%).data ??= {})[%%hotDataKey%%] = %%stableComponentIdent%%
|
|
19
23
|
}
|
|
20
24
|
`, { syntacticPlaceholders: true });
|
|
21
|
-
function createReactStableHmrSplitRouteComponentsPlugin() {
|
|
25
|
+
function createReactStableHmrSplitRouteComponentsPlugin(opts) {
|
|
22
26
|
return {
|
|
23
27
|
name: "react-stable-hmr-split-route-components",
|
|
24
28
|
onSplitRouteProperty(ctx) {
|
|
@@ -28,6 +32,7 @@ function createReactStableHmrSplitRouteComponentsPlugin() {
|
|
|
28
32
|
ctx.insertionPath.insertBefore(buildStableSplitComponentStatements({
|
|
29
33
|
stableComponentIdent,
|
|
30
34
|
hotDataKey: _babel_types.stringLiteral(hotDataKey),
|
|
35
|
+
hotExpression: require_hmr_hot_expression.createHmrHotExpressionAst(opts?.hotExpression ?? ctx.opts.hmrHotExpression),
|
|
31
36
|
lazyRouteComponentIdent: _babel_types.identifier(ctx.lazyRouteComponentIdent),
|
|
32
37
|
localImporterIdent: _babel_types.identifier(ctx.splitNodeMeta.localImporterIdent),
|
|
33
38
|
exporterIdent: _babel_types.stringLiteral(ctx.splitNodeMeta.exporterIdent)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-stable-hmr-split-route-components.cjs","names":[],"sources":["../../../../../src/core/code-splitter/plugins/react-stable-hmr-split-route-components.ts"],"sourcesContent":["import * as template from '@babel/template'\nimport * as t from '@babel/types'\nimport { getUniqueProgramIdentifier } from '../../utils'\nimport type { ReferenceRouteCompilerPlugin } from '../plugins'\n\nfunction capitalizeIdentifier(str: string) {\n return str[0]!.toUpperCase() + str.slice(1)\n}\n\nfunction createHotDataKey(exportName: string) {\n return `tsr-split-component:${exportName}`\n}\n\nconst buildStableSplitComponentStatements = template.statements(\n `\n const %%stableComponentIdent%% =
|
|
1
|
+
{"version":3,"file":"react-stable-hmr-split-route-components.cjs","names":[],"sources":["../../../../../src/core/code-splitter/plugins/react-stable-hmr-split-route-components.ts"],"sourcesContent":["import * as template from '@babel/template'\nimport * as t from '@babel/types'\nimport { createHmrHotExpressionAst } from '../../hmr-hot-expression'\nimport { getUniqueProgramIdentifier } from '../../utils'\nimport type { ReferenceRouteCompilerPlugin } from '../plugins'\n\nfunction capitalizeIdentifier(str: string) {\n return str[0]!.toUpperCase() + str.slice(1)\n}\n\nfunction createHotDataKey(exportName: string) {\n return `tsr-split-component:${exportName}`\n}\n\nconst buildStableSplitComponentStatements = template.statements(\n `\n const %%stableComponentIdent%% = (() => {\n const hot = %%hotExpression%%\n const hotData = hot ? (hot.data ??= {}) : undefined\n return hotData?.[%%hotDataKey%%] ?? %%lazyRouteComponentIdent%%(%%localImporterIdent%%, %%exporterIdent%%)\n })()\n if (%%hotExpression%%) {\n ((%%hotExpression%%).data ??= {})[%%hotDataKey%%] = %%stableComponentIdent%%\n }\n `,\n {\n syntacticPlaceholders: true,\n },\n)\n\nexport function createReactStableHmrSplitRouteComponentsPlugin(opts?: {\n hotExpression?: string\n}): ReferenceRouteCompilerPlugin {\n return {\n name: 'react-stable-hmr-split-route-components',\n onSplitRouteProperty(ctx) {\n if (ctx.splitNodeMeta.splitStrategy !== 'lazyRouteComponent') {\n return\n }\n\n const stableComponentIdent = getUniqueProgramIdentifier(\n ctx.programPath,\n `TSRSplit${capitalizeIdentifier(ctx.splitNodeMeta.exporterIdent)}`,\n )\n\n const hotDataKey = createHotDataKey(ctx.splitNodeMeta.exporterIdent)\n\n ctx.insertionPath.insertBefore(\n buildStableSplitComponentStatements({\n stableComponentIdent,\n hotDataKey: t.stringLiteral(hotDataKey),\n hotExpression: createHmrHotExpressionAst(\n opts?.hotExpression ?? ctx.opts.hmrHotExpression,\n ),\n lazyRouteComponentIdent: t.identifier(ctx.lazyRouteComponentIdent),\n localImporterIdent: t.identifier(\n ctx.splitNodeMeta.localImporterIdent,\n ),\n exporterIdent: t.stringLiteral(ctx.splitNodeMeta.exporterIdent),\n }),\n )\n\n return t.identifier(stableComponentIdent.name)\n },\n }\n}\n"],"mappings":";;;;;;;;AAMA,SAAS,qBAAqB,KAAa;AACzC,QAAO,IAAI,GAAI,aAAa,GAAG,IAAI,MAAM,EAAE;;AAG7C,SAAS,iBAAiB,YAAoB;AAC5C,QAAO,uBAAuB;;AAGhC,IAAM,sCAAsC,gBAAS,WACnD;;;;;;;;;KAUA,EACE,uBAAuB,MACxB,CACF;AAED,SAAgB,+CAA+C,MAE9B;AAC/B,QAAO;EACL,MAAM;EACN,qBAAqB,KAAK;AACxB,OAAI,IAAI,cAAc,kBAAkB,qBACtC;GAGF,MAAM,uBAAuB,cAAA,2BAC3B,IAAI,aACJ,WAAW,qBAAqB,IAAI,cAAc,cAAc,GACjE;GAED,MAAM,aAAa,iBAAiB,IAAI,cAAc,cAAc;AAEpE,OAAI,cAAc,aAChB,oCAAoC;IAClC;IACA,YAAY,aAAE,cAAc,WAAW;IACvC,eAAe,2BAAA,0BACb,MAAM,iBAAiB,IAAI,KAAK,iBACjC;IACD,yBAAyB,aAAE,WAAW,IAAI,wBAAwB;IAClE,oBAAoB,aAAE,WACpB,IAAI,cAAc,mBACnB;IACD,eAAe,aAAE,cAAc,IAAI,cAAc,cAAc;IAChE,CAAC,CACH;AAED,UAAO,aAAE,WAAW,qBAAqB,KAAK;;EAEjD"}
|
|
@@ -1,2 +1,4 @@
|
|
|
1
1
|
import { ReferenceRouteCompilerPlugin } from '../plugins.cjs';
|
|
2
|
-
export declare function createReactStableHmrSplitRouteComponentsPlugin(
|
|
2
|
+
export declare function createReactStableHmrSplitRouteComponentsPlugin(opts?: {
|
|
3
|
+
hotExpression?: string;
|
|
4
|
+
}): ReferenceRouteCompilerPlugin;
|
|
@@ -10,6 +10,7 @@ export type CompileCodeSplitReferenceRouteOptions = {
|
|
|
10
10
|
filename: string;
|
|
11
11
|
id: string;
|
|
12
12
|
addHmr?: boolean;
|
|
13
|
+
hmrHotExpression?: string;
|
|
13
14
|
sharedBindings?: Set<string>;
|
|
14
15
|
};
|
|
15
16
|
export type ReferenceRouteCompilerPluginContext = {
|
|
@@ -28,6 +29,7 @@ export type ReferenceRouteSplitPropertyCompilerPluginContext = {
|
|
|
28
29
|
prop: t.ObjectProperty;
|
|
29
30
|
splitNodeMeta: SplitNodeMeta;
|
|
30
31
|
lazyRouteComponentIdent: string;
|
|
32
|
+
opts: CompileCodeSplitReferenceRouteOptions;
|
|
31
33
|
};
|
|
32
34
|
export type ReferenceRouteCompilerPluginResult = {
|
|
33
35
|
modified?: boolean;
|
package/dist/cjs/core/config.cjs
CHANGED
|
@@ -26,7 +26,10 @@ var configSchema = _tanstack_router_generator.configSchema.extend({
|
|
|
26
26
|
codeSplittingOptions: zod.z.custom((v) => {
|
|
27
27
|
return codeSplittingOptionsSchema.parse(v);
|
|
28
28
|
}).optional(),
|
|
29
|
-
plugin: zod.z.object({
|
|
29
|
+
plugin: zod.z.object({
|
|
30
|
+
hmr: zod.z.object({ hotExpression: zod.z.string().optional() }).optional(),
|
|
31
|
+
vite: zod.z.object({ environmentName: zod.z.string().optional() }).optional()
|
|
32
|
+
}).optional()
|
|
30
33
|
});
|
|
31
34
|
var getConfig = (inlineConfig, root) => {
|
|
32
35
|
const config = (0, _tanstack_router_generator.getConfig)(inlineConfig, root);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.cjs","names":[],"sources":["../../../src/core/config.ts"],"sourcesContent":["import { z } from 'zod'\nimport {\n configSchema as generatorConfigSchema,\n getConfig as getGeneratorConfig,\n} from '@tanstack/router-generator'\nimport type {\n CreateFileRoute,\n RegisteredRouter,\n RouteIds,\n} from '@tanstack/router-core'\nimport type { CodeSplitGroupings } from './constants'\n\nexport const splitGroupingsSchema = z\n .array(\n z.array(\n z.union([\n z.literal('loader'),\n z.literal('component'),\n z.literal('pendingComponent'),\n z.literal('errorComponent'),\n z.literal('notFoundComponent'),\n ]),\n ),\n {\n message:\n \" Must be an Array of Arrays containing the split groupings. i.e. [['component'], ['pendingComponent'], ['errorComponent', 'notFoundComponent']]\",\n },\n )\n .superRefine((val, ctx) => {\n const flattened = val.flat()\n const unique = [...new Set(flattened)]\n\n // Elements must be unique,\n // ie. this shouldn't be allows [['component'], ['component', 'loader']]\n if (unique.length !== flattened.length) {\n ctx.addIssue({\n code: 'custom',\n message:\n \" Split groupings must be unique and not repeated. i.e. i.e. [['component'], ['pendingComponent'], ['errorComponent', 'notFoundComponent']].\" +\n `\\n You input was: ${JSON.stringify(val)}.`,\n })\n }\n })\n\nexport type CodeSplittingOptions = {\n /**\n * Use this function to programmatically control the code splitting behavior\n * based on the `routeId` for each route.\n *\n * If you just need to change the default behavior, you can use the `defaultBehavior` option.\n * @param params\n */\n splitBehavior?: (params: {\n routeId: RouteIds<RegisteredRouter['routeTree']>\n }) => CodeSplitGroupings | undefined | void\n\n /**\n * The default/global configuration to control your code splitting behavior per route.\n * @default [['component'],['pendingComponent'],['errorComponent'],['notFoundComponent']]\n */\n defaultBehavior?: CodeSplitGroupings\n\n /**\n * The nodes that shall be deleted from the route.\n * @default undefined\n */\n deleteNodes?: Array<DeletableNodes>\n\n /**\n * @default true\n */\n addHmr?: boolean\n}\n\nconst codeSplittingOptionsSchema = z.object({\n splitBehavior: z.function().optional(),\n defaultBehavior: splitGroupingsSchema.optional(),\n deleteNodes: z.array(z.string()).optional(),\n addHmr: z.boolean().optional().default(true),\n})\n\ntype FileRouteKeys = keyof (Parameters<\n CreateFileRoute<any, any, any, any, any>\n>[0] & {})\nexport type DeletableNodes = FileRouteKeys | (string & {})\n\nexport const configSchema = generatorConfigSchema.extend({\n enableRouteGeneration: z.boolean().optional(),\n codeSplittingOptions: z\n .custom<CodeSplittingOptions>((v) => {\n return codeSplittingOptionsSchema.parse(v)\n })\n .optional(),\n plugin: z\n .object({\n vite: z\n .object({\n environmentName: z.string().optional(),\n })\n .optional(),\n })\n .optional(),\n})\n\nexport const getConfig = (inlineConfig: Partial<Config>, root: string) => {\n const config = getGeneratorConfig(inlineConfig, root)\n\n return configSchema.parse({ ...inlineConfig, ...config })\n}\n\nexport type Config = z.infer<typeof configSchema>\nexport type ConfigInput = z.input<typeof configSchema>\nexport type ConfigOutput = z.output<typeof configSchema>\n"],"mappings":";;;;AAYA,IAAa,uBAAuB,IAAA,EACjC,MACC,IAAA,EAAE,MACA,IAAA,EAAE,MAAM;CACN,IAAA,EAAE,QAAQ,SAAS;CACnB,IAAA,EAAE,QAAQ,YAAY;CACtB,IAAA,EAAE,QAAQ,mBAAmB;CAC7B,IAAA,EAAE,QAAQ,iBAAiB;CAC3B,IAAA,EAAE,QAAQ,oBAAoB;CAC/B,CAAC,CACH,EACD,EACE,SACE,oJACH,CACF,CACA,aAAa,KAAK,QAAQ;CACzB,MAAM,YAAY,IAAI,MAAM;AAK5B,KAJe,CAAC,GAAG,IAAI,IAAI,UAAU,CAAC,CAI3B,WAAW,UAAU,OAC9B,KAAI,SAAS;EACX,MAAM;EACN,SACE,kKACsB,KAAK,UAAU,IAAI,CAAC;EAC7C,CAAC;EAEJ;
|
|
1
|
+
{"version":3,"file":"config.cjs","names":[],"sources":["../../../src/core/config.ts"],"sourcesContent":["import { z } from 'zod'\nimport {\n configSchema as generatorConfigSchema,\n getConfig as getGeneratorConfig,\n} from '@tanstack/router-generator'\nimport type {\n CreateFileRoute,\n RegisteredRouter,\n RouteIds,\n} from '@tanstack/router-core'\nimport type { CodeSplitGroupings } from './constants'\n\nexport const splitGroupingsSchema = z\n .array(\n z.array(\n z.union([\n z.literal('loader'),\n z.literal('component'),\n z.literal('pendingComponent'),\n z.literal('errorComponent'),\n z.literal('notFoundComponent'),\n ]),\n ),\n {\n message:\n \" Must be an Array of Arrays containing the split groupings. i.e. [['component'], ['pendingComponent'], ['errorComponent', 'notFoundComponent']]\",\n },\n )\n .superRefine((val, ctx) => {\n const flattened = val.flat()\n const unique = [...new Set(flattened)]\n\n // Elements must be unique,\n // ie. this shouldn't be allows [['component'], ['component', 'loader']]\n if (unique.length !== flattened.length) {\n ctx.addIssue({\n code: 'custom',\n message:\n \" Split groupings must be unique and not repeated. i.e. i.e. [['component'], ['pendingComponent'], ['errorComponent', 'notFoundComponent']].\" +\n `\\n You input was: ${JSON.stringify(val)}.`,\n })\n }\n })\n\nexport type CodeSplittingOptions = {\n /**\n * Use this function to programmatically control the code splitting behavior\n * based on the `routeId` for each route.\n *\n * If you just need to change the default behavior, you can use the `defaultBehavior` option.\n * @param params\n */\n splitBehavior?: (params: {\n routeId: RouteIds<RegisteredRouter['routeTree']>\n }) => CodeSplitGroupings | undefined | void\n\n /**\n * The default/global configuration to control your code splitting behavior per route.\n * @default [['component'],['pendingComponent'],['errorComponent'],['notFoundComponent']]\n */\n defaultBehavior?: CodeSplitGroupings\n\n /**\n * The nodes that shall be deleted from the route.\n * @default undefined\n */\n deleteNodes?: Array<DeletableNodes>\n\n /**\n * @default true\n */\n addHmr?: boolean\n}\n\nexport type HmrOptions = {\n hotExpression?: string\n}\n\nconst codeSplittingOptionsSchema = z.object({\n splitBehavior: z.function().optional(),\n defaultBehavior: splitGroupingsSchema.optional(),\n deleteNodes: z.array(z.string()).optional(),\n addHmr: z.boolean().optional().default(true),\n})\n\ntype FileRouteKeys = keyof (Parameters<\n CreateFileRoute<any, any, any, any, any>\n>[0] & {})\nexport type DeletableNodes = FileRouteKeys | (string & {})\n\nexport const configSchema = generatorConfigSchema.extend({\n enableRouteGeneration: z.boolean().optional(),\n codeSplittingOptions: z\n .custom<CodeSplittingOptions>((v) => {\n return codeSplittingOptionsSchema.parse(v)\n })\n .optional(),\n plugin: z\n .object({\n hmr: z\n .object({\n hotExpression: z.string().optional(),\n })\n .optional(),\n vite: z\n .object({\n environmentName: z.string().optional(),\n })\n .optional(),\n })\n .optional(),\n})\n\nexport const getConfig = (inlineConfig: Partial<Config>, root: string) => {\n const config = getGeneratorConfig(inlineConfig, root)\n\n return configSchema.parse({ ...inlineConfig, ...config })\n}\n\nexport type Config = z.infer<typeof configSchema>\nexport type ConfigInput = z.input<typeof configSchema>\nexport type ConfigOutput = z.output<typeof configSchema>\n"],"mappings":";;;;AAYA,IAAa,uBAAuB,IAAA,EACjC,MACC,IAAA,EAAE,MACA,IAAA,EAAE,MAAM;CACN,IAAA,EAAE,QAAQ,SAAS;CACnB,IAAA,EAAE,QAAQ,YAAY;CACtB,IAAA,EAAE,QAAQ,mBAAmB;CAC7B,IAAA,EAAE,QAAQ,iBAAiB;CAC3B,IAAA,EAAE,QAAQ,oBAAoB;CAC/B,CAAC,CACH,EACD,EACE,SACE,oJACH,CACF,CACA,aAAa,KAAK,QAAQ;CACzB,MAAM,YAAY,IAAI,MAAM;AAK5B,KAJe,CAAC,GAAG,IAAI,IAAI,UAAU,CAAC,CAI3B,WAAW,UAAU,OAC9B,KAAI,SAAS;EACX,MAAM;EACN,SACE,kKACsB,KAAK,UAAU,IAAI,CAAC;EAC7C,CAAC;EAEJ;AAoCJ,IAAM,6BAA6B,IAAA,EAAE,OAAO;CAC1C,eAAe,IAAA,EAAE,UAAU,CAAC,UAAU;CACtC,iBAAiB,qBAAqB,UAAU;CAChD,aAAa,IAAA,EAAE,MAAM,IAAA,EAAE,QAAQ,CAAC,CAAC,UAAU;CAC3C,QAAQ,IAAA,EAAE,SAAS,CAAC,UAAU,CAAC,QAAQ,KAAK;CAC7C,CAAC;AAOF,IAAa,eAAe,2BAAA,aAAsB,OAAO;CACvD,uBAAuB,IAAA,EAAE,SAAS,CAAC,UAAU;CAC7C,sBAAsB,IAAA,EACnB,QAA8B,MAAM;AACnC,SAAO,2BAA2B,MAAM,EAAE;GAC1C,CACD,UAAU;CACb,QAAQ,IAAA,EACL,OAAO;EACN,KAAK,IAAA,EACF,OAAO,EACN,eAAe,IAAA,EAAE,QAAQ,CAAC,UAAU,EACrC,CAAC,CACD,UAAU;EACb,MAAM,IAAA,EACH,OAAO,EACN,iBAAiB,IAAA,EAAE,QAAQ,CAAC,UAAU,EACvC,CAAC,CACD,UAAU;EACd,CAAC,CACD,UAAU;CACd,CAAC;AAEF,IAAa,aAAa,cAA+B,SAAiB;CACxE,MAAM,UAAA,GAAA,2BAAA,WAA4B,cAAc,KAAK;AAErD,QAAO,aAAa,MAAM;EAAE,GAAG;EAAc,GAAG;EAAQ,CAAC"}
|
|
@@ -28,6 +28,9 @@ export type CodeSplittingOptions = {
|
|
|
28
28
|
*/
|
|
29
29
|
addHmr?: boolean;
|
|
30
30
|
};
|
|
31
|
+
export type HmrOptions = {
|
|
32
|
+
hotExpression?: string;
|
|
33
|
+
};
|
|
31
34
|
type FileRouteKeys = keyof (Parameters<CreateFileRoute<any, any, any, any, any>>[0] & {});
|
|
32
35
|
export type DeletableNodes = FileRouteKeys | (string & {});
|
|
33
36
|
export declare const configSchema: z.ZodObject<{
|
|
@@ -94,6 +97,13 @@ export declare const configSchema: z.ZodObject<{
|
|
|
94
97
|
enableRouteGeneration: z.ZodOptional<z.ZodBoolean>;
|
|
95
98
|
codeSplittingOptions: z.ZodOptional<z.ZodType<CodeSplittingOptions, z.ZodTypeDef, CodeSplittingOptions>>;
|
|
96
99
|
plugin: z.ZodOptional<z.ZodObject<{
|
|
100
|
+
hmr: z.ZodOptional<z.ZodObject<{
|
|
101
|
+
hotExpression: z.ZodOptional<z.ZodString>;
|
|
102
|
+
}, "strip", z.ZodTypeAny, {
|
|
103
|
+
hotExpression?: string | undefined;
|
|
104
|
+
}, {
|
|
105
|
+
hotExpression?: string | undefined;
|
|
106
|
+
}>>;
|
|
97
107
|
vite: z.ZodOptional<z.ZodObject<{
|
|
98
108
|
environmentName: z.ZodOptional<z.ZodString>;
|
|
99
109
|
}, "strip", z.ZodTypeAny, {
|
|
@@ -102,10 +112,16 @@ export declare const configSchema: z.ZodObject<{
|
|
|
102
112
|
environmentName?: string | undefined;
|
|
103
113
|
}>>;
|
|
104
114
|
}, "strip", z.ZodTypeAny, {
|
|
115
|
+
hmr?: {
|
|
116
|
+
hotExpression?: string | undefined;
|
|
117
|
+
} | undefined;
|
|
105
118
|
vite?: {
|
|
106
119
|
environmentName?: string | undefined;
|
|
107
120
|
} | undefined;
|
|
108
121
|
}, {
|
|
122
|
+
hmr?: {
|
|
123
|
+
hotExpression?: string | undefined;
|
|
124
|
+
} | undefined;
|
|
109
125
|
vite?: {
|
|
110
126
|
environmentName?: string | undefined;
|
|
111
127
|
} | undefined;
|
|
@@ -135,6 +151,9 @@ export declare const configSchema: z.ZodObject<{
|
|
|
135
151
|
enableRouteGeneration?: boolean | undefined;
|
|
136
152
|
codeSplittingOptions?: CodeSplittingOptions | undefined;
|
|
137
153
|
plugin?: {
|
|
154
|
+
hmr?: {
|
|
155
|
+
hotExpression?: string | undefined;
|
|
156
|
+
} | undefined;
|
|
138
157
|
vite?: {
|
|
139
158
|
environmentName?: string | undefined;
|
|
140
159
|
} | undefined;
|
|
@@ -158,6 +177,9 @@ export declare const configSchema: z.ZodObject<{
|
|
|
158
177
|
enableRouteGeneration?: boolean | undefined;
|
|
159
178
|
codeSplittingOptions?: CodeSplittingOptions | undefined;
|
|
160
179
|
plugin?: {
|
|
180
|
+
hmr?: {
|
|
181
|
+
hotExpression?: string | undefined;
|
|
182
|
+
} | undefined;
|
|
161
183
|
vite?: {
|
|
162
184
|
environmentName?: string | undefined;
|
|
163
185
|
} | undefined;
|
|
@@ -224,6 +246,9 @@ export declare const getConfig: (inlineConfig: Partial<Config>, root: string) =>
|
|
|
224
246
|
enableRouteGeneration?: boolean | undefined;
|
|
225
247
|
codeSplittingOptions?: CodeSplittingOptions | undefined;
|
|
226
248
|
plugin?: {
|
|
249
|
+
hmr?: {
|
|
250
|
+
hotExpression?: string | undefined;
|
|
251
|
+
} | undefined;
|
|
227
252
|
vite?: {
|
|
228
253
|
environmentName?: string | undefined;
|
|
229
254
|
} | undefined;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
2
|
+
let _babel_template = require("@babel/template");
|
|
3
|
+
_babel_template = require_runtime.__toESM(_babel_template);
|
|
4
|
+
function resolveHmrHotExpression(hotExpression) {
|
|
5
|
+
return hotExpression ?? "import.meta.hot";
|
|
6
|
+
}
|
|
7
|
+
function createHmrHotExpressionAst(hotExpression) {
|
|
8
|
+
return _babel_template.expression.ast(resolveHmrHotExpression(hotExpression));
|
|
9
|
+
}
|
|
10
|
+
function withHmrHotExpression(config, hotExpression) {
|
|
11
|
+
return {
|
|
12
|
+
...config,
|
|
13
|
+
plugin: {
|
|
14
|
+
...config?.plugin,
|
|
15
|
+
hmr: {
|
|
16
|
+
...config?.plugin?.hmr,
|
|
17
|
+
hotExpression: config?.plugin?.hmr?.hotExpression ?? hotExpression
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
23
|
+
exports.createHmrHotExpressionAst = createHmrHotExpressionAst;
|
|
24
|
+
exports.resolveHmrHotExpression = resolveHmrHotExpression;
|
|
25
|
+
exports.withHmrHotExpression = withHmrHotExpression;
|
|
26
|
+
|
|
27
|
+
//# sourceMappingURL=hmr-hot-expression.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hmr-hot-expression.cjs","names":[],"sources":["../../../src/core/hmr-hot-expression.ts"],"sourcesContent":["import * as template from '@babel/template'\nimport type * as t from '@babel/types'\nimport type { Config } from './config'\n\nexport const DEFAULT_HMR_HOT_EXPRESSION = 'import.meta.hot'\n\nexport function resolveHmrHotExpression(hotExpression?: string): string {\n return hotExpression ?? DEFAULT_HMR_HOT_EXPRESSION\n}\n\nexport function createHmrHotExpressionAst(\n hotExpression?: string,\n): t.Expression {\n return template.expression.ast(resolveHmrHotExpression(hotExpression))\n}\n\nexport function withHmrHotExpression(\n config: Partial<Config> | undefined,\n hotExpression: string,\n): Partial<Config> {\n return {\n ...config,\n plugin: {\n ...config?.plugin,\n hmr: {\n ...config?.plugin?.hmr,\n hotExpression: config?.plugin?.hmr?.hotExpression ?? hotExpression,\n },\n },\n }\n}\n"],"mappings":";;;AAMA,SAAgB,wBAAwB,eAAgC;AACtE,QAAO,iBAAA;;AAGT,SAAgB,0BACd,eACc;AACd,QAAO,gBAAS,WAAW,IAAI,wBAAwB,cAAc,CAAC;;AAGxE,SAAgB,qBACd,QACA,eACiB;AACjB,QAAO;EACL,GAAG;EACH,QAAQ;GACN,GAAG,QAAQ;GACX,KAAK;IACH,GAAG,QAAQ,QAAQ;IACnB,eAAe,QAAQ,QAAQ,KAAK,iBAAiB;IACtD;GACF;EACF"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { Config } from './config.cjs';
|
|
2
|
+
import type * as t from '@babel/types';
|
|
3
|
+
export declare const DEFAULT_HMR_HOT_EXPRESSION = "import.meta.hot";
|
|
4
|
+
export declare function resolveHmrHotExpression(hotExpression?: string): string;
|
|
5
|
+
export declare function createHmrHotExpressionAst(hotExpression?: string): t.Expression;
|
|
6
|
+
export declare function withHmrHotExpression(config: Partial<Config> | undefined, hotExpression: string): Partial<Config>;
|
|
@@ -2,10 +2,10 @@ const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
|
2
2
|
const require_config = require("./config.cjs");
|
|
3
3
|
const require_utils = require("./utils.cjs");
|
|
4
4
|
let _tanstack_router_utils = require("@tanstack/router-utils");
|
|
5
|
-
let _babel_core = require("@babel/core");
|
|
6
|
-
_babel_core = require_runtime.__toESM(_babel_core);
|
|
7
5
|
let _babel_template = require("@babel/template");
|
|
8
6
|
_babel_template = require_runtime.__toESM(_babel_template);
|
|
7
|
+
let _babel_core = require("@babel/core");
|
|
8
|
+
_babel_core = require_runtime.__toESM(_babel_core);
|
|
9
9
|
//#region src/core/route-autoimport-plugin.ts
|
|
10
10
|
/**
|
|
11
11
|
* This plugin adds imports for createFileRoute and createLazyFileRoute to the file route.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
2
|
+
const require_hmr_hot_expression = require("./hmr-hot-expression.cjs");
|
|
2
3
|
let _babel_template = require("@babel/template");
|
|
3
4
|
_babel_template = require_runtime.__toESM(_babel_template);
|
|
4
5
|
//#region src/core/route-hmr-statement.ts
|
|
@@ -28,9 +29,9 @@ function handleRouteUpdate(routeId, newRoute) {
|
|
|
28
29
|
router.resolvePathCache.clear();
|
|
29
30
|
walkReplaceSegmentTree(oldRoute, router.processedTree.segmentTree);
|
|
30
31
|
const filter = (m) => m.routeId === oldRoute.id;
|
|
31
|
-
const activeMatch = router.stores.activeMatchesSnapshot.
|
|
32
|
-
const pendingMatch = router.stores.pendingMatchesSnapshot.
|
|
33
|
-
const cachedMatches = router.stores.cachedMatchesSnapshot.
|
|
32
|
+
const activeMatch = router.stores.activeMatchesSnapshot.get().find(filter);
|
|
33
|
+
const pendingMatch = router.stores.pendingMatchesSnapshot.get().find(filter);
|
|
34
|
+
const cachedMatches = router.stores.cachedMatchesSnapshot.get().filter(filter);
|
|
34
35
|
if (activeMatch || pendingMatch || cachedMatches.length > 0) {
|
|
35
36
|
if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) {
|
|
36
37
|
const matchIds = [
|
|
@@ -41,7 +42,7 @@ function handleRouteUpdate(routeId, newRoute) {
|
|
|
41
42
|
router.batch(() => {
|
|
42
43
|
for (const matchId of matchIds) {
|
|
43
44
|
const store = router.stores.pendingMatchStoresById.get(matchId) || router.stores.activeMatchStoresById.get(matchId) || router.stores.cachedMatchStoresById.get(matchId);
|
|
44
|
-
if (store) store.
|
|
45
|
+
if (store) store.set((prev) => {
|
|
45
46
|
const next = { ...prev };
|
|
46
47
|
if (removedKeys.has("loader")) next.loaderData = void 0;
|
|
47
48
|
if (removedKeys.has("beforeLoad")) next.__beforeLoadContext = void 0;
|
|
@@ -66,20 +67,22 @@ function handleRouteUpdate(routeId, newRoute) {
|
|
|
66
67
|
}
|
|
67
68
|
}
|
|
68
69
|
var handleRouteUpdateStr = handleRouteUpdate.toString();
|
|
69
|
-
function createRouteHmrStatement(stableRouteOptionKeys) {
|
|
70
|
+
function createRouteHmrStatement(stableRouteOptionKeys, opts) {
|
|
70
71
|
return _babel_template.statement(`
|
|
71
|
-
if (
|
|
72
|
-
|
|
72
|
+
if (%%hotExpression%%) {
|
|
73
|
+
const hot = %%hotExpression%%
|
|
74
|
+
const hotData = hot.data ??= {}
|
|
75
|
+
hot.accept((newModule) => {
|
|
73
76
|
if (Route && newModule && newModule.Route) {
|
|
74
|
-
const routeId =
|
|
77
|
+
const routeId = hotData['tsr-route-id'] ?? Route.id
|
|
75
78
|
if (routeId) {
|
|
76
|
-
|
|
79
|
+
hotData['tsr-route-id'] = routeId
|
|
77
80
|
}
|
|
78
81
|
(${handleRouteUpdateStr.replace(/['"]__TSR_COMPONENT_TYPES__['"]/, JSON.stringify(stableRouteOptionKeys))})(routeId, newModule.Route)
|
|
79
82
|
}
|
|
80
83
|
})
|
|
81
84
|
}
|
|
82
|
-
`, {
|
|
85
|
+
`, { syntacticPlaceholders: true })({ hotExpression: require_hmr_hot_expression.createHmrHotExpressionAst(opts?.hotExpression) });
|
|
83
86
|
}
|
|
84
87
|
//#endregion
|
|
85
88
|
exports.createRouteHmrStatement = createRouteHmrStatement;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-hmr-statement.cjs","names":[],"sources":["../../../src/core/route-hmr-statement.ts"],"sourcesContent":["import * as template from '@babel/template'\nimport type {
|
|
1
|
+
{"version":3,"file":"route-hmr-statement.cjs","names":[],"sources":["../../../src/core/route-hmr-statement.ts"],"sourcesContent":["import * as template from '@babel/template'\nimport { createHmrHotExpressionAst } from './hmr-hot-expression'\nimport type {\n AnyRoute,\n AnyRouteMatch,\n AnyRouter,\n RouterWritableStore,\n} from '@tanstack/router-core'\n\ntype AnyRouteWithPrivateProps = AnyRoute & {\n options: Record<string, unknown>\n _componentsPromise?: Promise<void>\n _lazyPromise?: Promise<void>\n update: (options: Record<string, unknown>) => unknown\n _path: string\n _id: string\n _fullPath: string\n _to: string\n}\n\ntype AnyRouterWithPrivateMaps = AnyRouter & {\n routesById: Record<string, AnyRoute>\n routesByPath: Record<string, AnyRoute>\n stores: AnyRouter['stores'] & {\n cachedMatchStoresById: Map<\n string,\n Pick<RouterWritableStore<AnyRouteMatch>, 'set'>\n >\n pendingMatchStoresById: Map<\n string,\n Pick<RouterWritableStore<AnyRouteMatch>, 'set'>\n >\n activeMatchStoresById: Map<\n string,\n Pick<RouterWritableStore<AnyRouteMatch>, 'set'>\n >\n }\n}\n\ntype AnyRouteMatchWithPrivateProps = AnyRouteMatch & {\n __beforeLoadContext?: unknown\n}\n\nfunction handleRouteUpdate(\n routeId: string,\n newRoute: AnyRouteWithPrivateProps,\n) {\n const router = window.__TSR_ROUTER__ as AnyRouterWithPrivateMaps\n const oldRoute = router.routesById[routeId] as\n | AnyRouteWithPrivateProps\n | undefined\n\n if (!oldRoute) {\n return\n }\n\n // Keys whose identity must remain stable to prevent React from\n // unmounting/remounting the component tree. React Fast Refresh already\n // handles hot-updating the function bodies of these components — our job\n // is only to update non-component route options (loader, head, etc.).\n // For code-split (splittable) routes, the lazyRouteComponent wrapper is\n // already cached in the bundler hot data so its identity is stable.\n // For unsplittable routes (e.g. root routes), the component is a plain\n // function reference that gets recreated on every module re-execution,\n // so we must explicitly preserve the old reference.\n const removedKeys = new Set<string>()\n Object.keys(oldRoute.options).forEach((key) => {\n if (!(key in newRoute.options)) {\n removedKeys.add(key)\n delete oldRoute.options[key]\n }\n })\n\n // Preserve component identity so React doesn't remount.\n // React Fast Refresh patches the function bodies in-place.\n const componentKeys = '__TSR_COMPONENT_TYPES__' as unknown as Array<string>\n componentKeys.forEach((key) => {\n if (key in oldRoute.options && key in newRoute.options) {\n newRoute.options[key] = oldRoute.options[key]\n }\n })\n\n oldRoute.options = newRoute.options\n oldRoute.update(newRoute.options)\n oldRoute._componentsPromise = undefined\n oldRoute._lazyPromise = undefined\n\n router.routesById[oldRoute.id] = oldRoute\n router.routesByPath[oldRoute.fullPath] = oldRoute\n\n router.processedTree.matchCache.clear()\n router.processedTree.flatCache?.clear()\n router.processedTree.singleCache.clear()\n router.resolvePathCache.clear()\n walkReplaceSegmentTree(oldRoute, router.processedTree.segmentTree)\n\n const filter = (m: AnyRouteMatch) => m.routeId === oldRoute.id\n const activeMatch = router.stores.activeMatchesSnapshot.get().find(filter)\n const pendingMatch = router.stores.pendingMatchesSnapshot.get().find(filter)\n const cachedMatches = router.stores.cachedMatchesSnapshot.get().filter(filter)\n\n if (activeMatch || pendingMatch || cachedMatches.length > 0) {\n // Clear stale match data for removed route options BEFORE invalidating.\n // Without this, router.invalidate() -> matchRoutes() reuses the existing\n // match from the store (via ...existingMatch spread) and the stale\n // loaderData / __beforeLoadContext survives the reload cycle.\n //\n // We must update the store directly (not via router.updateMatch) because\n // updateMatch wraps in startTransition which may defer the state update,\n // and we need the clear to be visible before invalidate reads the store.\n if (removedKeys.has('loader') || removedKeys.has('beforeLoad')) {\n const matchIds = [\n activeMatch?.id,\n pendingMatch?.id,\n ...cachedMatches.map((match) => match.id),\n ].filter(Boolean) as Array<string>\n router.batch(() => {\n for (const matchId of matchIds) {\n const store =\n router.stores.pendingMatchStoresById.get(matchId) ||\n router.stores.activeMatchStoresById.get(matchId) ||\n router.stores.cachedMatchStoresById.get(matchId)\n if (store) {\n store.set((prev) => {\n const next: AnyRouteMatchWithPrivateProps = { ...prev }\n\n if (removedKeys.has('loader')) {\n next.loaderData = undefined\n }\n if (removedKeys.has('beforeLoad')) {\n next.__beforeLoadContext = undefined\n }\n\n return next\n })\n }\n }\n })\n }\n\n router.invalidate({ filter, sync: true })\n }\n\n function walkReplaceSegmentTree(\n route: AnyRouteWithPrivateProps,\n node: AnyRouter['processedTree']['segmentTree'],\n ) {\n if (node.route?.id === route.id) node.route = route\n if (node.index) walkReplaceSegmentTree(route, node.index)\n node.static?.forEach((child) => walkReplaceSegmentTree(route, child))\n node.staticInsensitive?.forEach((child) =>\n walkReplaceSegmentTree(route, child),\n )\n node.dynamic?.forEach((child) => walkReplaceSegmentTree(route, child))\n node.optional?.forEach((child) => walkReplaceSegmentTree(route, child))\n node.wildcard?.forEach((child) => walkReplaceSegmentTree(route, child))\n }\n}\n\nconst handleRouteUpdateStr = handleRouteUpdate.toString()\n\nexport function createRouteHmrStatement(\n stableRouteOptionKeys: Array<string>,\n opts?: { hotExpression?: string },\n) {\n return template.statement(\n `\nif (%%hotExpression%%) {\n const hot = %%hotExpression%%\n const hotData = hot.data ??= {}\n hot.accept((newModule) => {\n if (Route && newModule && newModule.Route) {\n const routeId = hotData['tsr-route-id'] ?? Route.id\n if (routeId) {\n hotData['tsr-route-id'] = routeId\n }\n (${handleRouteUpdateStr.replace(\n /['\"]__TSR_COMPONENT_TYPES__['\"]/,\n JSON.stringify(stableRouteOptionKeys),\n )})(routeId, newModule.Route)\n }\n })\n}\n`,\n {\n syntacticPlaceholders: true,\n },\n )({\n hotExpression: createHmrHotExpressionAst(opts?.hotExpression),\n })\n}\n"],"mappings":";;;;;AA2CA,SAAS,kBACP,SACA,UACA;CACA,MAAM,SAAS,OAAO;CACtB,MAAM,WAAW,OAAO,WAAW;AAInC,KAAI,CAAC,SACH;CAYF,MAAM,8BAAc,IAAI,KAAa;AACrC,QAAO,KAAK,SAAS,QAAQ,CAAC,SAAS,QAAQ;AAC7C,MAAI,EAAE,OAAO,SAAS,UAAU;AAC9B,eAAY,IAAI,IAAI;AACpB,UAAO,SAAS,QAAQ;;GAE1B;AAIoB,2BACR,SAAS,QAAQ;AAC7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AAG7B,aAAO;OACP;;KAGN;;AAGJ,SAAO,WAAW;GAAE;GAAQ,MAAM;GAAM,CAAC;;CAG3C,SAAS,uBACP,OACA,MACA;AACA,MAAI,KAAK,OAAO,OAAO,MAAM,GAAI,MAAK,QAAQ;AAC9C,MAAI,KAAK,MAAO,wBAAuB,OAAO,KAAK,MAAM;AACzD,OAAK,QAAQ,SAAS,UAAU,uBAAuB,OAAO,MAAM,CAAC;AACrE,OAAK,mBAAmB,SAAS,UAC/B,uBAAuB,OAAO,MAAM,CACrC;AACD,OAAK,SAAS,SAAS,UAAU,uBAAuB,OAAO,MAAM,CAAC;AACtE,OAAK,UAAU,SAAS,UAAU,uBAAuB,OAAO,MAAM,CAAC;AACvE,OAAK,UAAU,SAAS,UAAU,uBAAuB,OAAO,MAAM,CAAC;;;AAI3E,IAAM,uBAAuB,kBAAkB,UAAU;AAEzD,SAAgB,wBACd,uBACA,MACA;AACA,QAAO,gBAAS,UACd;;;;;;;;;;SAUK,qBAAqB,QACtB,mCACA,KAAK,UAAU,sBAAsB,CACtC,CAAC;;;;GAKJ,EACE,uBAAuB,MACxB,CACF,CAAC,EACA,eAAe,2BAAA,0BAA0B,MAAM,cAAc,EAC9D,CAAC"}
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
export declare function createRouteHmrStatement(stableRouteOptionKeys: Array<string
|
|
1
|
+
export declare function createRouteHmrStatement(stableRouteOptionKeys: Array<string>, opts?: {
|
|
2
|
+
hotExpression?: string;
|
|
3
|
+
}): import('@babel/types').Statement;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
require("../_virtual/_rolldown/runtime.cjs");
|
|
2
2
|
const require_config = require("./config.cjs");
|
|
3
|
+
const require_hmr_hot_expression = require("./hmr-hot-expression.cjs");
|
|
3
4
|
const require_constants = require("./constants.cjs");
|
|
4
5
|
const require_utils = require("./utils.cjs");
|
|
5
6
|
const require_path_ids = require("./code-splitter/path-ids.cjs");
|
|
@@ -12,7 +13,6 @@ let _tanstack_router_utils = require("@tanstack/router-utils");
|
|
|
12
13
|
* It is important to familiarize yourself with how the code-splitting works in this plugin.
|
|
13
14
|
* https://github.com/TanStack/router/pull/3355
|
|
14
15
|
*/
|
|
15
|
-
var PLUGIN_NAME = "unplugin:router-code-splitter";
|
|
16
16
|
var CODE_SPLITTER_PLUGIN_NAME = "tanstack-router:code-splitter:compile-reference-file";
|
|
17
17
|
/**
|
|
18
18
|
* JSX transformation plugins grouped by framework.
|
|
@@ -83,6 +83,7 @@ var unpluginRouterCodeSplitterFactory = (options = {}, { framework: _framework }
|
|
|
83
83
|
if (sharedBindings.size > 0) sharedBindingsMap.set(id, sharedBindings);
|
|
84
84
|
else sharedBindingsMap.delete(id);
|
|
85
85
|
const addHmr = (userConfig.codeSplittingOptions?.addHmr ?? true) && !isProduction;
|
|
86
|
+
const hmrHotExpression = require_hmr_hot_expression.resolveHmrHotExpression(userConfig.plugin?.hmr?.hotExpression);
|
|
86
87
|
const compiledReferenceRoute = require_compilers.compileCodeSplitReferenceRoute({
|
|
87
88
|
code,
|
|
88
89
|
codeSplitGroupings: splitGroupings,
|
|
@@ -91,10 +92,12 @@ var unpluginRouterCodeSplitterFactory = (options = {}, { framework: _framework }
|
|
|
91
92
|
id,
|
|
92
93
|
deleteNodes: userConfig.codeSplittingOptions?.deleteNodes ? new Set(userConfig.codeSplittingOptions.deleteNodes) : void 0,
|
|
93
94
|
addHmr,
|
|
95
|
+
hmrHotExpression,
|
|
94
96
|
sharedBindings: sharedBindings.size > 0 ? sharedBindings : void 0,
|
|
95
97
|
compilerPlugins: require_framework_plugins.getReferenceRouteCompilerPlugins({
|
|
96
98
|
targetFramework: userConfig.target,
|
|
97
|
-
addHmr
|
|
99
|
+
addHmr,
|
|
100
|
+
hmrHotExpression
|
|
98
101
|
})
|
|
99
102
|
});
|
|
100
103
|
if (compiledReferenceRoute === null) {
|
|
@@ -169,19 +172,13 @@ var unpluginRouterCodeSplitterFactory = (options = {}, { framework: _framework }
|
|
|
169
172
|
return true;
|
|
170
173
|
}
|
|
171
174
|
},
|
|
172
|
-
rspack(
|
|
175
|
+
rspack() {
|
|
173
176
|
ROOT = process.cwd();
|
|
174
177
|
initUserConfig();
|
|
175
|
-
if (compiler.options.mode === "production") compiler.hooks.done.tap(PLUGIN_NAME, () => {
|
|
176
|
-
console.info("✅ " + PLUGIN_NAME + ": code-splitting done!");
|
|
177
|
-
});
|
|
178
178
|
},
|
|
179
|
-
webpack(
|
|
179
|
+
webpack() {
|
|
180
180
|
ROOT = process.cwd();
|
|
181
181
|
initUserConfig();
|
|
182
|
-
if (compiler.options.mode === "production") compiler.hooks.done.tap(PLUGIN_NAME, () => {
|
|
183
|
-
console.info("✅ " + PLUGIN_NAME + ": code-splitting done!");
|
|
184
|
-
});
|
|
185
182
|
}
|
|
186
183
|
},
|
|
187
184
|
{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router-code-splitter-plugin.cjs","names":[],"sources":["../../../src/core/router-code-splitter-plugin.ts"],"sourcesContent":["/**\n * It is important to familiarize yourself with how the code-splitting works in this plugin.\n * https://github.com/TanStack/router/pull/3355\n */\n\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { logDiff } from '@tanstack/router-utils'\nimport { getConfig, splitGroupingsSchema } from './config'\nimport {\n compileCodeSplitReferenceRoute,\n compileCodeSplitSharedRoute,\n compileCodeSplitVirtualRoute,\n computeSharedBindings,\n detectCodeSplitGroupingsFromRoute,\n} from './code-splitter/compilers'\nimport { getReferenceRouteCompilerPlugins } from './code-splitter/plugins/framework-plugins'\nimport {\n defaultCodeSplitGroupings,\n splitRouteIdentNodes,\n tsrShared,\n tsrSplit,\n} from './constants'\nimport { decodeIdentifier } from './code-splitter/path-ids'\nimport { debug, normalizePath } from './utils'\nimport type { CodeSplitGroupings, SplitRouteIdentNodes } from './constants'\nimport type { GetRoutesByFileMapResultValue } from '@tanstack/router-generator'\nimport type { Config } from './config'\nimport type {\n UnpluginFactory,\n TransformResult as UnpluginTransformResult,\n} from 'unplugin'\n\nconst PLUGIN_NAME = 'unplugin:router-code-splitter'\nconst CODE_SPLITTER_PLUGIN_NAME =\n 'tanstack-router:code-splitter:compile-reference-file'\n\ntype TransformationPluginInfo = {\n pluginNames: Array<string>\n pkg: string\n usage: string\n}\n\n/**\n * JSX transformation plugins grouped by framework.\n * These plugins must come AFTER the TanStack Router plugin in the Vite config.\n */\nconst TRANSFORMATION_PLUGINS_BY_FRAMEWORK: Record<\n string,\n Array<TransformationPluginInfo>\n> = {\n react: [\n {\n // Babel-based React plugin\n pluginNames: ['vite:react-babel', 'vite:react-refresh'],\n pkg: '@vitejs/plugin-react',\n usage: 'react()',\n },\n {\n // SWC-based React plugin\n pluginNames: ['vite:react-swc', 'vite:react-swc:resolve-runtime'],\n pkg: '@vitejs/plugin-react-swc',\n usage: 'reactSwc()',\n },\n {\n // OXC-based React plugin (deprecated but should still be handled)\n pluginNames: ['vite:react-oxc:config', 'vite:react-oxc:refresh-runtime'],\n pkg: '@vitejs/plugin-react-oxc',\n usage: 'reactOxc()',\n },\n ],\n solid: [\n {\n pluginNames: ['solid'],\n pkg: 'vite-plugin-solid',\n usage: 'solid()',\n },\n ],\n}\n\nexport const unpluginRouterCodeSplitterFactory: UnpluginFactory<\n Partial<Config | (() => Config)> | undefined\n> = (options = {}, { framework: _framework }) => {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n function initUserConfig() {\n if (typeof options === 'function') {\n userConfig = options()\n } else {\n userConfig = getConfig(options, ROOT)\n }\n }\n const isProduction = process.env.NODE_ENV === 'production'\n // Map from normalized route file path → set of shared binding names.\n // Populated by the reference compiler, consumed by virtual and shared compilers.\n const sharedBindingsMap = new Map<string, Set<string>>()\n\n const getGlobalCodeSplitGroupings = () => {\n return (\n userConfig.codeSplittingOptions?.defaultBehavior ||\n defaultCodeSplitGroupings\n )\n }\n const getShouldSplitFn = () => {\n return userConfig.codeSplittingOptions?.splitBehavior\n }\n\n const handleCompilingReferenceFile = (\n code: string,\n id: string,\n generatorNodeInfo: GetRoutesByFileMapResultValue,\n ): UnpluginTransformResult => {\n if (debug) console.info('Compiling Route: ', id)\n\n const fromCode = detectCodeSplitGroupingsFromRoute({\n code,\n })\n\n if (fromCode.groupings !== undefined) {\n const res = splitGroupingsSchema.safeParse(fromCode.groupings)\n if (!res.success) {\n const message = res.error.errors.map((e) => e.message).join('. ')\n throw new Error(\n `The groupings for the route \"${id}\" are invalid.\\n${message}`,\n )\n }\n }\n\n const userShouldSplitFn = getShouldSplitFn()\n\n const pluginSplitBehavior = userShouldSplitFn?.({\n routeId: generatorNodeInfo.routePath,\n }) as CodeSplitGroupings | undefined\n\n if (pluginSplitBehavior) {\n const res = splitGroupingsSchema.safeParse(pluginSplitBehavior)\n if (!res.success) {\n const message = res.error.errors.map((e) => e.message).join('. ')\n throw new Error(\n `The groupings returned when using \\`splitBehavior\\` for the route \"${id}\" are invalid.\\n${message}`,\n )\n }\n }\n\n const splitGroupings: CodeSplitGroupings =\n fromCode.groupings ?? pluginSplitBehavior ?? getGlobalCodeSplitGroupings()\n\n // Compute shared bindings before compiling the reference route\n const sharedBindings = computeSharedBindings({\n code,\n codeSplitGroupings: splitGroupings,\n })\n if (sharedBindings.size > 0) {\n sharedBindingsMap.set(id, sharedBindings)\n } else {\n sharedBindingsMap.delete(id)\n }\n\n const addHmr =\n (userConfig.codeSplittingOptions?.addHmr ?? true) && !isProduction\n\n const compiledReferenceRoute = compileCodeSplitReferenceRoute({\n code,\n codeSplitGroupings: splitGroupings,\n targetFramework: userConfig.target,\n filename: id,\n id,\n deleteNodes: userConfig.codeSplittingOptions?.deleteNodes\n ? new Set(userConfig.codeSplittingOptions.deleteNodes)\n : undefined,\n addHmr,\n sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined,\n compilerPlugins: getReferenceRouteCompilerPlugins({\n targetFramework: userConfig.target,\n addHmr,\n }),\n })\n\n if (compiledReferenceRoute === null) {\n if (debug) {\n console.info(\n `No changes made to route \"${id}\", skipping code-splitting.`,\n )\n }\n return null\n }\n if (debug) {\n logDiff(code, compiledReferenceRoute.code)\n console.log('Output:\\n', compiledReferenceRoute.code + '\\n\\n')\n }\n\n return compiledReferenceRoute\n }\n\n const handleCompilingVirtualFile = (\n code: string,\n id: string,\n ): UnpluginTransformResult => {\n if (debug) console.info('Splitting Route: ', id)\n\n const [_, ...pathnameParts] = id.split('?')\n\n const searchParams = new URLSearchParams(pathnameParts.join('?'))\n const splitValue = searchParams.get(tsrSplit)\n\n if (!splitValue) {\n throw new Error(\n `The split value for the virtual route \"${id}\" was not found.`,\n )\n }\n\n const rawGrouping = decodeIdentifier(splitValue)\n const grouping = [...new Set(rawGrouping)].filter((p) =>\n splitRouteIdentNodes.includes(p as any),\n ) as Array<SplitRouteIdentNodes>\n\n const baseId = id.split('?')[0]!\n const resolvedSharedBindings = sharedBindingsMap.get(baseId)\n\n const result = compileCodeSplitVirtualRoute({\n code,\n filename: id,\n splitTargets: grouping,\n sharedBindings: resolvedSharedBindings,\n })\n\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n\n return result\n }\n\n const includedCode = [\n 'createFileRoute(',\n 'createRootRoute(',\n 'createRootRouteWithContext(',\n ]\n return [\n {\n name: 'tanstack-router:code-splitter:compile-reference-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: {\n exclude: [tsrSplit, tsrShared],\n // this is necessary for webpack / rspack to avoid matching .html files\n include: /\\.(m|c)?(j|t)sx?$/,\n },\n code: {\n include: includedCode,\n },\n },\n handler(code, id) {\n const normalizedId = normalizePath(id)\n const generatorFileInfo =\n globalThis.TSR_ROUTES_BY_ID_MAP?.get(normalizedId)\n if (\n generatorFileInfo &&\n includedCode.some((included) => code.includes(included))\n ) {\n return handleCompilingReferenceFile(\n code,\n normalizedId,\n generatorFileInfo,\n )\n }\n\n return null\n },\n },\n\n vite: {\n configResolved(config) {\n ROOT = config.root\n initUserConfig()\n\n // Validate plugin order - router must come before JSX transformation plugins\n const routerPluginIndex = config.plugins.findIndex(\n (p) => p.name === CODE_SPLITTER_PLUGIN_NAME,\n )\n\n if (routerPluginIndex === -1) return\n\n const frameworkPlugins =\n TRANSFORMATION_PLUGINS_BY_FRAMEWORK[userConfig.target]\n if (!frameworkPlugins) return\n\n for (const transformPlugin of frameworkPlugins) {\n const transformPluginIndex = config.plugins.findIndex((p) =>\n transformPlugin.pluginNames.includes(p.name),\n )\n\n if (\n transformPluginIndex !== -1 &&\n transformPluginIndex < routerPluginIndex\n ) {\n throw new Error(\n `Plugin order error: '${transformPlugin.pkg}' is placed before '@tanstack/router-plugin'.\\n\\n` +\n `The TanStack Router plugin must come BEFORE JSX transformation plugins.\\n\\n` +\n `Please update your Vite config:\\n\\n` +\n ` plugins: [\\n` +\n ` tanstackRouter(),\\n` +\n ` ${transformPlugin.usage},\\n` +\n ` ]\\n`,\n )\n }\n }\n },\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n\n rspack(compiler) {\n ROOT = process.cwd()\n initUserConfig()\n\n if (compiler.options.mode === 'production') {\n compiler.hooks.done.tap(PLUGIN_NAME, () => {\n console.info('✅ ' + PLUGIN_NAME + ': code-splitting done!')\n })\n }\n },\n\n webpack(compiler) {\n ROOT = process.cwd()\n initUserConfig()\n\n if (compiler.options.mode === 'production') {\n compiler.hooks.done.tap(PLUGIN_NAME, () => {\n console.info('✅ ' + PLUGIN_NAME + ': code-splitting done!')\n })\n }\n },\n },\n {\n name: 'tanstack-router:code-splitter:compile-virtual-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: /tsr-split/,\n },\n handler(code, id) {\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n const normalizedId = normalizePath(fileURLToPath(url))\n return handleCompilingVirtualFile(code, normalizedId)\n },\n },\n\n vite: {\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n },\n {\n name: 'tanstack-router:code-splitter:compile-shared-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: /tsr-shared/,\n },\n handler(code, id) {\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n const normalizedId = normalizePath(fileURLToPath(url))\n const [baseId] = normalizedId.split('?')\n\n if (!baseId) return null\n\n const sharedBindings = sharedBindingsMap.get(baseId)\n if (!sharedBindings || sharedBindings.size === 0) return null\n\n if (debug) console.info('Compiling Shared Module: ', id)\n\n const result = compileCodeSplitSharedRoute({\n code,\n sharedBindings,\n filename: normalizedId,\n })\n\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n\n return result\n },\n },\n\n vite: {\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n },\n ]\n}\n"],"mappings":";;;;;;;;;;;;;;AAgCA,IAAM,cAAc;AACpB,IAAM,4BACJ;;;;;AAYF,IAAM,sCAGF;CACF,OAAO;EACL;GAEE,aAAa,CAAC,oBAAoB,qBAAqB;GACvD,KAAK;GACL,OAAO;GACR;EACD;GAEE,aAAa,CAAC,kBAAkB,iCAAiC;GACjE,KAAK;GACL,OAAO;GACR;EACD;GAEE,aAAa,CAAC,yBAAyB,iCAAiC;GACxE,KAAK;GACL,OAAO;GACR;EACF;CACD,OAAO,CACL;EACE,aAAa,CAAC,QAAQ;EACtB,KAAK;EACL,OAAO;EACR,CACF;CACF;AAED,IAAa,qCAER,UAAU,EAAE,EAAE,EAAE,WAAW,iBAAiB;CAC/C,IAAI,OAAe,QAAQ,KAAK;CAChC,IAAI;CAEJ,SAAS,iBAAiB;AACxB,MAAI,OAAO,YAAY,WACrB,cAAa,SAAS;MAEtB,cAAa,eAAA,UAAU,SAAS,KAAK;;CAGzC,MAAM,eAAA,QAAA,IAAA,aAAwC;CAG9C,MAAM,oCAAoB,IAAI,KAA0B;CAExD,MA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**\n * It is important to familiarize yourself with how the code-splitting works in this plugin.\n * https://github.com/TanStack/router/pull/3355\n */\n\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { logDiff } from '@tanstack/router-utils'\nimport { getConfig, splitGroupingsSchema } from './config'\nimport { resolveHmrHotExpression } from './hmr-hot-expression'\nimport {\n compileCodeSplitReferenceRoute,\n compileCodeSplitSharedRoute,\n compileCodeSplitVirtualRoute,\n computeSharedBindings,\n detectCodeSplitGroupingsFromRoute,\n} from './code-splitter/compilers'\nimport { getReferenceRouteCompilerPlugins } from './code-splitter/plugins/framework-plugins'\nimport {\n defaultCodeSplitGroupings,\n splitRouteIdentNodes,\n tsrShared,\n tsrSplit,\n} from './constants'\nimport { decodeIdentifier } from './code-splitter/path-ids'\nimport { debug, normalizePath } from './utils'\nimport type { CodeSplitGroupings, SplitRouteIdentNodes } from './constants'\nimport type { GetRoutesByFileMapResultValue } from '@tanstack/router-generator'\nimport type { Config } from './config'\nimport type {\n UnpluginFactory,\n TransformResult as UnpluginTransformResult,\n} from 'unplugin'\n\nconst PLUGIN_NAME = 'unplugin:router-code-splitter'\nconst CODE_SPLITTER_PLUGIN_NAME =\n 'tanstack-router:code-splitter:compile-reference-file'\n\ntype TransformationPluginInfo = {\n pluginNames: Array<string>\n pkg: string\n usage: string\n}\n\n/**\n * JSX transformation plugins grouped by framework.\n * These plugins must come AFTER the TanStack Router plugin in the Vite config.\n */\nconst TRANSFORMATION_PLUGINS_BY_FRAMEWORK: Record<\n string,\n Array<TransformationPluginInfo>\n> = {\n react: [\n {\n // Babel-based React plugin\n pluginNames: ['vite:react-babel', 'vite:react-refresh'],\n pkg: '@vitejs/plugin-react',\n usage: 'react()',\n },\n {\n // SWC-based React plugin\n pluginNames: ['vite:react-swc', 'vite:react-swc:resolve-runtime'],\n pkg: '@vitejs/plugin-react-swc',\n usage: 'reactSwc()',\n },\n {\n // OXC-based React plugin (deprecated but should still be handled)\n pluginNames: ['vite:react-oxc:config', 'vite:react-oxc:refresh-runtime'],\n pkg: '@vitejs/plugin-react-oxc',\n usage: 'reactOxc()',\n },\n ],\n solid: [\n {\n pluginNames: ['solid'],\n pkg: 'vite-plugin-solid',\n usage: 'solid()',\n },\n ],\n}\n\nexport const unpluginRouterCodeSplitterFactory: UnpluginFactory<\n Partial<Config | (() => Config)> | undefined\n> = (options = {}, { framework: _framework }) => {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n function initUserConfig() {\n if (typeof options === 'function') {\n userConfig = options()\n } else {\n userConfig = getConfig(options, ROOT)\n }\n }\n const isProduction = process.env.NODE_ENV === 'production'\n // Map from normalized route file path → set of shared binding names.\n // Populated by the reference compiler, consumed by virtual and shared compilers.\n const sharedBindingsMap = new Map<string, Set<string>>()\n\n const getGlobalCodeSplitGroupings = () => {\n return (\n userConfig.codeSplittingOptions?.defaultBehavior ||\n defaultCodeSplitGroupings\n )\n }\n const getShouldSplitFn = () => {\n return userConfig.codeSplittingOptions?.splitBehavior\n }\n\n const handleCompilingReferenceFile = (\n code: string,\n id: string,\n generatorNodeInfo: GetRoutesByFileMapResultValue,\n ): UnpluginTransformResult => {\n if (debug) console.info('Compiling Route: ', id)\n\n const fromCode = detectCodeSplitGroupingsFromRoute({\n code,\n })\n\n if (fromCode.groupings !== undefined) {\n const res = splitGroupingsSchema.safeParse(fromCode.groupings)\n if (!res.success) {\n const message = res.error.errors.map((e) => e.message).join('. ')\n throw new Error(\n `The groupings for the route \"${id}\" are invalid.\\n${message}`,\n )\n }\n }\n\n const userShouldSplitFn = getShouldSplitFn()\n\n const pluginSplitBehavior = userShouldSplitFn?.({\n routeId: generatorNodeInfo.routePath,\n }) as CodeSplitGroupings | undefined\n\n if (pluginSplitBehavior) {\n const res = splitGroupingsSchema.safeParse(pluginSplitBehavior)\n if (!res.success) {\n const message = res.error.errors.map((e) => e.message).join('. ')\n throw new Error(\n `The groupings returned when using \\`splitBehavior\\` for the route \"${id}\" are invalid.\\n${message}`,\n )\n }\n }\n\n const splitGroupings: CodeSplitGroupings =\n fromCode.groupings ?? pluginSplitBehavior ?? getGlobalCodeSplitGroupings()\n\n // Compute shared bindings before compiling the reference route\n const sharedBindings = computeSharedBindings({\n code,\n codeSplitGroupings: splitGroupings,\n })\n if (sharedBindings.size > 0) {\n sharedBindingsMap.set(id, sharedBindings)\n } else {\n sharedBindingsMap.delete(id)\n }\n\n const addHmr =\n (userConfig.codeSplittingOptions?.addHmr ?? true) && !isProduction\n const hmrHotExpression = resolveHmrHotExpression(\n userConfig.plugin?.hmr?.hotExpression,\n )\n\n const compiledReferenceRoute = compileCodeSplitReferenceRoute({\n code,\n codeSplitGroupings: splitGroupings,\n targetFramework: userConfig.target,\n filename: id,\n id,\n deleteNodes: userConfig.codeSplittingOptions?.deleteNodes\n ? new Set(userConfig.codeSplittingOptions.deleteNodes)\n : undefined,\n addHmr,\n hmrHotExpression,\n sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined,\n compilerPlugins: getReferenceRouteCompilerPlugins({\n targetFramework: userConfig.target,\n addHmr,\n hmrHotExpression,\n }),\n })\n\n if (compiledReferenceRoute === null) {\n if (debug) {\n console.info(\n `No changes made to route \"${id}\", skipping code-splitting.`,\n )\n }\n return null\n }\n if (debug) {\n logDiff(code, compiledReferenceRoute.code)\n console.log('Output:\\n', compiledReferenceRoute.code + '\\n\\n')\n }\n\n return compiledReferenceRoute\n }\n\n const handleCompilingVirtualFile = (\n code: string,\n id: string,\n ): UnpluginTransformResult => {\n if (debug) console.info('Splitting Route: ', id)\n\n const [_, ...pathnameParts] = id.split('?')\n\n const searchParams = new URLSearchParams(pathnameParts.join('?'))\n const splitValue = searchParams.get(tsrSplit)\n\n if (!splitValue) {\n throw new Error(\n `The split value for the virtual route \"${id}\" was not found.`,\n )\n }\n\n const rawGrouping = decodeIdentifier(splitValue)\n const grouping = [...new Set(rawGrouping)].filter((p) =>\n splitRouteIdentNodes.includes(p as any),\n ) as Array<SplitRouteIdentNodes>\n\n const baseId = id.split('?')[0]!\n const resolvedSharedBindings = sharedBindingsMap.get(baseId)\n\n const result = compileCodeSplitVirtualRoute({\n code,\n filename: id,\n splitTargets: grouping,\n sharedBindings: resolvedSharedBindings,\n })\n\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n\n return result\n }\n\n const includedCode = [\n 'createFileRoute(',\n 'createRootRoute(',\n 'createRootRouteWithContext(',\n ]\n return [\n {\n name: 'tanstack-router:code-splitter:compile-reference-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: {\n exclude: [tsrSplit, tsrShared],\n // this is necessary for webpack / rspack to avoid matching .html files\n include: /\\.(m|c)?(j|t)sx?$/,\n },\n code: {\n include: includedCode,\n },\n },\n handler(code, id) {\n const normalizedId = normalizePath(id)\n const generatorFileInfo =\n globalThis.TSR_ROUTES_BY_ID_MAP?.get(normalizedId)\n if (\n generatorFileInfo &&\n includedCode.some((included) => code.includes(included))\n ) {\n return handleCompilingReferenceFile(\n code,\n normalizedId,\n generatorFileInfo,\n )\n }\n\n return null\n },\n },\n\n vite: {\n configResolved(config) {\n ROOT = config.root\n initUserConfig()\n\n // Validate plugin order - router must come before JSX transformation plugins\n const routerPluginIndex = config.plugins.findIndex(\n (p) => p.name === CODE_SPLITTER_PLUGIN_NAME,\n )\n\n if (routerPluginIndex === -1) return\n\n const frameworkPlugins =\n TRANSFORMATION_PLUGINS_BY_FRAMEWORK[userConfig.target]\n if (!frameworkPlugins) return\n\n for (const transformPlugin of frameworkPlugins) {\n const transformPluginIndex = config.plugins.findIndex((p) =>\n transformPlugin.pluginNames.includes(p.name),\n )\n\n if (\n transformPluginIndex !== -1 &&\n transformPluginIndex < routerPluginIndex\n ) {\n throw new Error(\n `Plugin order error: '${transformPlugin.pkg}' is placed before '@tanstack/router-plugin'.\\n\\n` +\n `The TanStack Router plugin must come BEFORE JSX transformation plugins.\\n\\n` +\n `Please update your Vite config:\\n\\n` +\n ` plugins: [\\n` +\n ` tanstackRouter(),\\n` +\n ` ${transformPlugin.usage},\\n` +\n ` ]\\n`,\n )\n }\n }\n },\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n\n rspack() {\n ROOT = process.cwd()\n initUserConfig()\n },\n\n webpack() {\n ROOT = process.cwd()\n initUserConfig()\n },\n },\n {\n name: 'tanstack-router:code-splitter:compile-virtual-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: /tsr-split/,\n },\n handler(code, id) {\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n const normalizedId = normalizePath(fileURLToPath(url))\n return handleCompilingVirtualFile(code, normalizedId)\n },\n },\n\n vite: {\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n },\n {\n name: 'tanstack-router:code-splitter:compile-shared-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: /tsr-shared/,\n },\n handler(code, id) {\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n const normalizedId = normalizePath(fileURLToPath(url))\n const [baseId] = normalizedId.split('?')\n\n if (!baseId) return null\n\n const sharedBindings = sharedBindingsMap.get(baseId)\n if (!sharedBindings || sharedBindings.size === 0) return null\n\n if (debug) console.info('Compiling Shared Module: ', id)\n\n const result = compileCodeSplitSharedRoute({\n code,\n sharedBindings,\n filename: normalizedId,\n })\n\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n\n return result\n },\n },\n\n vite: {\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n },\n ]\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,IAAM,4BACJ;;;;;AAYF,IAAM,sCAGF;CACF,OAAO;EACL;GAEE,aAAa,CAAC,oBAAoB,qBAAqB;GACvD,KAAK;GACL,OAAO;GACR;EACD;GAEE,aAAa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;AAC1B,cAAQ,IAAI,aAAa,OAAO,OAAO,OAAO;;AAGhD,YAAO;;IAEV;GAED,MAAM,EACJ,mBAAmB,aAAa;AAC9B,QAAI,WAAW,QAAQ,MAAM,gBAC3B,QAAO,WAAW,OAAO,KAAK,oBAAoB,YAAY;AAEhE,WAAO;MAEV;GACF;EACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
require("../_virtual/_rolldown/runtime.cjs");
|
|
2
2
|
const require_config = require("./config.cjs");
|
|
3
|
+
const require_hmr_hot_expression = require("./hmr-hot-expression.cjs");
|
|
3
4
|
const require_route_hmr_statement = require("./route-hmr-statement.cjs");
|
|
4
5
|
const require_utils = require("./utils.cjs");
|
|
5
6
|
const require_compilers = require("./code-splitter/compilers.cjs");
|
|
@@ -31,17 +32,20 @@ var unpluginRouterHmrFactory = (options = {}) => {
|
|
|
31
32
|
const normalizedId = require_utils.normalizePath(id);
|
|
32
33
|
if (!globalThis.TSR_ROUTES_BY_ID_MAP?.has(normalizedId)) return null;
|
|
33
34
|
if (require_utils.debug) console.info("Adding HMR handling to route ", normalizedId);
|
|
35
|
+
const hmrHotExpression = require_hmr_hot_expression.resolveHmrHotExpression(userConfig.plugin?.hmr?.hotExpression);
|
|
34
36
|
if (userConfig.target === "react") {
|
|
35
37
|
const compiled = require_compilers.compileCodeSplitReferenceRoute({
|
|
36
38
|
code,
|
|
37
39
|
filename: normalizedId,
|
|
38
40
|
id: normalizedId,
|
|
39
41
|
addHmr: true,
|
|
42
|
+
hmrHotExpression,
|
|
40
43
|
codeSplitGroupings: [],
|
|
41
44
|
targetFramework: "react",
|
|
42
45
|
compilerPlugins: require_framework_plugins.getReferenceRouteCompilerPlugins({
|
|
43
46
|
targetFramework: "react",
|
|
44
|
-
addHmr: true
|
|
47
|
+
addHmr: true,
|
|
48
|
+
hmrHotExpression
|
|
45
49
|
})
|
|
46
50
|
});
|
|
47
51
|
if (compiled) {
|
|
@@ -53,7 +57,7 @@ var unpluginRouterHmrFactory = (options = {}) => {
|
|
|
53
57
|
}
|
|
54
58
|
}
|
|
55
59
|
const ast = (0, _tanstack_router_utils.parseAst)({ code });
|
|
56
|
-
ast.program.body.push(require_route_hmr_statement.createRouteHmrStatement([]));
|
|
60
|
+
ast.program.body.push(require_route_hmr_statement.createRouteHmrStatement([], { hotExpression: hmrHotExpression }));
|
|
57
61
|
const result = (0, _tanstack_router_utils.generateFromAst)(ast, {
|
|
58
62
|
sourceMaps: true,
|
|
59
63
|
filename: normalizedId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router-hmr-plugin.cjs","names":[],"sources":["../../../src/core/router-hmr-plugin.ts"],"sourcesContent":["import { generateFromAst, logDiff, parseAst } from '@tanstack/router-utils'\nimport { compileCodeSplitReferenceRoute } from './code-splitter/compilers'\nimport { getReferenceRouteCompilerPlugins } from './code-splitter/plugins/framework-plugins'\nimport { createRouteHmrStatement } from './route-hmr-statement'\nimport { debug, normalizePath } from './utils'\nimport { getConfig } from './config'\nimport type { UnpluginFactory } from 'unplugin'\nimport type { Config } from './config'\n\n/**\n * This plugin adds HMR support for file routes.\n * It is only added to the composed plugin in dev when autoCodeSplitting is disabled, since the code splitting plugin\n * handles HMR for code-split routes itself.\n */\n\nconst includeCode = [\n 'createFileRoute(',\n 'createRootRoute(',\n 'createRootRouteWithContext(',\n]\nexport const unpluginRouterHmrFactory: UnpluginFactory<\n Partial<Config> | undefined\n> = (options = {}) => {\n let ROOT: string = process.cwd()\n let userConfig = options as Config\n\n return {\n name: 'tanstack-router:hmr',\n enforce: 'pre',\n transform: {\n filter: {\n // this is necessary for webpack / rspack to avoid matching .html files\n id: /\\.(m|c)?(j|t)sx?$/,\n code: {\n include: includeCode,\n },\n },\n handler(code, id) {\n const normalizedId = normalizePath(id)\n if (!globalThis.TSR_ROUTES_BY_ID_MAP?.has(normalizedId)) {\n return null\n }\n\n if (debug) console.info('Adding HMR handling to route ', normalizedId)\n\n if (userConfig.target === 'react') {\n const compilerPlugins = getReferenceRouteCompilerPlugins({\n targetFramework: 'react',\n addHmr: true,\n })\n const compiled = compileCodeSplitReferenceRoute({\n code,\n filename: normalizedId,\n id: normalizedId,\n addHmr: true,\n codeSplitGroupings: [],\n targetFramework: 'react',\n compilerPlugins,\n })\n\n if (compiled) {\n if (debug) {\n logDiff(code, compiled.code)\n console.log('Output:\\n', compiled.code + '\\n\\n')\n }\n\n return compiled\n }\n }\n\n const ast = parseAst({ code })\n ast.program.body.push(createRouteHmrStatement([]))\n const result = generateFromAst(ast, {\n sourceMaps: true,\n filename: normalizedId,\n sourceFileName: normalizedId,\n })\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n return result\n },\n },\n vite: {\n configResolved(config) {\n ROOT = config.root\n userConfig = getConfig(options, ROOT)\n },\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"router-hmr-plugin.cjs","names":[],"sources":["../../../src/core/router-hmr-plugin.ts"],"sourcesContent":["import { generateFromAst, logDiff, parseAst } from '@tanstack/router-utils'\nimport { compileCodeSplitReferenceRoute } from './code-splitter/compilers'\nimport { getReferenceRouteCompilerPlugins } from './code-splitter/plugins/framework-plugins'\nimport { createRouteHmrStatement } from './route-hmr-statement'\nimport { debug, normalizePath } from './utils'\nimport { getConfig } from './config'\nimport { resolveHmrHotExpression } from './hmr-hot-expression'\nimport type { UnpluginFactory } from 'unplugin'\nimport type { Config } from './config'\n\n/**\n * This plugin adds HMR support for file routes.\n * It is only added to the composed plugin in dev when autoCodeSplitting is disabled, since the code splitting plugin\n * handles HMR for code-split routes itself.\n */\n\nconst includeCode = [\n 'createFileRoute(',\n 'createRootRoute(',\n 'createRootRouteWithContext(',\n]\nexport const unpluginRouterHmrFactory: UnpluginFactory<\n Partial<Config> | undefined\n> = (options = {}) => {\n let ROOT: string = process.cwd()\n let userConfig = options as Config\n\n return {\n name: 'tanstack-router:hmr',\n enforce: 'pre',\n transform: {\n filter: {\n // this is necessary for webpack / rspack to avoid matching .html files\n id: /\\.(m|c)?(j|t)sx?$/,\n code: {\n include: includeCode,\n },\n },\n handler(code, id) {\n const normalizedId = normalizePath(id)\n if (!globalThis.TSR_ROUTES_BY_ID_MAP?.has(normalizedId)) {\n return null\n }\n\n if (debug) console.info('Adding HMR handling to route ', normalizedId)\n\n const hmrHotExpression = resolveHmrHotExpression(\n userConfig.plugin?.hmr?.hotExpression,\n )\n\n if (userConfig.target === 'react') {\n const compilerPlugins = getReferenceRouteCompilerPlugins({\n targetFramework: 'react',\n addHmr: true,\n hmrHotExpression,\n })\n const compiled = compileCodeSplitReferenceRoute({\n code,\n filename: normalizedId,\n id: normalizedId,\n addHmr: true,\n hmrHotExpression,\n codeSplitGroupings: [],\n targetFramework: 'react',\n compilerPlugins,\n })\n\n if (compiled) {\n if (debug) {\n logDiff(code, compiled.code)\n console.log('Output:\\n', compiled.code + '\\n\\n')\n }\n\n return compiled\n }\n }\n\n const ast = parseAst({ code })\n ast.program.body.push(\n createRouteHmrStatement([], { hotExpression: hmrHotExpression }),\n )\n const result = generateFromAst(ast, {\n sourceMaps: true,\n filename: normalizedId,\n sourceFileName: normalizedId,\n })\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n return result\n },\n },\n vite: {\n configResolved(config) {\n ROOT = config.root\n userConfig = getConfig(options, ROOT)\n },\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,IAAM,cAAc;CAClB;CACA;CACA;CACD;AACD,IAAa,4BAER,UAAU,EAAE,KAAK;CACpB,IAAI,OAAe,QAAQ,KAAK;CAChC,IAAI,aAAa;AAEjB,QAAO;EACL,MAAM;EACN,SAAS;EACT,WAAW;GACT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