@tanstack/router-vite-plugin 1.39.3 → 1.39.5

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/src/index.ts CHANGED
@@ -1,225 +1,2 @@
1
- import { isAbsolute, join, normalize, resolve } from 'path'
2
- import { fileURLToPath, pathToFileURL } from 'url'
3
- import { z } from 'zod'
4
- import {
5
- generator,
6
- configSchema as generatorConfigSchema,
7
- getConfig as getGeneratorConfig,
8
- } from '@tanstack/router-generator'
9
- import { compileFile, makeCompile, splitFile } from './compilers'
10
- import { splitPrefix } from './constants'
11
- import type { Plugin } from 'vite'
12
-
13
- export const configSchema = generatorConfigSchema.extend({
14
- enableRouteGeneration: z.boolean().optional(),
15
- experimental: z
16
- .object({
17
- enableCodeSplitting: z.boolean().optional(),
18
- })
19
- .optional(),
20
- })
21
-
22
- export type Config = z.infer<typeof configSchema>
23
-
24
- const CONFIG_FILE_NAME = 'tsr.config.json'
25
- const debug = Boolean(process.env.TSR_VITE_DEBUG)
26
-
27
- const getConfig = async (inlineConfig: Partial<Config>, root: string) => {
28
- const config = await getGeneratorConfig(inlineConfig, root)
29
-
30
- return configSchema.parse({ ...config, ...inlineConfig })
31
- }
32
-
33
- export function TanStackRouterVite(
34
- inlineConfig: Partial<Config> = {},
35
- ): Array<Plugin> {
36
- return [
37
- TanStackRouterViteGenerator(inlineConfig),
38
- TanStackRouterViteCodeSplitter(inlineConfig),
39
- ]
40
- }
41
-
42
- let lock = false
43
-
44
- export function TanStackRouterViteGenerator(
45
- inlineConfig: Partial<Config> = {},
46
- ): Plugin {
47
- let ROOT: string = process.cwd()
48
- let userConfig: Config
49
-
50
- const generate = async () => {
51
- if (lock) {
52
- return
53
- }
54
- lock = true
55
- try {
56
- await generator(userConfig)
57
- } catch (err) {
58
- console.error(err)
59
- console.info()
60
- }
61
- lock = false
62
- }
63
-
64
- const handleFile = async (
65
- file: string,
66
- event: 'create' | 'update' | 'delete',
67
- ) => {
68
- const filePath = normalize(file)
69
-
70
- if (filePath === join(ROOT, CONFIG_FILE_NAME)) {
71
- userConfig = await getConfig(inlineConfig, ROOT)
72
- return
73
- }
74
-
75
- if (
76
- event === 'update' &&
77
- filePath === resolve(userConfig.generatedRouteTree)
78
- ) {
79
- // skip generating routes if the generated route tree is updated
80
- return
81
- }
82
-
83
- const routesDirectoryPath = isAbsolute(userConfig.routesDirectory)
84
- ? userConfig.routesDirectory
85
- : join(ROOT, userConfig.routesDirectory)
86
-
87
- if (filePath.startsWith(routesDirectoryPath)) {
88
- await generate()
89
- }
90
- }
91
-
92
- return {
93
- name: 'vite-plugin-tanstack-router-generator',
94
- configResolved: async (config) => {
95
- ROOT = process.cwd()
96
- userConfig = await getConfig(inlineConfig, ROOT)
97
- if (userConfig.enableRouteGeneration ?? true) {
98
- await generate()
99
- }
100
- },
101
- watchChange: async (file, context) => {
102
- if (userConfig.enableRouteGeneration ?? true) {
103
- if (['create', 'update', 'delete'].includes(context.event)) {
104
- await handleFile(file, context.event)
105
- }
106
- }
107
- },
108
- }
109
- }
110
-
111
- function fileIsInRoutesDirectory(filePath: string, routesDirectory: string) {
112
- const routesDirectoryPath = isAbsolute(routesDirectory)
113
- ? routesDirectory
114
- : join(process.cwd(), routesDirectory)
115
-
116
- return filePath.startsWith(routesDirectoryPath)
117
- }
118
-
119
- export function TanStackRouterViteCodeSplitter(
120
- inlineConfig: Partial<Config> = {},
121
- ): Plugin {
122
- let ROOT: string = process.cwd()
123
- let userConfig: Config
124
-
125
- return {
126
- name: 'vite-plugin-tanstack-router-code-splitter',
127
- enforce: 'pre',
128
- configResolved: async (config) => {
129
- ROOT = config.root
130
- userConfig = await getConfig(inlineConfig, ROOT)
131
- },
132
- resolveId(source) {
133
- if (!userConfig.experimental?.enableCodeSplitting) {
134
- return null
135
- }
136
-
137
- if (source.startsWith(splitPrefix + ':')) {
138
- return source.replace(splitPrefix + ':', '')
139
- }
140
- return null
141
- },
142
- async transform(code, id, transformOptions) {
143
- if (!userConfig.experimental?.enableCodeSplitting) {
144
- return null
145
- }
146
-
147
- const url = pathToFileURL(id)
148
- url.searchParams.delete('v')
149
- id = fileURLToPath(url).replace(/\\/g, '/')
150
-
151
- const compile = makeCompile({
152
- root: ROOT,
153
- })
154
-
155
- if (id.includes(splitPrefix)) {
156
- if (debug) console.info('Splitting route: ', id)
157
- // const ref = new URLSearchParams(id.split('?')[1]).get('ref') || ''
158
-
159
- const compiled = await splitFile({
160
- code,
161
- compile,
162
- filename: id,
163
- // ref,
164
- })
165
-
166
- if (debug) console.info('')
167
- if (debug) console.info('Split Output')
168
- if (debug) console.info('')
169
- if (debug) console.info(compiled.code)
170
- if (debug) console.info('')
171
- if (debug) console.info('')
172
- if (debug) console.info('')
173
- if (debug) console.info('')
174
- if (debug) console.info('')
175
- if (debug) console.info('')
176
- if (debug) console.info('')
177
- if (debug) console.info('')
178
-
179
- return compiled
180
- } else if (
181
- fileIsInRoutesDirectory(id, userConfig.routesDirectory) &&
182
- (code.includes('createRoute(') || code.includes('createFileRoute('))
183
- ) {
184
- if (code.includes('@react-refresh')) {
185
- throw new Error(
186
- `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:
187
- e.g.
188
-
189
- plugins: [
190
- TanStackRouterVite(), // Place this before viteReact()
191
- viteReact(),
192
- ]
193
- `,
194
- )
195
- }
196
-
197
- if (debug) console.info('Handling createRoute: ', id)
198
- const compiled = await compileFile({
199
- code,
200
- compile,
201
- filename: id,
202
- })
203
-
204
- if (debug) console.info('')
205
- if (debug) console.info('Compiled Output')
206
- if (debug) console.info('')
207
- if (debug) console.info(compiled.code)
208
- if (debug) console.info('')
209
- if (debug) console.info('')
210
- if (debug) console.info('')
211
- if (debug) console.info('')
212
- if (debug) console.info('')
213
- if (debug) console.info('')
214
- if (debug) console.info('')
215
- if (debug) console.info('')
216
- if (debug) console.info('')
217
- if (debug) console.info('')
218
-
219
- return compiled
220
- }
221
-
222
- return null
223
- },
224
- }
225
- }
1
+ export * from '@tanstack/router-plugin/vite'
2
+ export type * from '@tanstack/router-plugin/vite'
@@ -1,359 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const t = require("@babel/types");
4
- const template = require("@babel/template");
5
- const babel = require("@babel/core");
6
- const constants = require("./constants.cjs");
7
- const eliminateUnreferencedIdentifiers = require("./eliminateUnreferencedIdentifiers.cjs");
8
- function _interopNamespaceDefault(e) {
9
- const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
10
- if (e) {
11
- for (const k in e) {
12
- if (k !== "default") {
13
- const d = Object.getOwnPropertyDescriptor(e, k);
14
- Object.defineProperty(n, k, d.get ? d : {
15
- enumerable: true,
16
- get: () => e[k]
17
- });
18
- }
19
- }
20
- }
21
- n.default = e;
22
- return Object.freeze(n);
23
- }
24
- const t__namespace = /* @__PURE__ */ _interopNamespaceDefault(t);
25
- const template__namespace = /* @__PURE__ */ _interopNamespaceDefault(template);
26
- const babel__namespace = /* @__PURE__ */ _interopNamespaceDefault(babel);
27
- function makeCompile(makeOpts) {
28
- return async (opts) => {
29
- const res = await babel__namespace.transform(opts.code, {
30
- plugins: [
31
- ["@babel/plugin-syntax-jsx", {}],
32
- [
33
- "@babel/plugin-syntax-typescript",
34
- {
35
- isTSX: true
36
- }
37
- ],
38
- ...opts.getBabelConfig().plugins
39
- ],
40
- root: makeOpts.root,
41
- filename: opts.filename,
42
- sourceMaps: true
43
- });
44
- if (res == null ? void 0 : res.code) {
45
- return {
46
- code: res.code,
47
- map: res.map
48
- };
49
- }
50
- return {
51
- code: opts.code,
52
- map: null
53
- };
54
- };
55
- }
56
- async function compileFile(opts) {
57
- return await opts.compile({
58
- code: opts.code,
59
- filename: opts.filename,
60
- getBabelConfig: () => ({
61
- plugins: [
62
- [
63
- {
64
- visitor: {
65
- Program: {
66
- enter(programPath, state) {
67
- const splitUrl = `${constants.splitPrefix}:${opts.filename}?${constants.splitPrefix}`;
68
- programPath.traverse(
69
- {
70
- CallExpression: (path) => {
71
- if (path.node.callee.type === "Identifier") {
72
- if (path.node.callee.name === "createRoute" || path.node.callee.name === "createFileRoute") {
73
- if (path.parentPath.node.type === "CallExpression") {
74
- const options = resolveIdentifier(
75
- path,
76
- path.parentPath.node.arguments[0]
77
- );
78
- let found = false;
79
- const hasImportedOrDefinedIdentifier = (name) => {
80
- return programPath.scope.hasBinding(name);
81
- };
82
- if (t__namespace.isObjectExpression(options)) {
83
- options.properties.forEach((prop) => {
84
- if (t__namespace.isObjectProperty(prop)) {
85
- if (t__namespace.isIdentifier(prop.key)) {
86
- if (prop.key.name === "component") {
87
- const value = prop.value;
88
- if (t__namespace.isIdentifier(value)) {
89
- removeIdentifierLiteral(path, value);
90
- }
91
- if (!hasImportedOrDefinedIdentifier(
92
- "lazyRouteComponent"
93
- )) {
94
- programPath.unshiftContainer("body", [
95
- template__namespace.smart(
96
- `import { lazyRouteComponent } from '@tanstack/react-router'`
97
- )()
98
- ]);
99
- }
100
- if (!hasImportedOrDefinedIdentifier(
101
- "$$splitComponentImporter"
102
- )) {
103
- programPath.unshiftContainer("body", [
104
- template__namespace.smart(
105
- `const $$splitComponentImporter = () => import('${splitUrl}')`
106
- )()
107
- ]);
108
- }
109
- prop.value = template__namespace.expression(
110
- `lazyRouteComponent($$splitComponentImporter, 'component')`
111
- )();
112
- programPath.pushContainer("body", [
113
- template__namespace.smart(
114
- `function DummyComponent() { return null }`
115
- )()
116
- ]);
117
- found = true;
118
- } else if (prop.key.name === "loader") {
119
- const value = prop.value;
120
- if (t__namespace.isIdentifier(value)) {
121
- removeIdentifierLiteral(path, value);
122
- }
123
- if (!hasImportedOrDefinedIdentifier(
124
- "lazyFn"
125
- )) {
126
- programPath.unshiftContainer("body", [
127
- template__namespace.smart(
128
- `import { lazyFn } from '@tanstack/react-router'`
129
- )()
130
- ]);
131
- }
132
- if (!hasImportedOrDefinedIdentifier(
133
- "$$splitLoaderImporter"
134
- )) {
135
- programPath.unshiftContainer("body", [
136
- template__namespace.smart(
137
- `const $$splitLoaderImporter = () => import('${splitUrl}')`
138
- )()
139
- ]);
140
- }
141
- prop.value = template__namespace.expression(
142
- `lazyFn($$splitLoaderImporter, 'loader')`
143
- )();
144
- found = true;
145
- }
146
- }
147
- }
148
- programPath.scope.crawl();
149
- });
150
- }
151
- if (found) {
152
- programPath.pushContainer("body", [
153
- template__namespace.smart(
154
- `function TSR_Dummy_Component() {}`
155
- )()
156
- ]);
157
- }
158
- }
159
- }
160
- }
161
- }
162
- },
163
- state
164
- );
165
- eliminateUnreferencedIdentifiers.eliminateUnreferencedIdentifiers(programPath);
166
- }
167
- }
168
- }
169
- },
170
- {
171
- root: process.cwd(),
172
- minify: process.env.NODE_ENV === "production"
173
- }
174
- ]
175
- ].filter(Boolean)
176
- })
177
- });
178
- }
179
- function resolveIdentifier(path, node) {
180
- if (t__namespace.isIdentifier(node)) {
181
- const binding = path.scope.getBinding(node.name);
182
- if (binding) {
183
- const declarator = binding.path.node;
184
- if (t__namespace.isObjectExpression(declarator.init)) {
185
- return declarator.init;
186
- } else if (t__namespace.isFunctionDeclaration(declarator.init)) {
187
- return declarator.init;
188
- }
189
- }
190
- return void 0;
191
- }
192
- return node;
193
- }
194
- function removeIdentifierLiteral(path, node) {
195
- if (t__namespace.isIdentifier(node)) {
196
- const binding = path.scope.getBinding(node.name);
197
- if (binding) {
198
- binding.path.remove();
199
- }
200
- }
201
- }
202
- const splitNodeTypes = ["component", "loader"];
203
- async function splitFile(opts) {
204
- return await opts.compile({
205
- code: opts.code,
206
- filename: opts.filename,
207
- getBabelConfig: () => ({
208
- plugins: [
209
- [
210
- {
211
- visitor: {
212
- Program: {
213
- enter(programPath, state) {
214
- const splitNodesByType = {
215
- component: void 0,
216
- loader: void 0
217
- };
218
- programPath.traverse(
219
- {
220
- CallExpression: (path) => {
221
- if (path.node.callee.type === "Identifier") {
222
- if (path.node.callee.name === "createRoute" || path.node.callee.name === "createFileRoute") {
223
- if (path.parentPath.node.type === "CallExpression") {
224
- const options = resolveIdentifier(
225
- path,
226
- path.parentPath.node.arguments[0]
227
- );
228
- if (t__namespace.isObjectExpression(options)) {
229
- options.properties.forEach((prop) => {
230
- if (t__namespace.isObjectProperty(prop)) {
231
- splitNodeTypes.forEach((type) => {
232
- if (t__namespace.isIdentifier(prop.key)) {
233
- if (prop.key.name === type) {
234
- splitNodesByType[type] = prop.value;
235
- }
236
- }
237
- });
238
- }
239
- });
240
- options.properties = [];
241
- }
242
- }
243
- }
244
- }
245
- }
246
- },
247
- state
248
- );
249
- splitNodeTypes.forEach((splitType) => {
250
- let splitNode = splitNodesByType[splitType];
251
- if (!splitNode) {
252
- return;
253
- }
254
- while (t__namespace.isIdentifier(splitNode)) {
255
- const binding = programPath.scope.getBinding(
256
- splitNode.name
257
- );
258
- splitNode = binding == null ? void 0 : binding.path.node;
259
- }
260
- if (splitNode) {
261
- if (t__namespace.isFunctionDeclaration(splitNode)) {
262
- programPath.pushContainer(
263
- "body",
264
- t__namespace.variableDeclaration("const", [
265
- t__namespace.variableDeclarator(
266
- t__namespace.identifier(splitType),
267
- t__namespace.functionExpression(
268
- splitNode.id || null,
269
- // Anonymize the function expression
270
- splitNode.params,
271
- splitNode.body,
272
- splitNode.generator,
273
- splitNode.async
274
- )
275
- )
276
- ])
277
- );
278
- } else if (t__namespace.isFunctionExpression(splitNode) || t__namespace.isArrowFunctionExpression(splitNode)) {
279
- programPath.pushContainer(
280
- "body",
281
- t__namespace.variableDeclaration("const", [
282
- t__namespace.variableDeclarator(
283
- t__namespace.identifier(splitType),
284
- splitNode
285
- )
286
- ])
287
- );
288
- } else if (t__namespace.isImportSpecifier(splitNode)) {
289
- programPath.pushContainer(
290
- "body",
291
- t__namespace.variableDeclaration("const", [
292
- t__namespace.variableDeclarator(
293
- t__namespace.identifier(splitType),
294
- splitNode.local
295
- )
296
- ])
297
- );
298
- } else {
299
- console.info(splitNode);
300
- throw new Error(
301
- `Unexpected splitNode type ☝️: ${splitNode.type}`
302
- );
303
- }
304
- }
305
- programPath.node.body = programPath.node.body.filter(
306
- (node) => {
307
- return node !== splitNode;
308
- }
309
- );
310
- programPath.pushContainer("body", [
311
- t__namespace.exportNamedDeclaration(null, [
312
- t__namespace.exportSpecifier(
313
- t__namespace.identifier(splitType),
314
- t__namespace.identifier(splitType)
315
- )
316
- ])
317
- ]);
318
- });
319
- programPath.traverse({
320
- ExportNamedDeclaration(path) {
321
- if (path.node.declaration) {
322
- if (t__namespace.isVariableDeclaration(path.node.declaration)) {
323
- path.replaceWith(
324
- t__namespace.importDeclaration(
325
- path.node.declaration.declarations.map(
326
- (decl) => t__namespace.importSpecifier(
327
- t__namespace.identifier(decl.id.name),
328
- t__namespace.identifier(decl.id.name)
329
- )
330
- ),
331
- t__namespace.stringLiteral(
332
- opts.filename.split(
333
- `?${constants.splitPrefix}`
334
- )[0]
335
- )
336
- )
337
- );
338
- }
339
- }
340
- }
341
- });
342
- eliminateUnreferencedIdentifiers.eliminateUnreferencedIdentifiers(programPath);
343
- }
344
- }
345
- }
346
- },
347
- {
348
- root: process.cwd(),
349
- minify: process.env.NODE_ENV === "production"
350
- }
351
- ]
352
- ].filter(Boolean)
353
- })
354
- });
355
- }
356
- exports.compileFile = compileFile;
357
- exports.makeCompile = makeCompile;
358
- exports.splitFile = splitFile;
359
- //# sourceMappingURL=compilers.cjs.map
@@ -1 +0,0 @@
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;;;;"}
@@ -1,38 +0,0 @@
1
- export type CompileFn = (compileOpts: {
2
- code: string;
3
- filename: string;
4
- getBabelConfig: () => {
5
- plugins: Array<any>;
6
- };
7
- }) => Promise<{
8
- code: string;
9
- map: any;
10
- }>;
11
- export declare function makeCompile(makeOpts: {
12
- root: string;
13
- }): (opts: {
14
- code: string;
15
- filename: string;
16
- getBabelConfig: () => {
17
- plugins: Array<any>;
18
- };
19
- }) => Promise<{
20
- code: string;
21
- map: any;
22
- }>;
23
- export declare function compileFile(opts: {
24
- code: string;
25
- compile: CompileFn;
26
- filename: string;
27
- }): Promise<{
28
- code: string;
29
- map: any;
30
- }>;
31
- export declare function splitFile(opts: {
32
- code: string;
33
- compile: CompileFn;
34
- filename: string;
35
- }): Promise<{
36
- code: string;
37
- map: any;
38
- }>;
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const splitPrefix = "tsr-split";
4
- exports.splitPrefix = splitPrefix;
5
- //# sourceMappingURL=constants.cjs.map