@tanstack/router-vite-plugin 1.38.0 → 1.39.2
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/compilers.cjs +2 -124
- package/dist/cjs/compilers.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/esm/compilers.js +2 -124
- package/dist/esm/compilers.js.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/package.json +3 -2
- package/src/compilers.ts +2 -182
- package/src/index.ts +2 -4
package/dist/cjs/compilers.cjs
CHANGED
|
@@ -69,68 +69,7 @@ async function compileFile(opts) {
|
|
|
69
69
|
{
|
|
70
70
|
CallExpression: (path) => {
|
|
71
71
|
if (path.node.callee.type === "Identifier") {
|
|
72
|
-
if (path.node.callee.name === "
|
|
73
|
-
const fn = path.node.arguments[1];
|
|
74
|
-
if (t__namespace.isFunctionExpression(fn) || t__namespace.isArrowFunctionExpression(fn)) {
|
|
75
|
-
if (t__namespace.isBlockStatement(fn.body)) {
|
|
76
|
-
const hasUseServerDirective = fn.body.directives.some((directive) => {
|
|
77
|
-
return directive.value.value === "use server";
|
|
78
|
-
});
|
|
79
|
-
if (!hasUseServerDirective) {
|
|
80
|
-
fn.body.directives.unshift(
|
|
81
|
-
t__namespace.directive(
|
|
82
|
-
t__namespace.directiveLiteral("use server")
|
|
83
|
-
)
|
|
84
|
-
);
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
} else if (t__namespace.isIdentifier(fn) || t__namespace.isCallExpression(fn)) {
|
|
88
|
-
const args = t__namespace.restElement(t__namespace.identifier("args"));
|
|
89
|
-
args.typeAnnotation = t__namespace.tsTypeAnnotation(
|
|
90
|
-
t__namespace.tsTypeReference(
|
|
91
|
-
t__namespace.identifier("Parameters"),
|
|
92
|
-
t__namespace.tsTypeParameterInstantiation([
|
|
93
|
-
t__namespace.tsIndexedAccessType(
|
|
94
|
-
t__namespace.tsTypeReference(
|
|
95
|
-
t__namespace.identifier("Parameters"),
|
|
96
|
-
t__namespace.tsTypeParameterInstantiation([
|
|
97
|
-
t__namespace.tsTypeQuery(
|
|
98
|
-
t__namespace.identifier("createServerFn")
|
|
99
|
-
)
|
|
100
|
-
])
|
|
101
|
-
),
|
|
102
|
-
t__namespace.tsLiteralType(t__namespace.numericLiteral(1))
|
|
103
|
-
)
|
|
104
|
-
])
|
|
105
|
-
)
|
|
106
|
-
);
|
|
107
|
-
const wrappedFn = t__namespace.arrowFunctionExpression(
|
|
108
|
-
[args],
|
|
109
|
-
t__namespace.blockStatement(
|
|
110
|
-
[
|
|
111
|
-
t__namespace.returnStatement(
|
|
112
|
-
t__namespace.callExpression(
|
|
113
|
-
t__namespace.memberExpression(
|
|
114
|
-
fn,
|
|
115
|
-
t__namespace.identifier("apply")
|
|
116
|
-
),
|
|
117
|
-
[
|
|
118
|
-
t__namespace.identifier("this"),
|
|
119
|
-
t__namespace.identifier("args")
|
|
120
|
-
]
|
|
121
|
-
)
|
|
122
|
-
)
|
|
123
|
-
],
|
|
124
|
-
[
|
|
125
|
-
t__namespace.directive(
|
|
126
|
-
t__namespace.directiveLiteral("use server")
|
|
127
|
-
)
|
|
128
|
-
]
|
|
129
|
-
)
|
|
130
|
-
);
|
|
131
|
-
path.node.arguments[1] = wrappedFn;
|
|
132
|
-
}
|
|
133
|
-
} else if (path.node.callee.name === "createRoute" || path.node.callee.name === "createFileRoute") {
|
|
72
|
+
if (path.node.callee.name === "createRoute" || path.node.callee.name === "createFileRoute") {
|
|
134
73
|
if (path.parentPath.node.type === "CallExpression") {
|
|
135
74
|
const options = resolveIdentifier(
|
|
136
75
|
path,
|
|
@@ -280,68 +219,7 @@ async function splitFile(opts) {
|
|
|
280
219
|
{
|
|
281
220
|
CallExpression: (path) => {
|
|
282
221
|
if (path.node.callee.type === "Identifier") {
|
|
283
|
-
if (path.node.callee.name === "
|
|
284
|
-
const fn = path.node.arguments[1];
|
|
285
|
-
if (t__namespace.isFunctionExpression(fn) || t__namespace.isArrowFunctionExpression(fn)) {
|
|
286
|
-
if (t__namespace.isBlockStatement(fn.body)) {
|
|
287
|
-
const hasUseServerDirective = fn.body.directives.some((directive) => {
|
|
288
|
-
return directive.value.value === "use server";
|
|
289
|
-
});
|
|
290
|
-
if (!hasUseServerDirective) {
|
|
291
|
-
fn.body.directives.unshift(
|
|
292
|
-
t__namespace.directive(
|
|
293
|
-
t__namespace.directiveLiteral("use server")
|
|
294
|
-
)
|
|
295
|
-
);
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
} else if (t__namespace.isIdentifier(fn) || t__namespace.isCallExpression(fn)) {
|
|
299
|
-
const args = t__namespace.restElement(t__namespace.identifier("args"));
|
|
300
|
-
args.typeAnnotation = t__namespace.tsTypeAnnotation(
|
|
301
|
-
t__namespace.tsTypeReference(
|
|
302
|
-
t__namespace.identifier("Parameters"),
|
|
303
|
-
t__namespace.tsTypeParameterInstantiation([
|
|
304
|
-
t__namespace.tsIndexedAccessType(
|
|
305
|
-
t__namespace.tsTypeReference(
|
|
306
|
-
t__namespace.identifier("Parameters"),
|
|
307
|
-
t__namespace.tsTypeParameterInstantiation([
|
|
308
|
-
t__namespace.tsTypeQuery(
|
|
309
|
-
t__namespace.identifier("createServerFn")
|
|
310
|
-
)
|
|
311
|
-
])
|
|
312
|
-
),
|
|
313
|
-
t__namespace.tsLiteralType(t__namespace.numericLiteral(1))
|
|
314
|
-
)
|
|
315
|
-
])
|
|
316
|
-
)
|
|
317
|
-
);
|
|
318
|
-
const wrappedFn = t__namespace.arrowFunctionExpression(
|
|
319
|
-
[args],
|
|
320
|
-
t__namespace.blockStatement(
|
|
321
|
-
[
|
|
322
|
-
t__namespace.returnStatement(
|
|
323
|
-
t__namespace.callExpression(
|
|
324
|
-
t__namespace.memberExpression(
|
|
325
|
-
fn,
|
|
326
|
-
t__namespace.identifier("apply")
|
|
327
|
-
),
|
|
328
|
-
[
|
|
329
|
-
t__namespace.identifier("this"),
|
|
330
|
-
t__namespace.identifier("args")
|
|
331
|
-
]
|
|
332
|
-
)
|
|
333
|
-
)
|
|
334
|
-
],
|
|
335
|
-
[
|
|
336
|
-
t__namespace.directive(
|
|
337
|
-
t__namespace.directiveLiteral("use server")
|
|
338
|
-
)
|
|
339
|
-
]
|
|
340
|
-
)
|
|
341
|
-
);
|
|
342
|
-
path.node.arguments[1] = wrappedFn;
|
|
343
|
-
}
|
|
344
|
-
} else if (path.node.callee.name === "createRoute" || path.node.callee.name === "createFileRoute") {
|
|
222
|
+
if (path.node.callee.name === "createRoute" || path.node.callee.name === "createFileRoute") {
|
|
345
223
|
if (path.parentPath.node.type === "CallExpression") {
|
|
346
224
|
const options = resolveIdentifier(
|
|
347
225
|
path,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compilers.cjs","sources":["../../src/compilers.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport * as template from '@babel/template'\nimport * as babel from '@babel/core'\nimport { splitPrefix } from './constants'\nimport { eliminateUnreferencedIdentifiers } from './eliminateUnreferencedIdentifiers'\n\ntype SplitModulesById = Record<\n string,\n { id: string; node: t.FunctionExpression }\n>\n\ninterface State {\n filename: string\n opts: {\n minify: boolean\n root: string\n }\n imported: Record<string, boolean>\n refs: Set<any>\n serverIndex: number\n splitIndex: number\n splitModulesById: SplitModulesById\n}\n\nexport type CompileFn = (compileOpts: {\n code: string\n filename: string\n getBabelConfig: () => { plugins: Array<any> }\n}) => Promise<{\n code: string\n map: any\n}>\n\nexport function makeCompile(makeOpts: { root: string }) {\n return async (opts: {\n code: string\n filename: string\n getBabelConfig: () => { plugins: Array<any> }\n }): Promise<{\n code: string\n map: any\n }> => {\n const res = await babel.transform(opts.code, {\n plugins: [\n ['@babel/plugin-syntax-jsx', {}],\n [\n '@babel/plugin-syntax-typescript',\n {\n isTSX: true,\n },\n ],\n ...opts.getBabelConfig().plugins,\n ],\n root: makeOpts.root,\n filename: opts.filename,\n sourceMaps: true,\n })\n\n if (res?.code) {\n return {\n code: res.code,\n map: res.map,\n }\n }\n\n return {\n code: opts.code,\n map: null,\n }\n }\n}\n\nexport async function compileFile(opts: {\n code: string\n compile: CompileFn\n filename: string\n}) {\n return await opts.compile({\n code: opts.code,\n filename: opts.filename,\n getBabelConfig: () => ({\n plugins: [\n [\n {\n visitor: {\n Program: {\n enter(programPath: babel.NodePath<t.Program>, state: State) {\n const splitUrl = `${splitPrefix}:${opts.filename}?${splitPrefix}`\n\n programPath.traverse(\n {\n CallExpression: (path) => {\n if (path.node.callee.type === 'Identifier') {\n if (path.node.callee.name === 'createServerFn') {\n // If the function at createServerFn(_, MyFunc) doesn't have a\n // 'use server' directive at the top of the function scope,\n // then add it.\n\n const fn = path.node.arguments[1]\n\n if (\n t.isFunctionExpression(fn) ||\n t.isArrowFunctionExpression(fn)\n ) {\n if (t.isBlockStatement(fn.body)) {\n const hasUseServerDirective =\n fn.body.directives.some((directive) => {\n return (\n directive.value.value === 'use server'\n )\n })\n\n if (!hasUseServerDirective) {\n fn.body.directives.unshift(\n t.directive(\n t.directiveLiteral('use server'),\n ),\n )\n }\n }\n } else if (\n t.isIdentifier(fn) ||\n t.isCallExpression(fn)\n ) {\n // A function was passed to createServerFn in the form of an\n // identifier or a call expression that returns a function.\n\n // We wrap the identifier/call expression in a function\n // expression that accepts the same arguments as the original\n // function with the \"use server\" directive at the top of the\n // function scope.\n\n const args = t.restElement(t.identifier('args'))\n\n // Annotate args with the type:\n // Parameters<Parameters<typeof createServerFn>[1]>\n\n args.typeAnnotation = t.tsTypeAnnotation(\n t.tsTypeReference(\n t.identifier('Parameters'),\n t.tsTypeParameterInstantiation([\n t.tsIndexedAccessType(\n t.tsTypeReference(\n t.identifier('Parameters'),\n t.tsTypeParameterInstantiation([\n t.tsTypeQuery(\n t.identifier('createServerFn'),\n ),\n ]),\n ),\n t.tsLiteralType(t.numericLiteral(1)),\n ),\n ]),\n ),\n )\n\n const wrappedFn = t.arrowFunctionExpression(\n [args],\n t.blockStatement(\n [\n t.returnStatement(\n t.callExpression(\n t.memberExpression(\n fn,\n t.identifier('apply'),\n ),\n [\n t.identifier('this'),\n t.identifier('args'),\n ],\n ),\n ),\n ],\n [\n t.directive(\n t.directiveLiteral('use server'),\n ),\n ],\n ),\n )\n\n path.node.arguments[1] = wrappedFn\n }\n } else if (\n path.node.callee.name === 'createRoute' ||\n path.node.callee.name === 'createFileRoute'\n ) {\n if (\n path.parentPath.node.type === 'CallExpression'\n ) {\n const options = resolveIdentifier(\n path,\n path.parentPath.node.arguments[0],\n )\n\n let found = false\n\n const hasImportedOrDefinedIdentifier = (\n name: string,\n ) => {\n return programPath.scope.hasBinding(name)\n }\n\n if (t.isObjectExpression(options)) {\n options.properties.forEach((prop) => {\n if (t.isObjectProperty(prop)) {\n if (t.isIdentifier(prop.key)) {\n if (prop.key.name === 'component') {\n const value = prop.value\n\n if (t.isIdentifier(value)) {\n removeIdentifierLiteral(path, value)\n }\n\n // Prepend the import statement to the program along with the importer function\n // Check to see if lazyRouteComponent is already imported before attempting\n // to import it again\n\n if (\n !hasImportedOrDefinedIdentifier(\n 'lazyRouteComponent',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `import { lazyRouteComponent } from '@tanstack/react-router'`,\n )() as t.Statement,\n ])\n }\n\n if (\n !hasImportedOrDefinedIdentifier(\n '$$splitComponentImporter',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `const $$splitComponentImporter = () => import('${splitUrl}')`,\n )() as t.Statement,\n ])\n }\n\n prop.value = template.expression(\n `lazyRouteComponent($$splitComponentImporter, 'component')`,\n )() as any\n\n programPath.pushContainer('body', [\n template.smart(\n `function DummyComponent() { return null }`,\n )() as t.Statement,\n ])\n\n found = true\n } else if (prop.key.name === 'loader') {\n const value = prop.value\n\n if (t.isIdentifier(value)) {\n removeIdentifierLiteral(path, value)\n }\n\n // Prepend the import statement to the program along with the importer function\n\n if (\n !hasImportedOrDefinedIdentifier(\n 'lazyFn',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `import { lazyFn } from '@tanstack/react-router'`,\n )() as t.Statement,\n ])\n }\n\n if (\n !hasImportedOrDefinedIdentifier(\n '$$splitLoaderImporter',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `const $$splitLoaderImporter = () => import('${splitUrl}')`,\n )() as t.Statement,\n ])\n }\n\n prop.value = template.expression(\n `lazyFn($$splitLoaderImporter, 'loader')`,\n )() as any\n\n found = true\n }\n }\n }\n\n programPath.scope.crawl()\n })\n }\n\n if (found as boolean) {\n programPath.pushContainer('body', [\n template.smart(\n `function TSR_Dummy_Component() {}`,\n )() as t.Statement,\n ])\n }\n }\n }\n }\n },\n },\n state,\n )\n\n eliminateUnreferencedIdentifiers(programPath)\n },\n },\n },\n },\n {\n root: process.cwd(),\n minify: process.env.NODE_ENV === 'production',\n },\n ],\n ].filter(Boolean),\n }),\n })\n}\n\n// Reusable function to get literal value or resolve variable to literal\nfunction resolveIdentifier(path: any, node: any) {\n if (t.isIdentifier(node)) {\n const binding = path.scope.getBinding(node.name)\n if (\n binding\n // && binding.kind === 'const'\n ) {\n const declarator = binding.path.node\n if (t.isObjectExpression(declarator.init)) {\n return declarator.init\n } else if (t.isFunctionDeclaration(declarator.init)) {\n return declarator.init\n }\n }\n return undefined\n }\n\n return node\n}\n\nfunction removeIdentifierLiteral(path: any, node: any) {\n if (t.isIdentifier(node)) {\n const binding = path.scope.getBinding(node.name)\n if (binding) {\n binding.path.remove()\n }\n }\n}\n\nconst splitNodeTypes = ['component', 'loader'] as const\ntype SplitNodeType = (typeof splitNodeTypes)[number]\n\nexport async function splitFile(opts: {\n code: string\n compile: CompileFn\n filename: string\n // ref: string\n}) {\n return await opts.compile({\n code: opts.code,\n filename: opts.filename,\n getBabelConfig: () => ({\n plugins: [\n [\n {\n visitor: {\n Program: {\n enter(programPath: babel.NodePath<t.Program>, state: State) {\n const splitNodesByType: Record<\n SplitNodeType,\n t.Node | undefined\n > = {\n component: undefined,\n loader: undefined,\n }\n\n // Find the node\n programPath.traverse(\n {\n CallExpression: (path) => {\n if (path.node.callee.type === 'Identifier') {\n if (path.node.callee.name === 'createServerFn') {\n // If the function at createServerFn(_, MyFunc) doesn't have a\n // 'use server' directive at the top of the function scope,\n // then add it.\n\n const fn = path.node.arguments[1]\n\n if (\n t.isFunctionExpression(fn) ||\n t.isArrowFunctionExpression(fn)\n ) {\n if (t.isBlockStatement(fn.body)) {\n const hasUseServerDirective =\n fn.body.directives.some((directive) => {\n return (\n directive.value.value === 'use server'\n )\n })\n\n if (!hasUseServerDirective) {\n fn.body.directives.unshift(\n t.directive(\n t.directiveLiteral('use server'),\n ),\n )\n }\n }\n } else if (\n t.isIdentifier(fn) ||\n t.isCallExpression(fn)\n ) {\n // A function was passed to createServerFn in the form of an\n // identifier or a call expression that returns a function.\n\n // We wrap the identifier/call expression in a function\n // expression that accepts the same arguments as the original\n // function with the \"use server\" directive at the top of the\n // function scope.\n\n const args = t.restElement(t.identifier('args'))\n\n // Annotate args with the type:\n // Parameters<Parameters<typeof createServerFn>[1]>\n\n args.typeAnnotation = t.tsTypeAnnotation(\n t.tsTypeReference(\n t.identifier('Parameters'),\n t.tsTypeParameterInstantiation([\n t.tsIndexedAccessType(\n t.tsTypeReference(\n t.identifier('Parameters'),\n t.tsTypeParameterInstantiation([\n t.tsTypeQuery(\n t.identifier('createServerFn'),\n ),\n ]),\n ),\n t.tsLiteralType(t.numericLiteral(1)),\n ),\n ]),\n ),\n )\n\n const wrappedFn = t.arrowFunctionExpression(\n [args],\n t.blockStatement(\n [\n t.returnStatement(\n t.callExpression(\n t.memberExpression(\n fn,\n t.identifier('apply'),\n ),\n [\n t.identifier('this'),\n t.identifier('args'),\n ],\n ),\n ),\n ],\n [\n t.directive(\n t.directiveLiteral('use server'),\n ),\n ],\n ),\n )\n\n path.node.arguments[1] = wrappedFn\n }\n } else if (\n path.node.callee.name === 'createRoute' ||\n path.node.callee.name === 'createFileRoute'\n ) {\n if (\n path.parentPath.node.type === 'CallExpression'\n ) {\n const options = resolveIdentifier(\n path,\n path.parentPath.node.arguments[0],\n )\n\n if (t.isObjectExpression(options)) {\n options.properties.forEach((prop) => {\n if (t.isObjectProperty(prop)) {\n splitNodeTypes.forEach((type) => {\n if (t.isIdentifier(prop.key)) {\n if (prop.key.name === type) {\n splitNodesByType[type] = prop.value\n }\n }\n })\n }\n })\n\n // Remove all of the options\n options.properties = []\n }\n }\n }\n }\n },\n },\n state,\n )\n\n splitNodeTypes.forEach((splitType) => {\n let splitNode = splitNodesByType[splitType]\n\n if (!splitNode) {\n return\n }\n\n while (t.isIdentifier(splitNode)) {\n const binding = programPath.scope.getBinding(\n splitNode.name,\n )\n splitNode = binding?.path.node\n }\n\n // Add the node to the program\n if (splitNode) {\n if (t.isFunctionDeclaration(splitNode)) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n t.functionExpression(\n splitNode.id || null, // Anonymize the function expression\n splitNode.params,\n splitNode.body,\n splitNode.generator,\n splitNode.async,\n ),\n ),\n ]),\n )\n } else if (\n t.isFunctionExpression(splitNode) ||\n t.isArrowFunctionExpression(splitNode)\n ) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n splitNode as any,\n ),\n ]),\n )\n } else if (t.isImportSpecifier(splitNode)) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n splitNode.local,\n ),\n ]),\n )\n } else {\n console.info(splitNode)\n throw new Error(\n `Unexpected splitNode type ☝️: ${splitNode.type}`,\n )\n }\n }\n\n // If the splitNode exists at the top of the program\n // then we need to remove that copy\n programPath.node.body = programPath.node.body.filter(\n (node) => {\n return node !== splitNode\n },\n )\n\n // Export the node\n programPath.pushContainer('body', [\n t.exportNamedDeclaration(null, [\n t.exportSpecifier(\n t.identifier(splitType),\n t.identifier(splitType),\n ),\n ]),\n ])\n })\n\n // convert exports to imports from the original file\n programPath.traverse({\n ExportNamedDeclaration(path) {\n // e.g. export const x = 1 or export { x }\n // becomes\n // import { x } from '${opts.id}'\n\n if (path.node.declaration) {\n if (t.isVariableDeclaration(path.node.declaration)) {\n path.replaceWith(\n t.importDeclaration(\n path.node.declaration.declarations.map((decl) =>\n t.importSpecifier(\n t.identifier((decl.id as any).name),\n t.identifier((decl.id as any).name),\n ),\n ),\n t.stringLiteral(\n opts.filename.split(\n `?${splitPrefix}`,\n )[0] as string,\n ),\n ),\n )\n }\n }\n },\n })\n\n eliminateUnreferencedIdentifiers(programPath)\n },\n },\n },\n },\n {\n root: process.cwd(),\n minify: process.env.NODE_ENV === 'production',\n },\n ],\n ].filter(Boolean),\n }),\n })\n}\n"],"names":["babel","splitPrefix","t","template","eliminateUnreferencedIdentifiers"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAiCO,SAAS,YAAY,UAA4B;AACtD,SAAO,OAAO,SAOR;AACJ,UAAM,MAAM,MAAMA,iBAAM,UAAU,KAAK,MAAM;AAAA,MAC3C,SAAS;AAAA,QACP,CAAC,4BAA4B,CAAA,CAAE;AAAA,QAC/B;AAAA,UACE;AAAA,UACA;AAAA,YACE,OAAO;AAAA,UACT;AAAA,QACF;AAAA,QACA,GAAG,KAAK,eAAA,EAAiB;AAAA,MAC3B;AAAA,MACA,MAAM,SAAS;AAAA,MACf,UAAU,KAAK;AAAA,MACf,YAAY;AAAA,IAAA,CACb;AAED,QAAI,2BAAK,MAAM;AACN,aAAA;AAAA,QACL,MAAM,IAAI;AAAA,QACV,KAAK,IAAI;AAAA,MAAA;AAAA,IAEb;AAEO,WAAA;AAAA,MACL,MAAM,KAAK;AAAA,MACX,KAAK;AAAA,IAAA;AAAA,EACP;AAEJ;AAEA,eAAsB,YAAY,MAI/B;AACM,SAAA,MAAM,KAAK,QAAQ;AAAA,IACxB,MAAM,KAAK;AAAA,IACX,UAAU,KAAK;AAAA,IACf,g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AA,0BACtBA,aAAE,WAAW,SAAS;AAAA,wBACxB;AAAA,sBAAA,CACD;AAAA,oBAAA,CACF;AAAA,kBAAA,CACF;AAGD,8BAAY,SAAS;AAAA,oBACnB,uBAAuB,MAAM;AAKvB,0BAAA,KAAK,KAAK,aAAa;AACzB,4BAAIA,aAAE,sBAAsB,KAAK,KAAK,WAAW,GAAG;AAC7C,+BAAA;AAAA,4BACHA,aAAE;AAAA,8BACA,KAAK,KAAK,YAAY,aAAa;AAAA,gCAAI,CAAC,SACtCA,aAAE;AAAA,kCACAA,aAAE,WAAY,KAAK,GAAW,IAAI;AAAA,kCAClCA,aAAE,WAAY,KAAK,GAAW,IAAI;AAAA,gCACpC;AAAA,8BACF;AAAA,8BACAA,aAAE;AAAA,gCACA,KAAK,SAAS;AAAA,kCACZ,IAAID,UAAAA,WAAW;AAAA,kCACf,CAAC;AAAA,8BACL;AAAA,4BACF;AAAA,0BAAA;AAAA,wBAEJ;AAAA,sBACF;AAAA,oBACF;AAAA,kBAAA,CACD;AAEDG,mDAAA,iCAAiC,WAAW;AAAA,gBAC9C;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAAA,UACA;AAAA,YACE,MAAM,QAAQ,IAAI;AAAA,YAClB,QAAQ,QAAQ,IAAI,aAAa;AAAA,UACnC;AAAA,QACF;AAAA,MAAA,EACA,OAAO,OAAO;AAAA,IAAA;AAAA,EAClB,CACD;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"compilers.cjs","sources":["../../src/compilers.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport * as template from '@babel/template'\nimport * as babel from '@babel/core'\nimport { splitPrefix } from './constants'\nimport { eliminateUnreferencedIdentifiers } from './eliminateUnreferencedIdentifiers'\n\ntype SplitModulesById = Record<\n string,\n { id: string; node: t.FunctionExpression }\n>\n\ninterface State {\n filename: string\n opts: {\n minify: boolean\n root: string\n }\n imported: Record<string, boolean>\n refs: Set<any>\n serverIndex: number\n splitIndex: number\n splitModulesById: SplitModulesById\n}\n\nexport type CompileFn = (compileOpts: {\n code: string\n filename: string\n getBabelConfig: () => { plugins: Array<any> }\n}) => Promise<{\n code: string\n map: any\n}>\n\nexport function makeCompile(makeOpts: { root: string }) {\n return async (opts: {\n code: string\n filename: string\n getBabelConfig: () => { plugins: Array<any> }\n }): Promise<{\n code: string\n map: any\n }> => {\n const res = await babel.transform(opts.code, {\n plugins: [\n ['@babel/plugin-syntax-jsx', {}],\n [\n '@babel/plugin-syntax-typescript',\n {\n isTSX: true,\n },\n ],\n ...opts.getBabelConfig().plugins,\n ],\n root: makeOpts.root,\n filename: opts.filename,\n sourceMaps: true,\n })\n\n if (res?.code) {\n return {\n code: res.code,\n map: res.map,\n }\n }\n\n return {\n code: opts.code,\n map: null,\n }\n }\n}\n\nexport async function compileFile(opts: {\n code: string\n compile: CompileFn\n filename: string\n}) {\n return await opts.compile({\n code: opts.code,\n filename: opts.filename,\n getBabelConfig: () => ({\n plugins: [\n [\n {\n visitor: {\n Program: {\n enter(programPath: babel.NodePath<t.Program>, state: State) {\n const splitUrl = `${splitPrefix}:${opts.filename}?${splitPrefix}`\n\n programPath.traverse(\n {\n CallExpression: (path) => {\n if (path.node.callee.type === 'Identifier') {\n if (\n path.node.callee.name === 'createRoute' ||\n path.node.callee.name === 'createFileRoute'\n ) {\n if (\n path.parentPath.node.type === 'CallExpression'\n ) {\n const options = resolveIdentifier(\n path,\n path.parentPath.node.arguments[0],\n )\n\n let found = false\n\n const hasImportedOrDefinedIdentifier = (\n name: string,\n ) => {\n return programPath.scope.hasBinding(name)\n }\n\n if (t.isObjectExpression(options)) {\n options.properties.forEach((prop) => {\n if (t.isObjectProperty(prop)) {\n if (t.isIdentifier(prop.key)) {\n if (prop.key.name === 'component') {\n const value = prop.value\n\n if (t.isIdentifier(value)) {\n removeIdentifierLiteral(path, value)\n }\n\n // Prepend the import statement to the program along with the importer function\n // Check to see if lazyRouteComponent is already imported before attempting\n // to import it again\n\n if (\n !hasImportedOrDefinedIdentifier(\n 'lazyRouteComponent',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `import { lazyRouteComponent } from '@tanstack/react-router'`,\n )() as t.Statement,\n ])\n }\n\n if (\n !hasImportedOrDefinedIdentifier(\n '$$splitComponentImporter',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `const $$splitComponentImporter = () => import('${splitUrl}')`,\n )() as t.Statement,\n ])\n }\n\n prop.value = template.expression(\n `lazyRouteComponent($$splitComponentImporter, 'component')`,\n )() as any\n\n programPath.pushContainer('body', [\n template.smart(\n `function DummyComponent() { return null }`,\n )() as t.Statement,\n ])\n\n found = true\n } else if (prop.key.name === 'loader') {\n const value = prop.value\n\n if (t.isIdentifier(value)) {\n removeIdentifierLiteral(path, value)\n }\n\n // Prepend the import statement to the program along with the importer function\n\n if (\n !hasImportedOrDefinedIdentifier(\n 'lazyFn',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `import { lazyFn } from '@tanstack/react-router'`,\n )() as t.Statement,\n ])\n }\n\n if (\n !hasImportedOrDefinedIdentifier(\n '$$splitLoaderImporter',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `const $$splitLoaderImporter = () => import('${splitUrl}')`,\n )() as t.Statement,\n ])\n }\n\n prop.value = template.expression(\n `lazyFn($$splitLoaderImporter, 'loader')`,\n )() as any\n\n found = true\n }\n }\n }\n\n programPath.scope.crawl()\n })\n }\n\n if (found as boolean) {\n programPath.pushContainer('body', [\n template.smart(\n `function TSR_Dummy_Component() {}`,\n )() as t.Statement,\n ])\n }\n }\n }\n }\n },\n },\n state,\n )\n\n eliminateUnreferencedIdentifiers(programPath)\n },\n },\n },\n },\n {\n root: process.cwd(),\n minify: process.env.NODE_ENV === 'production',\n },\n ],\n ].filter(Boolean),\n }),\n })\n}\n\n// Reusable function to get literal value or resolve variable to literal\nfunction resolveIdentifier(path: any, node: any) {\n if (t.isIdentifier(node)) {\n const binding = path.scope.getBinding(node.name)\n if (\n binding\n // && binding.kind === 'const'\n ) {\n const declarator = binding.path.node\n if (t.isObjectExpression(declarator.init)) {\n return declarator.init\n } else if (t.isFunctionDeclaration(declarator.init)) {\n return declarator.init\n }\n }\n return undefined\n }\n\n return node\n}\n\nfunction removeIdentifierLiteral(path: any, node: any) {\n if (t.isIdentifier(node)) {\n const binding = path.scope.getBinding(node.name)\n if (binding) {\n binding.path.remove()\n }\n }\n}\n\nconst splitNodeTypes = ['component', 'loader'] as const\ntype SplitNodeType = (typeof splitNodeTypes)[number]\n\nexport async function splitFile(opts: {\n code: string\n compile: CompileFn\n filename: string\n // ref: string\n}) {\n return await opts.compile({\n code: opts.code,\n filename: opts.filename,\n getBabelConfig: () => ({\n plugins: [\n [\n {\n visitor: {\n Program: {\n enter(programPath: babel.NodePath<t.Program>, state: State) {\n const splitNodesByType: Record<\n SplitNodeType,\n t.Node | undefined\n > = {\n component: undefined,\n loader: undefined,\n }\n\n // Find the node\n programPath.traverse(\n {\n CallExpression: (path) => {\n if (path.node.callee.type === 'Identifier') {\n if (\n path.node.callee.name === 'createRoute' ||\n path.node.callee.name === 'createFileRoute'\n ) {\n if (\n path.parentPath.node.type === 'CallExpression'\n ) {\n const options = resolveIdentifier(\n path,\n path.parentPath.node.arguments[0],\n )\n\n if (t.isObjectExpression(options)) {\n options.properties.forEach((prop) => {\n if (t.isObjectProperty(prop)) {\n splitNodeTypes.forEach((type) => {\n if (t.isIdentifier(prop.key)) {\n if (prop.key.name === type) {\n splitNodesByType[type] = prop.value\n }\n }\n })\n }\n })\n\n // Remove all of the options\n options.properties = []\n }\n }\n }\n }\n },\n },\n state,\n )\n\n splitNodeTypes.forEach((splitType) => {\n let splitNode = splitNodesByType[splitType]\n\n if (!splitNode) {\n return\n }\n\n while (t.isIdentifier(splitNode)) {\n const binding = programPath.scope.getBinding(\n splitNode.name,\n )\n splitNode = binding?.path.node\n }\n\n // Add the node to the program\n if (splitNode) {\n if (t.isFunctionDeclaration(splitNode)) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n t.functionExpression(\n splitNode.id || null, // Anonymize the function expression\n splitNode.params,\n splitNode.body,\n splitNode.generator,\n splitNode.async,\n ),\n ),\n ]),\n )\n } else if (\n t.isFunctionExpression(splitNode) ||\n t.isArrowFunctionExpression(splitNode)\n ) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n splitNode as any,\n ),\n ]),\n )\n } else if (t.isImportSpecifier(splitNode)) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n splitNode.local,\n ),\n ]),\n )\n } else {\n console.info(splitNode)\n throw new Error(\n `Unexpected splitNode type ☝️: ${splitNode.type}`,\n )\n }\n }\n\n // If the splitNode exists at the top of the program\n // then we need to remove that copy\n programPath.node.body = programPath.node.body.filter(\n (node) => {\n return node !== splitNode\n },\n )\n\n // Export the node\n programPath.pushContainer('body', [\n t.exportNamedDeclaration(null, [\n t.exportSpecifier(\n t.identifier(splitType),\n t.identifier(splitType),\n ),\n ]),\n ])\n })\n\n // convert exports to imports from the original file\n programPath.traverse({\n ExportNamedDeclaration(path) {\n // e.g. export const x = 1 or export { x }\n // becomes\n // import { x } from '${opts.id}'\n\n if (path.node.declaration) {\n if (t.isVariableDeclaration(path.node.declaration)) {\n path.replaceWith(\n t.importDeclaration(\n path.node.declaration.declarations.map((decl) =>\n t.importSpecifier(\n t.identifier((decl.id as any).name),\n t.identifier((decl.id as any).name),\n ),\n ),\n t.stringLiteral(\n opts.filename.split(\n `?${splitPrefix}`,\n )[0] as string,\n ),\n ),\n )\n }\n }\n },\n })\n\n eliminateUnreferencedIdentifiers(programPath)\n },\n },\n },\n },\n {\n root: process.cwd(),\n minify: process.env.NODE_ENV === 'production',\n },\n ],\n ].filter(Boolean),\n }),\n })\n}\n"],"names":["babel","splitPrefix","t","template","eliminateUnreferencedIdentifiers"],"mappings":";;;;;;;;;;;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,cAAc,QAAQ;AAAA,sBAChCA,aAAE,uBAAuB,MAAM;AAAA,wBAC7BA,aAAE;AAAA,0BACAA,aAAE,WAAW,SAAS;AAAA,0BACtBA,aAAE,WAAW,SAAS;AAAA,wBACxB;AAAA,sBAAA,CACD;AAAA,oBAAA,CACF;AAAA,kBAAA,CACF;AAGD,8BAAY,SAAS;AAAA,oBACnB,uBAAuB,MAAM;AAKvB,0BAAA,KAAK,KAAK,aAAa;AACzB,4BAAIA,aAAE,sBAAsB,KAAK,KAAK,WAAW,GAAG;AAC7C,+BAAA;AAAA,4BACHA,aAAE;AAAA,8BACA,KAAK,KAAK,YAAY,aAAa;AAAA,gCAAI,CAAC,SACtCA,aAAE;AAAA,kCACAA,aAAE,WAAY,KAAK,GAAW,IAAI;AAAA,kCAClCA,aAAE,WAAY,KAAK,GAAW,IAAI;AAAA,gCACpC;AAAA,8BACF;AAAA,8BACAA,aAAE;AAAA,gCACA,KAAK,SAAS;AAAA,kCACZ,IAAID,UAAAA,WAAW;AAAA,kCACf,CAAC;AAAA,8BACL;AAAA,4BACF;AAAA,0BAAA;AAAA,wBAEJ;AAAA,sBACF;AAAA,oBACF;AAAA,kBAAA,CACD;AAEDG,mDAAA,iCAAiC,WAAW;AAAA,gBAC9C;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAAA,UACA;AAAA,YACE,MAAM,QAAQ,IAAI;AAAA,YAClB,QAAQ,QAAQ,IAAI,aAAa;AAAA,UACnC;AAAA,QACF;AAAA,MAAA,EACA,OAAO,OAAO;AAAA,IAAA;AAAA,EAClB,CACD;AACH;;;;"}
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -142,7 +142,7 @@ function TanStackRouterViteCodeSplitter(inlineConfig = {}) {
|
|
|
142
142
|
if (debug)
|
|
143
143
|
console.info("");
|
|
144
144
|
return compiled;
|
|
145
|
-
} else if (fileIsInRoutesDirectory(id, userConfig.routesDirectory) && (code.includes("createRoute(") || code.includes("createFileRoute("))
|
|
145
|
+
} else if (fileIsInRoutesDirectory(id, userConfig.routesDirectory) && (code.includes("createRoute(") || code.includes("createFileRoute("))) {
|
|
146
146
|
if (code.includes("@react-refresh")) {
|
|
147
147
|
throw new Error(
|
|
148
148
|
`We detected that the '@vitejs/plugin-react' was passed before '@tanstack/router-vite-plugin'. Please make sure that '@tanstack/router-vite-plugin' is passed before '@vitejs/plugin-react' and try again:
|
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../../src/index.ts"],"sourcesContent":["import { isAbsolute, join, normalize, resolve } from 'path'\nimport { fileURLToPath, pathToFileURL } from 'url'\nimport { z } from 'zod'\nimport {\n generator,\n configSchema as generatorConfigSchema,\n getConfig as getGeneratorConfig,\n} from '@tanstack/router-generator'\nimport { compileFile, makeCompile, splitFile } from './compilers'\nimport { splitPrefix } from './constants'\nimport type { Plugin } from 'vite'\n\nexport const configSchema = generatorConfigSchema.extend({\n enableRouteGeneration: z.boolean().optional(),\n experimental: z\n .object({\n enableCodeSplitting: z.boolean().optional(),\n })\n .optional(),\n})\n\nexport type Config = z.infer<typeof configSchema>\n\nconst CONFIG_FILE_NAME = 'tsr.config.json'\nconst debug = Boolean(process.env.TSR_VITE_DEBUG)\n\nconst getConfig = async (inlineConfig: Partial<Config>, root: string) => {\n const config = await getGeneratorConfig(inlineConfig, root)\n\n return configSchema.parse({ ...config, ...inlineConfig })\n}\n\nexport function TanStackRouterVite(\n inlineConfig: Partial<Config> = {},\n): Array<Plugin> {\n return [\n TanStackRouterViteGenerator(inlineConfig),\n TanStackRouterViteCodeSplitter(inlineConfig),\n ]\n}\n\nlet lock = false\n\nexport function TanStackRouterViteGenerator(\n inlineConfig: Partial<Config> = {},\n): Plugin {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n const generate = async () => {\n if (lock) {\n return\n }\n lock = true\n try {\n await generator(userConfig)\n } catch (err) {\n console.error(err)\n console.info()\n }\n lock = false\n }\n\n const handleFile = async (\n file: string,\n event: 'create' | 'update' | 'delete',\n ) => {\n const filePath = normalize(file)\n\n if (filePath === join(ROOT, CONFIG_FILE_NAME)) {\n userConfig = await getConfig(inlineConfig, ROOT)\n return\n }\n\n if (\n event === 'update' &&\n filePath === resolve(userConfig.generatedRouteTree)\n ) {\n // skip generating routes if the generated route tree is updated\n return\n }\n\n const routesDirectoryPath = isAbsolute(userConfig.routesDirectory)\n ? userConfig.routesDirectory\n : join(ROOT, userConfig.routesDirectory)\n\n if (filePath.startsWith(routesDirectoryPath)) {\n await generate()\n }\n }\n\n return {\n name: 'vite-plugin-tanstack-router-generator',\n configResolved: async (config) => {\n ROOT = process.cwd()\n userConfig = await getConfig(inlineConfig, ROOT)\n if (userConfig.enableRouteGeneration ?? true) {\n await generate()\n }\n },\n watchChange: async (file, context) => {\n if (userConfig.enableRouteGeneration ?? true) {\n if (['create', 'update', 'delete'].includes(context.event)) {\n await handleFile(file, context.event)\n }\n }\n },\n }\n}\n\nfunction fileIsInRoutesDirectory(filePath: string, routesDirectory: string) {\n const routesDirectoryPath = isAbsolute(routesDirectory)\n ? routesDirectory\n : join(process.cwd(), routesDirectory)\n\n return filePath.startsWith(routesDirectoryPath)\n}\n\nexport function TanStackRouterViteCodeSplitter(\n inlineConfig: Partial<Config> = {},\n): Plugin {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n return {\n name: 'vite-plugin-tanstack-router-code-splitter',\n enforce: 'pre',\n configResolved: async (config) => {\n ROOT = config.root\n userConfig = await getConfig(inlineConfig, ROOT)\n },\n resolveId(source) {\n if (!userConfig.experimental?.enableCodeSplitting) {\n return null\n }\n\n if (source.startsWith(splitPrefix + ':')) {\n return source.replace(splitPrefix + ':', '')\n }\n return null\n },\n async transform(code, id, transformOptions) {\n if (!userConfig.experimental?.enableCodeSplitting) {\n return null\n }\n\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n id = fileURLToPath(url).replace(/\\\\/g, '/')\n\n const compile = makeCompile({\n root: ROOT,\n })\n\n if (id.includes(splitPrefix)) {\n if (debug) console.info('Splitting route: ', id)\n // const ref = new URLSearchParams(id.split('?')[1]).get('ref') || ''\n\n const compiled = await splitFile({\n code,\n compile,\n filename: id,\n // ref,\n })\n\n if (debug) console.info('')\n if (debug) console.info('Split Output')\n if (debug) console.info('')\n if (debug) console.info(compiled.code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n return compiled\n } else if (\n (fileIsInRoutesDirectory(id, userConfig.routesDirectory) &&\n (code.includes('createRoute(') ||\n code.includes('createFileRoute('))) ||\n code.includes('createServerFn')\n ) {\n if (code.includes('@react-refresh')) {\n throw new Error(\n `We detected that the '@vitejs/plugin-react' was passed before '@tanstack/router-vite-plugin'. Please make sure that '@tanstack/router-vite-plugin' is passed before '@vitejs/plugin-react' and try again: \ne.g.\n\nplugins: [\n TanStackRouterVite(), // Place this before viteReact()\n viteReact(),\n]\n`,\n )\n }\n\n if (debug) console.info('Handling createRoute: ', id)\n const compiled = await compileFile({\n code,\n compile,\n filename: id,\n })\n\n if (debug) console.info('')\n if (debug) console.info('Compiled Output')\n if (debug) console.info('')\n if (debug) console.info(compiled.code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n return compiled\n }\n\n return null\n },\n }\n}\n"],"names":["generatorConfigSchema","z","getGeneratorConfig","generator","normalize","join","resolve","isAbsolute","splitPrefix","url","pathToFileURL","fileURLToPath","makeCompile","splitFile","compileFile"],"mappings":";;;;;;;;AAYa,MAAA,eAAeA,6BAAsB,OAAO;AAAA,EACvD,uBAAuBC,IAAA,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC5C,cAAcA,MACX,OAAO;AAAA,IACN,qBAAqBA,IAAA,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A;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AAEnB,eAAA;AAAA,MACT;AAEO,aAAA;AAAA,IACT;AAAA,EAAA;AAEJ;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../../src/index.ts"],"sourcesContent":["import { isAbsolute, join, normalize, resolve } from 'path'\nimport { fileURLToPath, pathToFileURL } from 'url'\nimport { z } from 'zod'\nimport {\n generator,\n configSchema as generatorConfigSchema,\n getConfig as getGeneratorConfig,\n} from '@tanstack/router-generator'\nimport { compileFile, makeCompile, splitFile } from './compilers'\nimport { splitPrefix } from './constants'\nimport type { Plugin } from 'vite'\n\nexport const configSchema = generatorConfigSchema.extend({\n enableRouteGeneration: z.boolean().optional(),\n experimental: z\n .object({\n enableCodeSplitting: z.boolean().optional(),\n })\n .optional(),\n})\n\nexport type Config = z.infer<typeof configSchema>\n\nconst CONFIG_FILE_NAME = 'tsr.config.json'\nconst debug = Boolean(process.env.TSR_VITE_DEBUG)\n\nconst getConfig = async (inlineConfig: Partial<Config>, root: string) => {\n const config = await getGeneratorConfig(inlineConfig, root)\n\n return configSchema.parse({ ...config, ...inlineConfig })\n}\n\nexport function TanStackRouterVite(\n inlineConfig: Partial<Config> = {},\n): Array<Plugin> {\n return [\n TanStackRouterViteGenerator(inlineConfig),\n TanStackRouterViteCodeSplitter(inlineConfig),\n ]\n}\n\nlet lock = false\n\nexport function TanStackRouterViteGenerator(\n inlineConfig: Partial<Config> = {},\n): Plugin {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n const generate = async () => {\n if (lock) {\n return\n }\n lock = true\n try {\n await generator(userConfig)\n } catch (err) {\n console.error(err)\n console.info()\n }\n lock = false\n }\n\n const handleFile = async (\n file: string,\n event: 'create' | 'update' | 'delete',\n ) => {\n const filePath = normalize(file)\n\n if (filePath === join(ROOT, CONFIG_FILE_NAME)) {\n userConfig = await getConfig(inlineConfig, ROOT)\n return\n }\n\n if (\n event === 'update' &&\n filePath === resolve(userConfig.generatedRouteTree)\n ) {\n // skip generating routes if the generated route tree is updated\n return\n }\n\n const routesDirectoryPath = isAbsolute(userConfig.routesDirectory)\n ? userConfig.routesDirectory\n : join(ROOT, userConfig.routesDirectory)\n\n if (filePath.startsWith(routesDirectoryPath)) {\n await generate()\n }\n }\n\n return {\n name: 'vite-plugin-tanstack-router-generator',\n configResolved: async (config) => {\n ROOT = process.cwd()\n userConfig = await getConfig(inlineConfig, ROOT)\n if (userConfig.enableRouteGeneration ?? true) {\n await generate()\n }\n },\n watchChange: async (file, context) => {\n if (userConfig.enableRouteGeneration ?? true) {\n if (['create', 'update', 'delete'].includes(context.event)) {\n await handleFile(file, context.event)\n }\n }\n },\n }\n}\n\nfunction fileIsInRoutesDirectory(filePath: string, routesDirectory: string) {\n const routesDirectoryPath = isAbsolute(routesDirectory)\n ? routesDirectory\n : join(process.cwd(), routesDirectory)\n\n return filePath.startsWith(routesDirectoryPath)\n}\n\nexport function TanStackRouterViteCodeSplitter(\n inlineConfig: Partial<Config> = {},\n): Plugin {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n return {\n name: 'vite-plugin-tanstack-router-code-splitter',\n enforce: 'pre',\n configResolved: async (config) => {\n ROOT = config.root\n userConfig = await getConfig(inlineConfig, ROOT)\n },\n resolveId(source) {\n if (!userConfig.experimental?.enableCodeSplitting) {\n return null\n }\n\n if (source.startsWith(splitPrefix + ':')) {\n return source.replace(splitPrefix + ':', '')\n }\n return null\n },\n async transform(code, id, transformOptions) {\n if (!userConfig.experimental?.enableCodeSplitting) {\n return null\n }\n\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n id = fileURLToPath(url).replace(/\\\\/g, '/')\n\n const compile = makeCompile({\n root: ROOT,\n })\n\n if (id.includes(splitPrefix)) {\n if (debug) console.info('Splitting route: ', id)\n // const ref = new URLSearchParams(id.split('?')[1]).get('ref') || ''\n\n const compiled = await splitFile({\n code,\n compile,\n filename: id,\n // ref,\n })\n\n if (debug) console.info('')\n if (debug) console.info('Split Output')\n if (debug) console.info('')\n if (debug) console.info(compiled.code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n return compiled\n } else if (\n fileIsInRoutesDirectory(id, userConfig.routesDirectory) &&\n (code.includes('createRoute(') || code.includes('createFileRoute('))\n ) {\n if (code.includes('@react-refresh')) {\n throw new Error(\n `We detected that the '@vitejs/plugin-react' was passed before '@tanstack/router-vite-plugin'. Please make sure that '@tanstack/router-vite-plugin' is passed before '@vitejs/plugin-react' and try again: \ne.g.\n\nplugins: [\n TanStackRouterVite(), // Place this before viteReact()\n viteReact(),\n]\n`,\n )\n }\n\n if (debug) console.info('Handling createRoute: ', id)\n const compiled = await compileFile({\n code,\n compile,\n filename: id,\n })\n\n if (debug) console.info('')\n if (debug) console.info('Compiled Output')\n if (debug) console.info('')\n if (debug) console.info(compiled.code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n return compiled\n }\n\n return null\n },\n }\n}\n"],"names":["generatorConfigSchema","z","getGeneratorConfig","generator","normalize","join","resolve","isAbsolute","splitPrefix","url","pathToFileURL","fileURLToPath","makeCompile","splitFile","compileFile"],"mappings":";;;;;;;;AAY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AAQ,KAAK,iBAAiB;AACrC,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAe,kBAAA,KAAK,SAAS,IAAI;AACjC,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AAEnB,eAAA;AAAA,MACT;AAEO,aAAA;AAAA,IACT;AAAA,EAAA;AAEJ;;;;;"}
|
package/dist/esm/compilers.js
CHANGED
|
@@ -48,68 +48,7 @@ async function compileFile(opts) {
|
|
|
48
48
|
{
|
|
49
49
|
CallExpression: (path) => {
|
|
50
50
|
if (path.node.callee.type === "Identifier") {
|
|
51
|
-
if (path.node.callee.name === "
|
|
52
|
-
const fn = path.node.arguments[1];
|
|
53
|
-
if (t.isFunctionExpression(fn) || t.isArrowFunctionExpression(fn)) {
|
|
54
|
-
if (t.isBlockStatement(fn.body)) {
|
|
55
|
-
const hasUseServerDirective = fn.body.directives.some((directive) => {
|
|
56
|
-
return directive.value.value === "use server";
|
|
57
|
-
});
|
|
58
|
-
if (!hasUseServerDirective) {
|
|
59
|
-
fn.body.directives.unshift(
|
|
60
|
-
t.directive(
|
|
61
|
-
t.directiveLiteral("use server")
|
|
62
|
-
)
|
|
63
|
-
);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
} else if (t.isIdentifier(fn) || t.isCallExpression(fn)) {
|
|
67
|
-
const args = t.restElement(t.identifier("args"));
|
|
68
|
-
args.typeAnnotation = t.tsTypeAnnotation(
|
|
69
|
-
t.tsTypeReference(
|
|
70
|
-
t.identifier("Parameters"),
|
|
71
|
-
t.tsTypeParameterInstantiation([
|
|
72
|
-
t.tsIndexedAccessType(
|
|
73
|
-
t.tsTypeReference(
|
|
74
|
-
t.identifier("Parameters"),
|
|
75
|
-
t.tsTypeParameterInstantiation([
|
|
76
|
-
t.tsTypeQuery(
|
|
77
|
-
t.identifier("createServerFn")
|
|
78
|
-
)
|
|
79
|
-
])
|
|
80
|
-
),
|
|
81
|
-
t.tsLiteralType(t.numericLiteral(1))
|
|
82
|
-
)
|
|
83
|
-
])
|
|
84
|
-
)
|
|
85
|
-
);
|
|
86
|
-
const wrappedFn = t.arrowFunctionExpression(
|
|
87
|
-
[args],
|
|
88
|
-
t.blockStatement(
|
|
89
|
-
[
|
|
90
|
-
t.returnStatement(
|
|
91
|
-
t.callExpression(
|
|
92
|
-
t.memberExpression(
|
|
93
|
-
fn,
|
|
94
|
-
t.identifier("apply")
|
|
95
|
-
),
|
|
96
|
-
[
|
|
97
|
-
t.identifier("this"),
|
|
98
|
-
t.identifier("args")
|
|
99
|
-
]
|
|
100
|
-
)
|
|
101
|
-
)
|
|
102
|
-
],
|
|
103
|
-
[
|
|
104
|
-
t.directive(
|
|
105
|
-
t.directiveLiteral("use server")
|
|
106
|
-
)
|
|
107
|
-
]
|
|
108
|
-
)
|
|
109
|
-
);
|
|
110
|
-
path.node.arguments[1] = wrappedFn;
|
|
111
|
-
}
|
|
112
|
-
} else if (path.node.callee.name === "createRoute" || path.node.callee.name === "createFileRoute") {
|
|
51
|
+
if (path.node.callee.name === "createRoute" || path.node.callee.name === "createFileRoute") {
|
|
113
52
|
if (path.parentPath.node.type === "CallExpression") {
|
|
114
53
|
const options = resolveIdentifier(
|
|
115
54
|
path,
|
|
@@ -259,68 +198,7 @@ async function splitFile(opts) {
|
|
|
259
198
|
{
|
|
260
199
|
CallExpression: (path) => {
|
|
261
200
|
if (path.node.callee.type === "Identifier") {
|
|
262
|
-
if (path.node.callee.name === "
|
|
263
|
-
const fn = path.node.arguments[1];
|
|
264
|
-
if (t.isFunctionExpression(fn) || t.isArrowFunctionExpression(fn)) {
|
|
265
|
-
if (t.isBlockStatement(fn.body)) {
|
|
266
|
-
const hasUseServerDirective = fn.body.directives.some((directive) => {
|
|
267
|
-
return directive.value.value === "use server";
|
|
268
|
-
});
|
|
269
|
-
if (!hasUseServerDirective) {
|
|
270
|
-
fn.body.directives.unshift(
|
|
271
|
-
t.directive(
|
|
272
|
-
t.directiveLiteral("use server")
|
|
273
|
-
)
|
|
274
|
-
);
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
} else if (t.isIdentifier(fn) || t.isCallExpression(fn)) {
|
|
278
|
-
const args = t.restElement(t.identifier("args"));
|
|
279
|
-
args.typeAnnotation = t.tsTypeAnnotation(
|
|
280
|
-
t.tsTypeReference(
|
|
281
|
-
t.identifier("Parameters"),
|
|
282
|
-
t.tsTypeParameterInstantiation([
|
|
283
|
-
t.tsIndexedAccessType(
|
|
284
|
-
t.tsTypeReference(
|
|
285
|
-
t.identifier("Parameters"),
|
|
286
|
-
t.tsTypeParameterInstantiation([
|
|
287
|
-
t.tsTypeQuery(
|
|
288
|
-
t.identifier("createServerFn")
|
|
289
|
-
)
|
|
290
|
-
])
|
|
291
|
-
),
|
|
292
|
-
t.tsLiteralType(t.numericLiteral(1))
|
|
293
|
-
)
|
|
294
|
-
])
|
|
295
|
-
)
|
|
296
|
-
);
|
|
297
|
-
const wrappedFn = t.arrowFunctionExpression(
|
|
298
|
-
[args],
|
|
299
|
-
t.blockStatement(
|
|
300
|
-
[
|
|
301
|
-
t.returnStatement(
|
|
302
|
-
t.callExpression(
|
|
303
|
-
t.memberExpression(
|
|
304
|
-
fn,
|
|
305
|
-
t.identifier("apply")
|
|
306
|
-
),
|
|
307
|
-
[
|
|
308
|
-
t.identifier("this"),
|
|
309
|
-
t.identifier("args")
|
|
310
|
-
]
|
|
311
|
-
)
|
|
312
|
-
)
|
|
313
|
-
],
|
|
314
|
-
[
|
|
315
|
-
t.directive(
|
|
316
|
-
t.directiveLiteral("use server")
|
|
317
|
-
)
|
|
318
|
-
]
|
|
319
|
-
)
|
|
320
|
-
);
|
|
321
|
-
path.node.arguments[1] = wrappedFn;
|
|
322
|
-
}
|
|
323
|
-
} else if (path.node.callee.name === "createRoute" || path.node.callee.name === "createFileRoute") {
|
|
201
|
+
if (path.node.callee.name === "createRoute" || path.node.callee.name === "createFileRoute") {
|
|
324
202
|
if (path.parentPath.node.type === "CallExpression") {
|
|
325
203
|
const options = resolveIdentifier(
|
|
326
204
|
path,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compilers.js","sources":["../../src/compilers.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport * as template from '@babel/template'\nimport * as babel from '@babel/core'\nimport { splitPrefix } from './constants'\nimport { eliminateUnreferencedIdentifiers } from './eliminateUnreferencedIdentifiers'\n\ntype SplitModulesById = Record<\n string,\n { id: string; node: t.FunctionExpression }\n>\n\ninterface State {\n filename: string\n opts: {\n minify: boolean\n root: string\n }\n imported: Record<string, boolean>\n refs: Set<any>\n serverIndex: number\n splitIndex: number\n splitModulesById: SplitModulesById\n}\n\nexport type CompileFn = (compileOpts: {\n code: string\n filename: string\n getBabelConfig: () => { plugins: Array<any> }\n}) => Promise<{\n code: string\n map: any\n}>\n\nexport function makeCompile(makeOpts: { root: string }) {\n return async (opts: {\n code: string\n filename: string\n getBabelConfig: () => { plugins: Array<any> }\n }): Promise<{\n code: string\n map: any\n }> => {\n const res = await babel.transform(opts.code, {\n plugins: [\n ['@babel/plugin-syntax-jsx', {}],\n [\n '@babel/plugin-syntax-typescript',\n {\n isTSX: true,\n },\n ],\n ...opts.getBabelConfig().plugins,\n ],\n root: makeOpts.root,\n filename: opts.filename,\n sourceMaps: true,\n })\n\n if (res?.code) {\n return {\n code: res.code,\n map: res.map,\n }\n }\n\n return {\n code: opts.code,\n map: null,\n }\n }\n}\n\nexport async function compileFile(opts: {\n code: string\n compile: CompileFn\n filename: string\n}) {\n return await opts.compile({\n code: opts.code,\n filename: opts.filename,\n getBabelConfig: () => ({\n plugins: [\n [\n {\n visitor: {\n Program: {\n enter(programPath: babel.NodePath<t.Program>, state: State) {\n const splitUrl = `${splitPrefix}:${opts.filename}?${splitPrefix}`\n\n programPath.traverse(\n {\n CallExpression: (path) => {\n if (path.node.callee.type === 'Identifier') {\n if (path.node.callee.name === 'createServerFn') {\n // If the function at createServerFn(_, MyFunc) doesn't have a\n // 'use server' directive at the top of the function scope,\n // then add it.\n\n const fn = path.node.arguments[1]\n\n if (\n t.isFunctionExpression(fn) ||\n t.isArrowFunctionExpression(fn)\n ) {\n if (t.isBlockStatement(fn.body)) {\n const hasUseServerDirective =\n fn.body.directives.some((directive) => {\n return (\n directive.value.value === 'use server'\n )\n })\n\n if (!hasUseServerDirective) {\n fn.body.directives.unshift(\n t.directive(\n t.directiveLiteral('use server'),\n ),\n )\n }\n }\n } else if (\n t.isIdentifier(fn) ||\n t.isCallExpression(fn)\n ) {\n // A function was passed to createServerFn in the form of an\n // identifier or a call expression that returns a function.\n\n // We wrap the identifier/call expression in a function\n // expression that accepts the same arguments as the original\n // function with the \"use server\" directive at the top of the\n // function scope.\n\n const args = t.restElement(t.identifier('args'))\n\n // Annotate args with the type:\n // Parameters<Parameters<typeof createServerFn>[1]>\n\n args.typeAnnotation = t.tsTypeAnnotation(\n t.tsTypeReference(\n t.identifier('Parameters'),\n t.tsTypeParameterInstantiation([\n t.tsIndexedAccessType(\n t.tsTypeReference(\n t.identifier('Parameters'),\n t.tsTypeParameterInstantiation([\n t.tsTypeQuery(\n t.identifier('createServerFn'),\n ),\n ]),\n ),\n t.tsLiteralType(t.numericLiteral(1)),\n ),\n ]),\n ),\n )\n\n const wrappedFn = t.arrowFunctionExpression(\n [args],\n t.blockStatement(\n [\n t.returnStatement(\n t.callExpression(\n t.memberExpression(\n fn,\n t.identifier('apply'),\n ),\n [\n t.identifier('this'),\n t.identifier('args'),\n ],\n ),\n ),\n ],\n [\n t.directive(\n t.directiveLiteral('use server'),\n ),\n ],\n ),\n )\n\n path.node.arguments[1] = wrappedFn\n }\n } else if (\n path.node.callee.name === 'createRoute' ||\n path.node.callee.name === 'createFileRoute'\n ) {\n if (\n path.parentPath.node.type === 'CallExpression'\n ) {\n const options = resolveIdentifier(\n path,\n path.parentPath.node.arguments[0],\n )\n\n let found = false\n\n const hasImportedOrDefinedIdentifier = (\n name: string,\n ) => {\n return programPath.scope.hasBinding(name)\n }\n\n if (t.isObjectExpression(options)) {\n options.properties.forEach((prop) => {\n if (t.isObjectProperty(prop)) {\n if (t.isIdentifier(prop.key)) {\n if (prop.key.name === 'component') {\n const value = prop.value\n\n if (t.isIdentifier(value)) {\n removeIdentifierLiteral(path, value)\n }\n\n // Prepend the import statement to the program along with the importer function\n // Check to see if lazyRouteComponent is already imported before attempting\n // to import it again\n\n if (\n !hasImportedOrDefinedIdentifier(\n 'lazyRouteComponent',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `import { lazyRouteComponent } from '@tanstack/react-router'`,\n )() as t.Statement,\n ])\n }\n\n if (\n !hasImportedOrDefinedIdentifier(\n '$$splitComponentImporter',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `const $$splitComponentImporter = () => import('${splitUrl}')`,\n )() as t.Statement,\n ])\n }\n\n prop.value = template.expression(\n `lazyRouteComponent($$splitComponentImporter, 'component')`,\n )() as any\n\n programPath.pushContainer('body', [\n template.smart(\n `function DummyComponent() { return null }`,\n )() as t.Statement,\n ])\n\n found = true\n } else if (prop.key.name === 'loader') {\n const value = prop.value\n\n if (t.isIdentifier(value)) {\n removeIdentifierLiteral(path, value)\n }\n\n // Prepend the import statement to the program along with the importer function\n\n if (\n !hasImportedOrDefinedIdentifier(\n 'lazyFn',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `import { lazyFn } from '@tanstack/react-router'`,\n )() as t.Statement,\n ])\n }\n\n if (\n !hasImportedOrDefinedIdentifier(\n '$$splitLoaderImporter',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `const $$splitLoaderImporter = () => import('${splitUrl}')`,\n )() as t.Statement,\n ])\n }\n\n prop.value = template.expression(\n `lazyFn($$splitLoaderImporter, 'loader')`,\n )() as any\n\n found = true\n }\n }\n }\n\n programPath.scope.crawl()\n })\n }\n\n if (found as boolean) {\n programPath.pushContainer('body', [\n template.smart(\n `function TSR_Dummy_Component() {}`,\n )() as t.Statement,\n ])\n }\n }\n }\n }\n },\n },\n state,\n )\n\n eliminateUnreferencedIdentifiers(programPath)\n },\n },\n },\n },\n {\n root: process.cwd(),\n minify: process.env.NODE_ENV === 'production',\n },\n ],\n ].filter(Boolean),\n }),\n })\n}\n\n// Reusable function to get literal value or resolve variable to literal\nfunction resolveIdentifier(path: any, node: any) {\n if (t.isIdentifier(node)) {\n const binding = path.scope.getBinding(node.name)\n if (\n binding\n // && binding.kind === 'const'\n ) {\n const declarator = binding.path.node\n if (t.isObjectExpression(declarator.init)) {\n return declarator.init\n } else if (t.isFunctionDeclaration(declarator.init)) {\n return declarator.init\n }\n }\n return undefined\n }\n\n return node\n}\n\nfunction removeIdentifierLiteral(path: any, node: any) {\n if (t.isIdentifier(node)) {\n const binding = path.scope.getBinding(node.name)\n if (binding) {\n binding.path.remove()\n }\n }\n}\n\nconst splitNodeTypes = ['component', 'loader'] as const\ntype SplitNodeType = (typeof splitNodeTypes)[number]\n\nexport async function splitFile(opts: {\n code: string\n compile: CompileFn\n filename: string\n // ref: string\n}) {\n return await opts.compile({\n code: opts.code,\n filename: opts.filename,\n getBabelConfig: () => ({\n plugins: [\n [\n {\n visitor: {\n Program: {\n enter(programPath: babel.NodePath<t.Program>, state: State) {\n const splitNodesByType: Record<\n SplitNodeType,\n t.Node | undefined\n > = {\n component: undefined,\n loader: undefined,\n }\n\n // Find the node\n programPath.traverse(\n {\n CallExpression: (path) => {\n if (path.node.callee.type === 'Identifier') {\n if (path.node.callee.name === 'createServerFn') {\n // If the function at createServerFn(_, MyFunc) doesn't have a\n // 'use server' directive at the top of the function scope,\n // then add it.\n\n const fn = path.node.arguments[1]\n\n if (\n t.isFunctionExpression(fn) ||\n t.isArrowFunctionExpression(fn)\n ) {\n if (t.isBlockStatement(fn.body)) {\n const hasUseServerDirective =\n fn.body.directives.some((directive) => {\n return (\n directive.value.value === 'use server'\n )\n })\n\n if (!hasUseServerDirective) {\n fn.body.directives.unshift(\n t.directive(\n t.directiveLiteral('use server'),\n ),\n )\n }\n }\n } else if (\n t.isIdentifier(fn) ||\n t.isCallExpression(fn)\n ) {\n // A function was passed to createServerFn in the form of an\n // identifier or a call expression that returns a function.\n\n // We wrap the identifier/call expression in a function\n // expression that accepts the same arguments as the original\n // function with the \"use server\" directive at the top of the\n // function scope.\n\n const args = t.restElement(t.identifier('args'))\n\n // Annotate args with the type:\n // Parameters<Parameters<typeof createServerFn>[1]>\n\n args.typeAnnotation = t.tsTypeAnnotation(\n t.tsTypeReference(\n t.identifier('Parameters'),\n t.tsTypeParameterInstantiation([\n t.tsIndexedAccessType(\n t.tsTypeReference(\n t.identifier('Parameters'),\n t.tsTypeParameterInstantiation([\n t.tsTypeQuery(\n t.identifier('createServerFn'),\n ),\n ]),\n ),\n t.tsLiteralType(t.numericLiteral(1)),\n ),\n ]),\n ),\n )\n\n const wrappedFn = t.arrowFunctionExpression(\n [args],\n t.blockStatement(\n [\n t.returnStatement(\n t.callExpression(\n t.memberExpression(\n fn,\n t.identifier('apply'),\n ),\n [\n t.identifier('this'),\n t.identifier('args'),\n ],\n ),\n ),\n ],\n [\n t.directive(\n t.directiveLiteral('use server'),\n ),\n ],\n ),\n )\n\n path.node.arguments[1] = wrappedFn\n }\n } else if (\n path.node.callee.name === 'createRoute' ||\n path.node.callee.name === 'createFileRoute'\n ) {\n if (\n path.parentPath.node.type === 'CallExpression'\n ) {\n const options = resolveIdentifier(\n path,\n path.parentPath.node.arguments[0],\n )\n\n if (t.isObjectExpression(options)) {\n options.properties.forEach((prop) => {\n if (t.isObjectProperty(prop)) {\n splitNodeTypes.forEach((type) => {\n if (t.isIdentifier(prop.key)) {\n if (prop.key.name === type) {\n splitNodesByType[type] = prop.value\n }\n }\n })\n }\n })\n\n // Remove all of the options\n options.properties = []\n }\n }\n }\n }\n },\n },\n state,\n )\n\n splitNodeTypes.forEach((splitType) => {\n let splitNode = splitNodesByType[splitType]\n\n if (!splitNode) {\n return\n }\n\n while (t.isIdentifier(splitNode)) {\n const binding = programPath.scope.getBinding(\n splitNode.name,\n )\n splitNode = binding?.path.node\n }\n\n // Add the node to the program\n if (splitNode) {\n if (t.isFunctionDeclaration(splitNode)) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n t.functionExpression(\n splitNode.id || null, // Anonymize the function expression\n splitNode.params,\n splitNode.body,\n splitNode.generator,\n splitNode.async,\n ),\n ),\n ]),\n )\n } else if (\n t.isFunctionExpression(splitNode) ||\n t.isArrowFunctionExpression(splitNode)\n ) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n splitNode as any,\n ),\n ]),\n )\n } else if (t.isImportSpecifier(splitNode)) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n splitNode.local,\n ),\n ]),\n )\n } else {\n console.info(splitNode)\n throw new Error(\n `Unexpected splitNode type ☝️: ${splitNode.type}`,\n )\n }\n }\n\n // If the splitNode exists at the top of the program\n // then we need to remove that copy\n programPath.node.body = programPath.node.body.filter(\n (node) => {\n return node !== splitNode\n },\n )\n\n // Export the node\n programPath.pushContainer('body', [\n t.exportNamedDeclaration(null, [\n t.exportSpecifier(\n t.identifier(splitType),\n t.identifier(splitType),\n ),\n ]),\n ])\n })\n\n // convert exports to imports from the original file\n programPath.traverse({\n ExportNamedDeclaration(path) {\n // e.g. export const x = 1 or export { x }\n // becomes\n // import { x } from '${opts.id}'\n\n if (path.node.declaration) {\n if (t.isVariableDeclaration(path.node.declaration)) {\n path.replaceWith(\n t.importDeclaration(\n path.node.declaration.declarations.map((decl) =>\n t.importSpecifier(\n t.identifier((decl.id as any).name),\n t.identifier((decl.id as any).name),\n ),\n ),\n t.stringLiteral(\n opts.filename.split(\n `?${splitPrefix}`,\n )[0] as string,\n ),\n ),\n )\n }\n }\n },\n })\n\n eliminateUnreferencedIdentifiers(programPath)\n },\n },\n },\n },\n {\n root: process.cwd(),\n minify: process.env.NODE_ENV === 'production',\n },\n ],\n ].filter(Boolean),\n }),\n })\n}\n"],"names":[],"mappings":";;;;;AAiCO,SAAS,YAAY,UAA4B;AACtD,SAAO,OAAO,SAOR;AACJ,UAAM,MAAM,MAAM,MAAM,UAAU,KAAK,MAAM;AAAA,MAC3C,SAAS;AAAA,QACP,CAAC,4BAA4B,CAAA,CAAE;AAAA,QAC/B;AAAA,UACE;AAAA,UACA;AAAA,YACE,OAAO;AAAA,UACT;AAAA,QACF;AAAA,QACA,GAAG,KAAK,eAAA,EAAiB;AAAA,MAC3B;AAAA,MACA,MAAM,SAAS;AAAA,MACf,UAAU,KAAK;AAAA,MACf,YAAY;AAAA,IAAA,CACb;AAED,QAAI,2BAAK,MAAM;AACN,aAAA;AAAA,QACL,MAAM,IAAI;AAAA,QACV,KAAK,IAAI;AAAA,MAAA;AAAA,IAEb;AAEO,WAAA;AAAA,MACL,MAAM,KAAK;AAAA,MACX,KAAK;AAAA,IAAA;AAAA,EACP;AAEJ;AAEA,eAAsB,YAAY,MAI/B;AACM,SAAA,MAAM,KAAK,QAAQ;AAAA,IACxB,MAAM,KAAK;AAAA,IACX,UAAU,KAAK;AAAA,IACf,gBAAgB,OAAO;AAAA,MACrB,SAAS;AAAA,QACP;AAAA,UACE;AAAA,YACE,SAAS;AAAA,cACP,SAAS;AAAA,gBACP,MAAM,aAAwC,OAAc;AAC1D,wBAAM,WAAW,GAAG,WAAW,IAAI,KAAK,QAAQ,IAAI,WAAW;A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CACA,EAAE,WAAY,KAAK,GAAW,IAAI;AAAA,kCAClC,EAAE,WAAY,KAAK,GAAW,IAAI;AAAA,gCACpC;AAAA,8BACF;AAAA,8BACA,EAAE;AAAA,gCACA,KAAK,SAAS;AAAA,kCACZ,IAAI,WAAW;AAAA,kCACf,CAAC;AAAA,8BACL;AAAA,4BACF;AAAA,0BAAA;AAAA,wBAEJ;AAAA,sBACF;AAAA,oBACF;AAAA,kBAAA,CACD;AAED,mDAAiC,WAAW;AAAA,gBAC9C;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAAA,UACA;AAAA,YACE,MAAM,QAAQ,IAAI;AAAA,YAClB,QAAQ,QAAQ,IAAI,aAAa;AAAA,UACnC;AAAA,QACF;AAAA,MAAA,EACA,OAAO,OAAO;AAAA,IAAA;AAAA,EAClB,CACD;AACH;"}
|
|
1
|
+
{"version":3,"file":"compilers.js","sources":["../../src/compilers.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport * as template from '@babel/template'\nimport * as babel from '@babel/core'\nimport { splitPrefix } from './constants'\nimport { eliminateUnreferencedIdentifiers } from './eliminateUnreferencedIdentifiers'\n\ntype SplitModulesById = Record<\n string,\n { id: string; node: t.FunctionExpression }\n>\n\ninterface State {\n filename: string\n opts: {\n minify: boolean\n root: string\n }\n imported: Record<string, boolean>\n refs: Set<any>\n serverIndex: number\n splitIndex: number\n splitModulesById: SplitModulesById\n}\n\nexport type CompileFn = (compileOpts: {\n code: string\n filename: string\n getBabelConfig: () => { plugins: Array<any> }\n}) => Promise<{\n code: string\n map: any\n}>\n\nexport function makeCompile(makeOpts: { root: string }) {\n return async (opts: {\n code: string\n filename: string\n getBabelConfig: () => { plugins: Array<any> }\n }): Promise<{\n code: string\n map: any\n }> => {\n const res = await babel.transform(opts.code, {\n plugins: [\n ['@babel/plugin-syntax-jsx', {}],\n [\n '@babel/plugin-syntax-typescript',\n {\n isTSX: true,\n },\n ],\n ...opts.getBabelConfig().plugins,\n ],\n root: makeOpts.root,\n filename: opts.filename,\n sourceMaps: true,\n })\n\n if (res?.code) {\n return {\n code: res.code,\n map: res.map,\n }\n }\n\n return {\n code: opts.code,\n map: null,\n }\n }\n}\n\nexport async function compileFile(opts: {\n code: string\n compile: CompileFn\n filename: string\n}) {\n return await opts.compile({\n code: opts.code,\n filename: opts.filename,\n getBabelConfig: () => ({\n plugins: [\n [\n {\n visitor: {\n Program: {\n enter(programPath: babel.NodePath<t.Program>, state: State) {\n const splitUrl = `${splitPrefix}:${opts.filename}?${splitPrefix}`\n\n programPath.traverse(\n {\n CallExpression: (path) => {\n if (path.node.callee.type === 'Identifier') {\n if (\n path.node.callee.name === 'createRoute' ||\n path.node.callee.name === 'createFileRoute'\n ) {\n if (\n path.parentPath.node.type === 'CallExpression'\n ) {\n const options = resolveIdentifier(\n path,\n path.parentPath.node.arguments[0],\n )\n\n let found = false\n\n const hasImportedOrDefinedIdentifier = (\n name: string,\n ) => {\n return programPath.scope.hasBinding(name)\n }\n\n if (t.isObjectExpression(options)) {\n options.properties.forEach((prop) => {\n if (t.isObjectProperty(prop)) {\n if (t.isIdentifier(prop.key)) {\n if (prop.key.name === 'component') {\n const value = prop.value\n\n if (t.isIdentifier(value)) {\n removeIdentifierLiteral(path, value)\n }\n\n // Prepend the import statement to the program along with the importer function\n // Check to see if lazyRouteComponent is already imported before attempting\n // to import it again\n\n if (\n !hasImportedOrDefinedIdentifier(\n 'lazyRouteComponent',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `import { lazyRouteComponent } from '@tanstack/react-router'`,\n )() as t.Statement,\n ])\n }\n\n if (\n !hasImportedOrDefinedIdentifier(\n '$$splitComponentImporter',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `const $$splitComponentImporter = () => import('${splitUrl}')`,\n )() as t.Statement,\n ])\n }\n\n prop.value = template.expression(\n `lazyRouteComponent($$splitComponentImporter, 'component')`,\n )() as any\n\n programPath.pushContainer('body', [\n template.smart(\n `function DummyComponent() { return null }`,\n )() as t.Statement,\n ])\n\n found = true\n } else if (prop.key.name === 'loader') {\n const value = prop.value\n\n if (t.isIdentifier(value)) {\n removeIdentifierLiteral(path, value)\n }\n\n // Prepend the import statement to the program along with the importer function\n\n if (\n !hasImportedOrDefinedIdentifier(\n 'lazyFn',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `import { lazyFn } from '@tanstack/react-router'`,\n )() as t.Statement,\n ])\n }\n\n if (\n !hasImportedOrDefinedIdentifier(\n '$$splitLoaderImporter',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.smart(\n `const $$splitLoaderImporter = () => import('${splitUrl}')`,\n )() as t.Statement,\n ])\n }\n\n prop.value = template.expression(\n `lazyFn($$splitLoaderImporter, 'loader')`,\n )() as any\n\n found = true\n }\n }\n }\n\n programPath.scope.crawl()\n })\n }\n\n if (found as boolean) {\n programPath.pushContainer('body', [\n template.smart(\n `function TSR_Dummy_Component() {}`,\n )() as t.Statement,\n ])\n }\n }\n }\n }\n },\n },\n state,\n )\n\n eliminateUnreferencedIdentifiers(programPath)\n },\n },\n },\n },\n {\n root: process.cwd(),\n minify: process.env.NODE_ENV === 'production',\n },\n ],\n ].filter(Boolean),\n }),\n })\n}\n\n// Reusable function to get literal value or resolve variable to literal\nfunction resolveIdentifier(path: any, node: any) {\n if (t.isIdentifier(node)) {\n const binding = path.scope.getBinding(node.name)\n if (\n binding\n // && binding.kind === 'const'\n ) {\n const declarator = binding.path.node\n if (t.isObjectExpression(declarator.init)) {\n return declarator.init\n } else if (t.isFunctionDeclaration(declarator.init)) {\n return declarator.init\n }\n }\n return undefined\n }\n\n return node\n}\n\nfunction removeIdentifierLiteral(path: any, node: any) {\n if (t.isIdentifier(node)) {\n const binding = path.scope.getBinding(node.name)\n if (binding) {\n binding.path.remove()\n }\n }\n}\n\nconst splitNodeTypes = ['component', 'loader'] as const\ntype SplitNodeType = (typeof splitNodeTypes)[number]\n\nexport async function splitFile(opts: {\n code: string\n compile: CompileFn\n filename: string\n // ref: string\n}) {\n return await opts.compile({\n code: opts.code,\n filename: opts.filename,\n getBabelConfig: () => ({\n plugins: [\n [\n {\n visitor: {\n Program: {\n enter(programPath: babel.NodePath<t.Program>, state: State) {\n const splitNodesByType: Record<\n SplitNodeType,\n t.Node | undefined\n > = {\n component: undefined,\n loader: undefined,\n }\n\n // Find the node\n programPath.traverse(\n {\n CallExpression: (path) => {\n if (path.node.callee.type === 'Identifier') {\n if (\n path.node.callee.name === 'createRoute' ||\n path.node.callee.name === 'createFileRoute'\n ) {\n if (\n path.parentPath.node.type === 'CallExpression'\n ) {\n const options = resolveIdentifier(\n path,\n path.parentPath.node.arguments[0],\n )\n\n if (t.isObjectExpression(options)) {\n options.properties.forEach((prop) => {\n if (t.isObjectProperty(prop)) {\n splitNodeTypes.forEach((type) => {\n if (t.isIdentifier(prop.key)) {\n if (prop.key.name === type) {\n splitNodesByType[type] = prop.value\n }\n }\n })\n }\n })\n\n // Remove all of the options\n options.properties = []\n }\n }\n }\n }\n },\n },\n state,\n )\n\n splitNodeTypes.forEach((splitType) => {\n let splitNode = splitNodesByType[splitType]\n\n if (!splitNode) {\n return\n }\n\n while (t.isIdentifier(splitNode)) {\n const binding = programPath.scope.getBinding(\n splitNode.name,\n )\n splitNode = binding?.path.node\n }\n\n // Add the node to the program\n if (splitNode) {\n if (t.isFunctionDeclaration(splitNode)) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n t.functionExpression(\n splitNode.id || null, // Anonymize the function expression\n splitNode.params,\n splitNode.body,\n splitNode.generator,\n splitNode.async,\n ),\n ),\n ]),\n )\n } else if (\n t.isFunctionExpression(splitNode) ||\n t.isArrowFunctionExpression(splitNode)\n ) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n splitNode as any,\n ),\n ]),\n )\n } else if (t.isImportSpecifier(splitNode)) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n splitNode.local,\n ),\n ]),\n )\n } else {\n console.info(splitNode)\n throw new Error(\n `Unexpected splitNode type ☝️: ${splitNode.type}`,\n )\n }\n }\n\n // If the splitNode exists at the top of the program\n // then we need to remove that copy\n programPath.node.body = programPath.node.body.filter(\n (node) => {\n return node !== splitNode\n },\n )\n\n // Export the node\n programPath.pushContainer('body', [\n t.exportNamedDeclaration(null, [\n t.exportSpecifier(\n t.identifier(splitType),\n t.identifier(splitType),\n ),\n ]),\n ])\n })\n\n // convert exports to imports from the original file\n programPath.traverse({\n ExportNamedDeclaration(path) {\n // e.g. export const x = 1 or export { x }\n // becomes\n // import { x } from '${opts.id}'\n\n if (path.node.declaration) {\n if (t.isVariableDeclaration(path.node.declaration)) {\n path.replaceWith(\n t.importDeclaration(\n path.node.declaration.declarations.map((decl) =>\n t.importSpecifier(\n t.identifier((decl.id as any).name),\n t.identifier((decl.id as any).name),\n ),\n ),\n t.stringLiteral(\n opts.filename.split(\n `?${splitPrefix}`,\n )[0] as string,\n ),\n ),\n )\n }\n }\n },\n })\n\n eliminateUnreferencedIdentifiers(programPath)\n },\n },\n },\n },\n {\n root: process.cwd(),\n minify: process.env.NODE_ENV === 'production',\n },\n ],\n ].filter(Boolean),\n }),\n })\n}\n"],"names":[],"mappings":";;;;;AAiCO,SAAS,YAAY,UAA4B;AACtD,SAAO,OAAO,SAOR;AACJ,UAAM,MAAM,MAAM,MAAM,UAAU,KAAK,MAAM;AAAA,MAC3C,SAAS;AAAA,QACP,CAAC,4BAA4B,CAAA,CAAE;AAAA,QAC/B;AAAA,UACE;AAAA,UACA;AAAA,YACE,OAAO;AAAA,UACT;AAAA,QACF;AAAA,QACA,GAAG,KAAK,eAAA,EAAiB;AAAA,MAC3B;AAAA,MACA,MAAM,SAAS;AAAA,MACf,UAAU,KAAK;AAAA,MACf,YAAY;AAAA,IAAA,CACb;AAED,QAAI,2BAAK,MAAM;AACN,aAAA;AAAA,QACL,MAAM,I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AW,IAAI;AAAA,gCACpC;AAAA,8BACF;AAAA,8BACA,EAAE;AAAA,gCACA,KAAK,SAAS;AAAA,kCACZ,IAAI,WAAW;AAAA,kCACf,CAAC;AAAA,8BACL;AAAA,4BACF;AAAA,0BAAA;AAAA,wBAEJ;AAAA,sBACF;AAAA,oBACF;AAAA,kBAAA,CACD;AAED,mDAAiC,WAAW;AAAA,gBAC9C;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAAA,UACA;AAAA,YACE,MAAM,QAAQ,IAAI;AAAA,YAClB,QAAQ,QAAQ,IAAI,aAAa;AAAA,UACnC;AAAA,QACF;AAAA,MAAA,EACA,OAAO,OAAO;AAAA,IAAA;AAAA,EAClB,CACD;AACH;"}
|
package/dist/esm/index.js
CHANGED
|
@@ -140,7 +140,7 @@ function TanStackRouterViteCodeSplitter(inlineConfig = {}) {
|
|
|
140
140
|
if (debug)
|
|
141
141
|
console.info("");
|
|
142
142
|
return compiled;
|
|
143
|
-
} else if (fileIsInRoutesDirectory(id, userConfig.routesDirectory) && (code.includes("createRoute(") || code.includes("createFileRoute("))
|
|
143
|
+
} else if (fileIsInRoutesDirectory(id, userConfig.routesDirectory) && (code.includes("createRoute(") || code.includes("createFileRoute("))) {
|
|
144
144
|
if (code.includes("@react-refresh")) {
|
|
145
145
|
throw new Error(
|
|
146
146
|
`We detected that the '@vitejs/plugin-react' was passed before '@tanstack/router-vite-plugin'. Please make sure that '@tanstack/router-vite-plugin' is passed before '@vitejs/plugin-react' and try again:
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../src/index.ts"],"sourcesContent":["import { isAbsolute, join, normalize, resolve } from 'path'\nimport { fileURLToPath, pathToFileURL } from 'url'\nimport { z } from 'zod'\nimport {\n generator,\n configSchema as generatorConfigSchema,\n getConfig as getGeneratorConfig,\n} from '@tanstack/router-generator'\nimport { compileFile, makeCompile, splitFile } from './compilers'\nimport { splitPrefix } from './constants'\nimport type { Plugin } from 'vite'\n\nexport const configSchema = generatorConfigSchema.extend({\n enableRouteGeneration: z.boolean().optional(),\n experimental: z\n .object({\n enableCodeSplitting: z.boolean().optional(),\n })\n .optional(),\n})\n\nexport type Config = z.infer<typeof configSchema>\n\nconst CONFIG_FILE_NAME = 'tsr.config.json'\nconst debug = Boolean(process.env.TSR_VITE_DEBUG)\n\nconst getConfig = async (inlineConfig: Partial<Config>, root: string) => {\n const config = await getGeneratorConfig(inlineConfig, root)\n\n return configSchema.parse({ ...config, ...inlineConfig })\n}\n\nexport function TanStackRouterVite(\n inlineConfig: Partial<Config> = {},\n): Array<Plugin> {\n return [\n TanStackRouterViteGenerator(inlineConfig),\n TanStackRouterViteCodeSplitter(inlineConfig),\n ]\n}\n\nlet lock = false\n\nexport function TanStackRouterViteGenerator(\n inlineConfig: Partial<Config> = {},\n): Plugin {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n const generate = async () => {\n if (lock) {\n return\n }\n lock = true\n try {\n await generator(userConfig)\n } catch (err) {\n console.error(err)\n console.info()\n }\n lock = false\n }\n\n const handleFile = async (\n file: string,\n event: 'create' | 'update' | 'delete',\n ) => {\n const filePath = normalize(file)\n\n if (filePath === join(ROOT, CONFIG_FILE_NAME)) {\n userConfig = await getConfig(inlineConfig, ROOT)\n return\n }\n\n if (\n event === 'update' &&\n filePath === resolve(userConfig.generatedRouteTree)\n ) {\n // skip generating routes if the generated route tree is updated\n return\n }\n\n const routesDirectoryPath = isAbsolute(userConfig.routesDirectory)\n ? userConfig.routesDirectory\n : join(ROOT, userConfig.routesDirectory)\n\n if (filePath.startsWith(routesDirectoryPath)) {\n await generate()\n }\n }\n\n return {\n name: 'vite-plugin-tanstack-router-generator',\n configResolved: async (config) => {\n ROOT = process.cwd()\n userConfig = await getConfig(inlineConfig, ROOT)\n if (userConfig.enableRouteGeneration ?? true) {\n await generate()\n }\n },\n watchChange: async (file, context) => {\n if (userConfig.enableRouteGeneration ?? true) {\n if (['create', 'update', 'delete'].includes(context.event)) {\n await handleFile(file, context.event)\n }\n }\n },\n }\n}\n\nfunction fileIsInRoutesDirectory(filePath: string, routesDirectory: string) {\n const routesDirectoryPath = isAbsolute(routesDirectory)\n ? routesDirectory\n : join(process.cwd(), routesDirectory)\n\n return filePath.startsWith(routesDirectoryPath)\n}\n\nexport function TanStackRouterViteCodeSplitter(\n inlineConfig: Partial<Config> = {},\n): Plugin {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n return {\n name: 'vite-plugin-tanstack-router-code-splitter',\n enforce: 'pre',\n configResolved: async (config) => {\n ROOT = config.root\n userConfig = await getConfig(inlineConfig, ROOT)\n },\n resolveId(source) {\n if (!userConfig.experimental?.enableCodeSplitting) {\n return null\n }\n\n if (source.startsWith(splitPrefix + ':')) {\n return source.replace(splitPrefix + ':', '')\n }\n return null\n },\n async transform(code, id, transformOptions) {\n if (!userConfig.experimental?.enableCodeSplitting) {\n return null\n }\n\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n id = fileURLToPath(url).replace(/\\\\/g, '/')\n\n const compile = makeCompile({\n root: ROOT,\n })\n\n if (id.includes(splitPrefix)) {\n if (debug) console.info('Splitting route: ', id)\n // const ref = new URLSearchParams(id.split('?')[1]).get('ref') || ''\n\n const compiled = await splitFile({\n code,\n compile,\n filename: id,\n // ref,\n })\n\n if (debug) console.info('')\n if (debug) console.info('Split Output')\n if (debug) console.info('')\n if (debug) console.info(compiled.code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n return compiled\n } else if (\n (fileIsInRoutesDirectory(id, userConfig.routesDirectory) &&\n (code.includes('createRoute(') ||\n code.includes('createFileRoute('))) ||\n code.includes('createServerFn')\n ) {\n if (code.includes('@react-refresh')) {\n throw new Error(\n `We detected that the '@vitejs/plugin-react' was passed before '@tanstack/router-vite-plugin'. Please make sure that '@tanstack/router-vite-plugin' is passed before '@vitejs/plugin-react' and try again: \ne.g.\n\nplugins: [\n TanStackRouterVite(), // Place this before viteReact()\n viteReact(),\n]\n`,\n )\n }\n\n if (debug) console.info('Handling createRoute: ', id)\n const compiled = await compileFile({\n code,\n compile,\n filename: id,\n })\n\n if (debug) console.info('')\n if (debug) console.info('Compiled Output')\n if (debug) console.info('')\n if (debug) console.info(compiled.code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n return compiled\n }\n\n return null\n },\n }\n}\n"],"names":["generatorConfigSchema","getGeneratorConfig"],"mappings":";;;;;;AAYa,MAAA,eAAeA,eAAsB,OAAO;AAAA,EACvD,uBAAuB,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC5C,cAAc,EACX,OAAO;AAAA,IACN,qBAAqB,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC3C,CAAA,EACA,SAAS;AACd,CAAC;AAID,MAAM,mBAAmB;AACzB,MAAM,QAAQ,QAAQ,QAAQ,IAAI,cAAc;AAEhD,MAAM,YAAY,OAAO,cAA+B,SAAiB;AACvE,QAAM,SAAS,MAAMC,YAAmB,cAAc,IAAI;AAE1D,SAAO,aAAa,MAAM,EAAE,GAAG,QAAQ,GAAG,cAAc;AAC1D;AAEgB,SAAA,mBACd,eAAgC,IACjB;AACR,SAAA;AAAA,IACL,4BAA4B,YAAY;AAAA,IACxC,+BAA+B,YAAY;AAAA,EAAA;AAE/C;AAEA,IAAI,OAAO;AAEK,SAAA,4BACd,eAAgC,IACxB;AACJ,MAAA,OAAe,QAAQ;AACvB,MAAA;AAEJ,QAAM,WAAW,YAAY;AAC3B,QAAI,MAAM;AACR;AAAA,IACF;AACO,WAAA;AACH,QAAA;AACF,YAAM,UAAU,UAAU;AAAA,aACnB,KAAK;AACZ,cAAQ,MAAM,GAAG;AACjB,cAAQ,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,SAAS,kBAAkB,MACpC,KAAK,SAAS,gBAAgB,GAC9B;AACI,YAAA,KAAK,SAAS,gBAAgB,GAAG;AACnC,gBAAM,IAAI;AAAA,YACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAAA;AAAA,QASJ;AAEI,YAAA;AAAe,kBAAA,KAAK,0BAA0B,EAAE;AAC9C,cAAA,WAAW,MAAM,YAAY;AAAA,UACjC;AAAA,UACA;AAAA,UACA,UAAU;AAAA,QAAA,CACX;AAEG,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,iBAAiB;AACrC,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAe,kBAAA,KAAK,SAAS,IAAI;AACjC,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AAEnB,eAAA;AAAA,MACT;AAEO,aAAA;AAAA,IACT;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../src/index.ts"],"sourcesContent":["import { isAbsolute, join, normalize, resolve } from 'path'\nimport { fileURLToPath, pathToFileURL } from 'url'\nimport { z } from 'zod'\nimport {\n generator,\n configSchema as generatorConfigSchema,\n getConfig as getGeneratorConfig,\n} from '@tanstack/router-generator'\nimport { compileFile, makeCompile, splitFile } from './compilers'\nimport { splitPrefix } from './constants'\nimport type { Plugin } from 'vite'\n\nexport const configSchema = generatorConfigSchema.extend({\n enableRouteGeneration: z.boolean().optional(),\n experimental: z\n .object({\n enableCodeSplitting: z.boolean().optional(),\n })\n .optional(),\n})\n\nexport type Config = z.infer<typeof configSchema>\n\nconst CONFIG_FILE_NAME = 'tsr.config.json'\nconst debug = Boolean(process.env.TSR_VITE_DEBUG)\n\nconst getConfig = async (inlineConfig: Partial<Config>, root: string) => {\n const config = await getGeneratorConfig(inlineConfig, root)\n\n return configSchema.parse({ ...config, ...inlineConfig })\n}\n\nexport function TanStackRouterVite(\n inlineConfig: Partial<Config> = {},\n): Array<Plugin> {\n return [\n TanStackRouterViteGenerator(inlineConfig),\n TanStackRouterViteCodeSplitter(inlineConfig),\n ]\n}\n\nlet lock = false\n\nexport function TanStackRouterViteGenerator(\n inlineConfig: Partial<Config> = {},\n): Plugin {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n const generate = async () => {\n if (lock) {\n return\n }\n lock = true\n try {\n await generator(userConfig)\n } catch (err) {\n console.error(err)\n console.info()\n }\n lock = false\n }\n\n const handleFile = async (\n file: string,\n event: 'create' | 'update' | 'delete',\n ) => {\n const filePath = normalize(file)\n\n if (filePath === join(ROOT, CONFIG_FILE_NAME)) {\n userConfig = await getConfig(inlineConfig, ROOT)\n return\n }\n\n if (\n event === 'update' &&\n filePath === resolve(userConfig.generatedRouteTree)\n ) {\n // skip generating routes if the generated route tree is updated\n return\n }\n\n const routesDirectoryPath = isAbsolute(userConfig.routesDirectory)\n ? userConfig.routesDirectory\n : join(ROOT, userConfig.routesDirectory)\n\n if (filePath.startsWith(routesDirectoryPath)) {\n await generate()\n }\n }\n\n return {\n name: 'vite-plugin-tanstack-router-generator',\n configResolved: async (config) => {\n ROOT = process.cwd()\n userConfig = await getConfig(inlineConfig, ROOT)\n if (userConfig.enableRouteGeneration ?? true) {\n await generate()\n }\n },\n watchChange: async (file, context) => {\n if (userConfig.enableRouteGeneration ?? true) {\n if (['create', 'update', 'delete'].includes(context.event)) {\n await handleFile(file, context.event)\n }\n }\n },\n }\n}\n\nfunction fileIsInRoutesDirectory(filePath: string, routesDirectory: string) {\n const routesDirectoryPath = isAbsolute(routesDirectory)\n ? routesDirectory\n : join(process.cwd(), routesDirectory)\n\n return filePath.startsWith(routesDirectoryPath)\n}\n\nexport function TanStackRouterViteCodeSplitter(\n inlineConfig: Partial<Config> = {},\n): Plugin {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n return {\n name: 'vite-plugin-tanstack-router-code-splitter',\n enforce: 'pre',\n configResolved: async (config) => {\n ROOT = config.root\n userConfig = await getConfig(inlineConfig, ROOT)\n },\n resolveId(source) {\n if (!userConfig.experimental?.enableCodeSplitting) {\n return null\n }\n\n if (source.startsWith(splitPrefix + ':')) {\n return source.replace(splitPrefix + ':', '')\n }\n return null\n },\n async transform(code, id, transformOptions) {\n if (!userConfig.experimental?.enableCodeSplitting) {\n return null\n }\n\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n id = fileURLToPath(url).replace(/\\\\/g, '/')\n\n const compile = makeCompile({\n root: ROOT,\n })\n\n if (id.includes(splitPrefix)) {\n if (debug) console.info('Splitting route: ', id)\n // const ref = new URLSearchParams(id.split('?')[1]).get('ref') || ''\n\n const compiled = await splitFile({\n code,\n compile,\n filename: id,\n // ref,\n })\n\n if (debug) console.info('')\n if (debug) console.info('Split Output')\n if (debug) console.info('')\n if (debug) console.info(compiled.code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n return compiled\n } else if (\n fileIsInRoutesDirectory(id, userConfig.routesDirectory) &&\n (code.includes('createRoute(') || code.includes('createFileRoute('))\n ) {\n if (code.includes('@react-refresh')) {\n throw new Error(\n `We detected that the '@vitejs/plugin-react' was passed before '@tanstack/router-vite-plugin'. Please make sure that '@tanstack/router-vite-plugin' is passed before '@vitejs/plugin-react' and try again: \ne.g.\n\nplugins: [\n TanStackRouterVite(), // Place this before viteReact()\n viteReact(),\n]\n`,\n )\n }\n\n if (debug) console.info('Handling createRoute: ', id)\n const compiled = await compileFile({\n code,\n compile,\n filename: id,\n })\n\n if (debug) console.info('')\n if (debug) console.info('Compiled Output')\n if (debug) console.info('')\n if (debug) console.info(compiled.code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n return compiled\n }\n\n return null\n },\n }\n}\n"],"names":["generatorConfigSchema","getGeneratorConfig"],"mappings":";;;;;;AAYa,MAAA,eAAeA,eAAsB,OAAO;AAAA,EACvD,uBAAuB,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC5C,cAAc,EACX,OAAO;AAAA,IACN,qBAAqB,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC3C,CAAA,EACA,SAAS;AACd,CAAC;AAID,MAAM,mBAAmB;AACzB,MAAM,QAAQ,QAAQ,QAAQ,IAAI,cAAc;AAEhD,MAAM,YAAY,OAAO,cAA+B,SAAiB;AACvE,QAAM,SAAS,MAAMC,YAAmB,cAAc,IAAI;AAE1D,SAAO,aAAa,MAAM,EAAE,GAAG,QAAQ,GAAG,cAAc;AAC1D;AAEgB,SAAA,mBACd,eAAgC,IACjB;AACR,SAAA;AAAA,IACL,4BAA4B,YAAY;AAAA,IACxC,+BAA+B,YAAY;AAAA,EAAA;AAE/C;AAEA,IAAI,OAAO;AAEK,SAAA,4BACd,eAAgC,IACxB;AACJ,MAAA,OAAe,QAAQ;AACvB,MAAA;AAEJ,QAAM,WAAW,YAAY;AAC3B,QAAI,MAAM;AACR;AAAA,IACF;AACO,WAAA;AACH,QAAA;AACF,YAAM,UAAU,UAAU;AAAA,aACnB,KAAK;AACZ,cAAQ,MAAM,GAAG;AACjB,cAAQ,KAAK;AAAA,IACf;AACO,WAAA;AAAA,EAAA;AAGH,QAAA,aAAa,OACjB,M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BAAM,IAAI;AAAA,YACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAAA;AAAA,QASJ;AAEI,YAAA;AAAe,kBAAA,KAAK,0BAA0B,EAAE;AAC9C,cAAA,WAAW,MAAM,YAAY;AAAA,UACjC;AAAA,UACA;AAAA,UACA,UAAU;AAAA,QAAA,CACX;AAEG,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,iBAAiB;AACrC,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAe,kBAAA,KAAK,SAAS,IAAI;AACjC,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AACtB,YAAA;AAAO,kBAAQ,KAAK,EAAE;AAEnB,eAAA;AAAA,MACT;AAEO,aAAA;AAAA,IACT;AAAA,EAAA;AAEJ;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/router-vite-plugin",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.39.2",
|
|
4
4
|
"description": "",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -64,7 +64,8 @@
|
|
|
64
64
|
"@types/babel__traverse": "^7.20.5",
|
|
65
65
|
"@vitejs/plugin-react": "^4.2.1",
|
|
66
66
|
"zod": "^3.22.4",
|
|
67
|
-
"@tanstack/router-generator": "1.37.0"
|
|
67
|
+
"@tanstack/router-generator": "1.37.0",
|
|
68
|
+
"@tanstack/router-plugin": "^1.39.2"
|
|
68
69
|
},
|
|
69
70
|
"scripts": {}
|
|
70
71
|
}
|
package/src/compilers.ts
CHANGED
|
@@ -91,97 +91,7 @@ export async function compileFile(opts: {
|
|
|
91
91
|
{
|
|
92
92
|
CallExpression: (path) => {
|
|
93
93
|
if (path.node.callee.type === 'Identifier') {
|
|
94
|
-
if (
|
|
95
|
-
// If the function at createServerFn(_, MyFunc) doesn't have a
|
|
96
|
-
// 'use server' directive at the top of the function scope,
|
|
97
|
-
// then add it.
|
|
98
|
-
|
|
99
|
-
const fn = path.node.arguments[1]
|
|
100
|
-
|
|
101
|
-
if (
|
|
102
|
-
t.isFunctionExpression(fn) ||
|
|
103
|
-
t.isArrowFunctionExpression(fn)
|
|
104
|
-
) {
|
|
105
|
-
if (t.isBlockStatement(fn.body)) {
|
|
106
|
-
const hasUseServerDirective =
|
|
107
|
-
fn.body.directives.some((directive) => {
|
|
108
|
-
return (
|
|
109
|
-
directive.value.value === 'use server'
|
|
110
|
-
)
|
|
111
|
-
})
|
|
112
|
-
|
|
113
|
-
if (!hasUseServerDirective) {
|
|
114
|
-
fn.body.directives.unshift(
|
|
115
|
-
t.directive(
|
|
116
|
-
t.directiveLiteral('use server'),
|
|
117
|
-
),
|
|
118
|
-
)
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
} else if (
|
|
122
|
-
t.isIdentifier(fn) ||
|
|
123
|
-
t.isCallExpression(fn)
|
|
124
|
-
) {
|
|
125
|
-
// A function was passed to createServerFn in the form of an
|
|
126
|
-
// identifier or a call expression that returns a function.
|
|
127
|
-
|
|
128
|
-
// We wrap the identifier/call expression in a function
|
|
129
|
-
// expression that accepts the same arguments as the original
|
|
130
|
-
// function with the "use server" directive at the top of the
|
|
131
|
-
// function scope.
|
|
132
|
-
|
|
133
|
-
const args = t.restElement(t.identifier('args'))
|
|
134
|
-
|
|
135
|
-
// Annotate args with the type:
|
|
136
|
-
// Parameters<Parameters<typeof createServerFn>[1]>
|
|
137
|
-
|
|
138
|
-
args.typeAnnotation = t.tsTypeAnnotation(
|
|
139
|
-
t.tsTypeReference(
|
|
140
|
-
t.identifier('Parameters'),
|
|
141
|
-
t.tsTypeParameterInstantiation([
|
|
142
|
-
t.tsIndexedAccessType(
|
|
143
|
-
t.tsTypeReference(
|
|
144
|
-
t.identifier('Parameters'),
|
|
145
|
-
t.tsTypeParameterInstantiation([
|
|
146
|
-
t.tsTypeQuery(
|
|
147
|
-
t.identifier('createServerFn'),
|
|
148
|
-
),
|
|
149
|
-
]),
|
|
150
|
-
),
|
|
151
|
-
t.tsLiteralType(t.numericLiteral(1)),
|
|
152
|
-
),
|
|
153
|
-
]),
|
|
154
|
-
),
|
|
155
|
-
)
|
|
156
|
-
|
|
157
|
-
const wrappedFn = t.arrowFunctionExpression(
|
|
158
|
-
[args],
|
|
159
|
-
t.blockStatement(
|
|
160
|
-
[
|
|
161
|
-
t.returnStatement(
|
|
162
|
-
t.callExpression(
|
|
163
|
-
t.memberExpression(
|
|
164
|
-
fn,
|
|
165
|
-
t.identifier('apply'),
|
|
166
|
-
),
|
|
167
|
-
[
|
|
168
|
-
t.identifier('this'),
|
|
169
|
-
t.identifier('args'),
|
|
170
|
-
],
|
|
171
|
-
),
|
|
172
|
-
),
|
|
173
|
-
],
|
|
174
|
-
[
|
|
175
|
-
t.directive(
|
|
176
|
-
t.directiveLiteral('use server'),
|
|
177
|
-
),
|
|
178
|
-
],
|
|
179
|
-
),
|
|
180
|
-
)
|
|
181
|
-
|
|
182
|
-
path.node.arguments[1] = wrappedFn
|
|
183
|
-
}
|
|
184
|
-
} else if (
|
|
94
|
+
if (
|
|
185
95
|
path.node.callee.name === 'createRoute' ||
|
|
186
96
|
path.node.callee.name === 'createFileRoute'
|
|
187
97
|
) {
|
|
@@ -389,97 +299,7 @@ export async function splitFile(opts: {
|
|
|
389
299
|
{
|
|
390
300
|
CallExpression: (path) => {
|
|
391
301
|
if (path.node.callee.type === 'Identifier') {
|
|
392
|
-
if (
|
|
393
|
-
// If the function at createServerFn(_, MyFunc) doesn't have a
|
|
394
|
-
// 'use server' directive at the top of the function scope,
|
|
395
|
-
// then add it.
|
|
396
|
-
|
|
397
|
-
const fn = path.node.arguments[1]
|
|
398
|
-
|
|
399
|
-
if (
|
|
400
|
-
t.isFunctionExpression(fn) ||
|
|
401
|
-
t.isArrowFunctionExpression(fn)
|
|
402
|
-
) {
|
|
403
|
-
if (t.isBlockStatement(fn.body)) {
|
|
404
|
-
const hasUseServerDirective =
|
|
405
|
-
fn.body.directives.some((directive) => {
|
|
406
|
-
return (
|
|
407
|
-
directive.value.value === 'use server'
|
|
408
|
-
)
|
|
409
|
-
})
|
|
410
|
-
|
|
411
|
-
if (!hasUseServerDirective) {
|
|
412
|
-
fn.body.directives.unshift(
|
|
413
|
-
t.directive(
|
|
414
|
-
t.directiveLiteral('use server'),
|
|
415
|
-
),
|
|
416
|
-
)
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
} else if (
|
|
420
|
-
t.isIdentifier(fn) ||
|
|
421
|
-
t.isCallExpression(fn)
|
|
422
|
-
) {
|
|
423
|
-
// A function was passed to createServerFn in the form of an
|
|
424
|
-
// identifier or a call expression that returns a function.
|
|
425
|
-
|
|
426
|
-
// We wrap the identifier/call expression in a function
|
|
427
|
-
// expression that accepts the same arguments as the original
|
|
428
|
-
// function with the "use server" directive at the top of the
|
|
429
|
-
// function scope.
|
|
430
|
-
|
|
431
|
-
const args = t.restElement(t.identifier('args'))
|
|
432
|
-
|
|
433
|
-
// Annotate args with the type:
|
|
434
|
-
// Parameters<Parameters<typeof createServerFn>[1]>
|
|
435
|
-
|
|
436
|
-
args.typeAnnotation = t.tsTypeAnnotation(
|
|
437
|
-
t.tsTypeReference(
|
|
438
|
-
t.identifier('Parameters'),
|
|
439
|
-
t.tsTypeParameterInstantiation([
|
|
440
|
-
t.tsIndexedAccessType(
|
|
441
|
-
t.tsTypeReference(
|
|
442
|
-
t.identifier('Parameters'),
|
|
443
|
-
t.tsTypeParameterInstantiation([
|
|
444
|
-
t.tsTypeQuery(
|
|
445
|
-
t.identifier('createServerFn'),
|
|
446
|
-
),
|
|
447
|
-
]),
|
|
448
|
-
),
|
|
449
|
-
t.tsLiteralType(t.numericLiteral(1)),
|
|
450
|
-
),
|
|
451
|
-
]),
|
|
452
|
-
),
|
|
453
|
-
)
|
|
454
|
-
|
|
455
|
-
const wrappedFn = t.arrowFunctionExpression(
|
|
456
|
-
[args],
|
|
457
|
-
t.blockStatement(
|
|
458
|
-
[
|
|
459
|
-
t.returnStatement(
|
|
460
|
-
t.callExpression(
|
|
461
|
-
t.memberExpression(
|
|
462
|
-
fn,
|
|
463
|
-
t.identifier('apply'),
|
|
464
|
-
),
|
|
465
|
-
[
|
|
466
|
-
t.identifier('this'),
|
|
467
|
-
t.identifier('args'),
|
|
468
|
-
],
|
|
469
|
-
),
|
|
470
|
-
),
|
|
471
|
-
],
|
|
472
|
-
[
|
|
473
|
-
t.directive(
|
|
474
|
-
t.directiveLiteral('use server'),
|
|
475
|
-
),
|
|
476
|
-
],
|
|
477
|
-
),
|
|
478
|
-
)
|
|
479
|
-
|
|
480
|
-
path.node.arguments[1] = wrappedFn
|
|
481
|
-
}
|
|
482
|
-
} else if (
|
|
302
|
+
if (
|
|
483
303
|
path.node.callee.name === 'createRoute' ||
|
|
484
304
|
path.node.callee.name === 'createFileRoute'
|
|
485
305
|
) {
|
package/src/index.ts
CHANGED
|
@@ -178,10 +178,8 @@ export function TanStackRouterViteCodeSplitter(
|
|
|
178
178
|
|
|
179
179
|
return compiled
|
|
180
180
|
} else if (
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
code.includes('createFileRoute('))) ||
|
|
184
|
-
code.includes('createServerFn')
|
|
181
|
+
fileIsInRoutesDirectory(id, userConfig.routesDirectory) &&
|
|
182
|
+
(code.includes('createRoute(') || code.includes('createFileRoute('))
|
|
185
183
|
) {
|
|
186
184
|
if (code.includes('@react-refresh')) {
|
|
187
185
|
throw new Error(
|