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

plugin.ts

403 lines14.3 KB

1import { joinPaths } from '@tanstack/router-core'
2import * as vite from 'vite'
3import { crawlFrameworkPkgs } from 'vitefu'
4import { join } from 'pathe'
5import { escapePath } from 'tinyglobby'
6import { startManifestPlugin } from './start-manifest-plugin/plugin'
7import { ENTRY_POINTS, VITE_ENVIRONMENT_NAMES } from './constants'
8import { tanStackStartRouter } from './start-router-plugin/plugin'
9import { loadEnvPlugin } from './load-env-plugin/plugin'
10import { devServerPlugin } from './dev-server-plugin/plugin'
11import { previewServerPlugin } from './preview-server-plugin/plugin'
12import { parseStartConfig } from './schema'
13import { resolveEntry } from './resolve-entries'
14import {
15 getClientOutputDirectory,
16 getServerOutputDirectory,
17} from './output-directory'
18import { postServerBuild } from './post-server-build'
19import { startCompilerPlugin } from './start-compiler-plugin/plugin'
20import type {
21 GetConfigFn,
22 ResolvedStartConfig,
23 TanStackStartVitePluginCoreOptions,
24} from './types'
25import type { ViteEnvironmentNames } from './constants'
26import type {
27 TanStackStartInputConfig,
28 TanStackStartOutputConfig,
29} from './schema'
30import type { PluginOption } from 'vite'
31​
32function isFullUrl(str: string): boolean {
33 try {
34 new URL(str)
35 return true
36 } catch {
37 return false
38 }
40​
41export function TanStackStartVitePluginCore(
42 corePluginOpts: TanStackStartVitePluginCoreOptions,
43 startPluginOpts: TanStackStartInputConfig,
44): Array<PluginOption> {
45 // Determine the provider environment for server functions
46 // If providerEnv is set, use that; otherwise default to SSR as the provider
47 const serverFnProviderEnv =
48 corePluginOpts.serverFn?.providerEnv || VITE_ENVIRONMENT_NAMES.server
49 const ssrIsProvider = serverFnProviderEnv === VITE_ENVIRONMENT_NAMES.server
50​
51 const resolvedStartConfig: ResolvedStartConfig = {
52 root: '',
53 startFilePath: undefined,
54 routerFilePath: '',
55 srcDirectory: '',
56 viteAppBase: '',
57 serverFnProviderEnv,
58 }
59​
60 let startConfig: TanStackStartOutputConfig | null
61 const getConfig: GetConfigFn = () => {
62 if (!resolvedStartConfig.root) {
63 throw new Error(`Cannot get config before root is resolved`)
64 }
65 if (!startConfig) {
66 startConfig = parseStartConfig(
67 startPluginOpts,
68 corePluginOpts,
69 resolvedStartConfig.root,
70 )
71 }
72 return { startConfig, resolvedStartConfig, corePluginOpts }
73 }
74​
75 const capturedBundle: Partial<
76 Record<ViteEnvironmentNames, vite.Rollup.OutputBundle>
77 > = {}
78​
79 function getBundle(envName: ViteEnvironmentNames): vite.Rollup.OutputBundle {
80 const bundle = capturedBundle[envName]
81 if (!bundle) {
82 throw new Error(`No bundle captured for environment: ${envName}`)
83 }
84 return bundle
85 }
86​
87 const environments: Array<{ name: string; type: 'client' | 'server' }> = [
88 { name: VITE_ENVIRONMENT_NAMES.client, type: 'client' },
89 { name: VITE_ENVIRONMENT_NAMES.server, type: 'server' },
90 ]
91 if (
92 corePluginOpts.serverFn?.providerEnv &&
93 !environments.find((e) => e.name === corePluginOpts.serverFn?.providerEnv)
94 ) {
95 environments.push({
96 name: corePluginOpts.serverFn.providerEnv,
97 type: 'server',
98 })
99 }
100 return [
101 {
102 name: 'tanstack-start-core:config',
103 enforce: 'pre',
104 async config(viteConfig, { command }) {
105 resolvedStartConfig.viteAppBase = viteConfig.base ?? '/'
106 if (!isFullUrl(resolvedStartConfig.viteAppBase)) {
107 resolvedStartConfig.viteAppBase = joinPaths([
108 '/',
109 viteConfig.base,
110 '/',
111 ])
112 }
113 const root = viteConfig.root || process.cwd()
114 resolvedStartConfig.root = root
115​
116 const { startConfig } = getConfig()
117 if (startConfig.router.basepath === undefined) {
118 if (!isFullUrl(resolvedStartConfig.viteAppBase)) {
119 startConfig.router.basepath =
120 resolvedStartConfig.viteAppBase.replace(/^\/|\/$/g, '')
121 } else {
122 startConfig.router.basepath = '/'
123 }
124 } else {
125 if (command === 'serve' && !viteConfig.server?.middlewareMode) {
126 // when serving, we must ensure that router basepath and viteAppBase are aligned
127 if (
128 !joinPaths(['/', startConfig.router.basepath, '/']).startsWith(
129 joinPaths(['/', resolvedStartConfig.viteAppBase, '/']),
130 )
131 ) {
132 this.error(
133 '[tanstack-start]: During `vite dev`, `router.basepath` must start with the vite `base` config value',
134 )
135 }
136 }
137 }
138​
139 const TSS_SERVER_FN_BASE = joinPaths([
140 '/',
141 startConfig.router.basepath,
142 startConfig.serverFns.base,
143 '/',
144 ])
145 const resolvedSrcDirectory = join(root, startConfig.srcDirectory)
146 resolvedStartConfig.srcDirectory = resolvedSrcDirectory
147​
148 const startFilePath = resolveEntry({
149 type: 'start entry',
150 configuredEntry: startConfig.start.entry,
151 defaultEntry: 'start',
152 resolvedSrcDirectory,
153 required: false,
154 })
155 resolvedStartConfig.startFilePath = startFilePath
156​
157 const routerFilePath = resolveEntry({
158 type: 'router entry',
159 configuredEntry: startConfig.router.entry,
160 defaultEntry: 'router',
161 resolvedSrcDirectory,
162 required: true,
163 })
164 resolvedStartConfig.routerFilePath = routerFilePath
165​
166 const clientEntryPath = resolveEntry({
167 type: 'client entry',
168 configuredEntry: startConfig.client.entry,
169 defaultEntry: 'client',
170 resolvedSrcDirectory,
171 required: false,
172 })
173​
174 const serverEntryPath = resolveEntry({
175 type: 'server entry',
176 configuredEntry: startConfig.server.entry,
177 defaultEntry: 'server',
178 resolvedSrcDirectory,
179 required: false,
180 })
181​
182 const clientAlias = vite.normalizePath(
183 clientEntryPath ?? corePluginOpts.defaultEntryPaths.client,
184 )
185 const serverAlias = vite.normalizePath(
186 serverEntryPath ?? corePluginOpts.defaultEntryPaths.server,
187 )
188 const startAlias = vite.normalizePath(
189 startFilePath ?? corePluginOpts.defaultEntryPaths.start,
190 )
191 const routerAlias = vite.normalizePath(routerFilePath)
192​
193 const entryAliasConfiguration: Record<
194 (typeof ENTRY_POINTS)[keyof typeof ENTRY_POINTS],
195 string
196 > = {
197 [ENTRY_POINTS.client]: clientAlias,
198 [ENTRY_POINTS.server]: serverAlias,
199 [ENTRY_POINTS.start]: startAlias,
200 [ENTRY_POINTS.router]: routerAlias,
201 }
202​
203 const startPackageName =
204 `@tanstack/${corePluginOpts.framework}-start` as const
205​
206 // crawl packages that have start in "peerDependencies"
207 // see https://github.com/svitejs/vitefu/blob/d8d82fa121e3b2215ba437107093c77bde51b63b/src/index.js#L95-L101
208​
209 // this is currently uncached; could be implemented similarly as vite handles lock file changes
210 // see https://github.com/vitejs/vite/blob/557f797d29422027e8c451ca50dd84bf8c41b5f0/packages/vite/src/node/optimizer/index.ts#L1282
211​
212 const crawlFrameworkPkgsResult = await crawlFrameworkPkgs({
213 root: process.cwd(),
214 isBuild: command === 'build',
215 isFrameworkPkgByJson(pkgJson) {
216 const peerDependencies = pkgJson['peerDependencies']
217​
218 if (peerDependencies) {
219 if (
220 startPackageName in peerDependencies ||
221 '@tanstack/start-client-core' in peerDependencies
222 ) {
223 return true
224 }
225 }
226​
227 return false
228 },
229 })
230​
231 return {
232 // see https://vite.dev/config/shared-options.html#apptype
233 // this will prevent vite from injecting middlewares that we don't want
234 appType: viteConfig.appType ?? 'custom',
235 environments: {
236 [VITE_ENVIRONMENT_NAMES.client]: {
237 consumer: 'client',
238 build: {
239 rollupOptions: {
240 input: {
241 main: ENTRY_POINTS.client,
242 },
243 },
244 outDir: getClientOutputDirectory(viteConfig),
245 },
246 optimizeDeps: {
247 exclude: crawlFrameworkPkgsResult.optimizeDeps.exclude,
248 // Ensure user code can be crawled for dependencies
249 entries: [clientAlias, routerAlias].map((entry) =>
250 // Entries are treated as `tinyglobby` patterns so need to be escaped
251 escapePath(entry),
252 ),
253 },
254 },
255 [VITE_ENVIRONMENT_NAMES.server]: {
256 consumer: 'server',
257 build: {
258 ssr: true,
259 rollupOptions: {
260 input:
261 viteConfig.environments?.[VITE_ENVIRONMENT_NAMES.server]
262 ?.build?.rollupOptions?.input ?? serverAlias,
263 },
264 outDir: getServerOutputDirectory(viteConfig),
265 commonjsOptions: {
266 include: [/node_modules/],
267 },
268 copyPublicDir:
269 viteConfig.environments?.[VITE_ENVIRONMENT_NAMES.server]
270 ?.build?.copyPublicDir ?? false,
271 },
272 optimizeDeps: {
273 // Ensure user code can be crawled for dependencies
274 entries: [serverAlias, startAlias, routerAlias].map((entry) =>
275 // Entries are treated as `tinyglobby` patterns so need to be escaped
276 escapePath(entry),
277 ),
278 },
279 },
280 },
281​
282 resolve: {
283 noExternal: [
284 // ENTRY_POINTS.start,
285 '@tanstack/start**',
286 `@tanstack/${corePluginOpts.framework}-start**`,
287 ...crawlFrameworkPkgsResult.ssr.noExternal.sort(),
288 ],
289 alias: {
290 ...entryAliasConfiguration,
291 },
292 },
293 /* prettier-ignore */
294 define: {
295 // define is an esbuild function that replaces the any instances of given keys with the given values
296 // i.e: __FRAMEWORK_NAME__ can be replaced with JSON.stringify("TanStack Start")
297 // This is not the same as injecting environment variables.
298​
299 ...defineReplaceEnv('TSS_SERVER_FN_BASE', TSS_SERVER_FN_BASE),
300 ...defineReplaceEnv('TSS_CLIENT_OUTPUT_DIR', getClientOutputDirectory(viteConfig)),
301 ...defineReplaceEnv('TSS_ROUTER_BASEPATH', startConfig.router.basepath),
302 ...(command === 'serve' ? defineReplaceEnv('TSS_SHELL', startConfig.spa?.enabled ? 'true' : 'false') : {}),
303 ...defineReplaceEnv('TSS_DEV_SERVER', command === 'serve' ? 'true' : 'false'),
304 },
305 builder: {
306 sharedPlugins: true,
307 async buildApp(builder) {
308 const client = builder.environments[VITE_ENVIRONMENT_NAMES.client]
309 const server = builder.environments[VITE_ENVIRONMENT_NAMES.server]
310​
311 if (!client) {
312 throw new Error('Client environment not found')
313 }
314​
315 if (!server) {
316 throw new Error('SSR environment not found')
317 }
318​
319 if (!client.isBuilt) {
320 // Build the client bundle first
321 await builder.build(client)
322 }
323 if (!server.isBuilt) {
324 // Build the SSR bundle
325 await builder.build(server)
326 }
327​
328 // If a custom provider environment is configured (not SSR),
329 // build it last so the manifest includes functions from all environments
330 if (!ssrIsProvider) {
331 const providerEnv = builder.environments[serverFnProviderEnv]
332 if (!providerEnv) {
333 throw new Error(
334 `Provider environment "${serverFnProviderEnv}" not found`,
335 )
336 }
337 if (!providerEnv.isBuilt) {
338 // Build the provider environment last
339 // This ensures all server functions are discovered from client/ssr builds
340 await builder.build(providerEnv)
341 }
342 }
343 },
344 },
345 }
346 },
347 buildApp: {
348 order: 'post',
349 async handler(builder) {
350 const { startConfig } = getConfig()
351 await postServerBuild({ builder, startConfig })
352 },
353 },
354 },
355 // Server function plugin handles:
356 // 1. Identifying createServerFn().handler() calls
357 // 2. Extracting server functions to separate modules
358 // 3. Replacing call sites with RPC stubs
359 // 4. Generating the server function manifest
360 // Also handles createIsomorphicFn, createServerOnlyFn, createClientOnlyFn, createMiddleware
361 startCompilerPlugin({
362 framework: corePluginOpts.framework,
363 environments,
364 generateFunctionId: startPluginOpts?.serverFns?.generateFunctionId,
365 providerEnvName: serverFnProviderEnv,
366 }),
367 tanStackStartRouter(startPluginOpts, getConfig, corePluginOpts),
368 loadEnvPlugin(),
369 startManifestPlugin({
370 getClientBundle: () => getBundle(VITE_ENVIRONMENT_NAMES.client),
371 getConfig,
372 }),
373 devServerPlugin({ getConfig }),
374 previewServerPlugin(),
375 {
376 name: 'tanstack-start:core:capture-bundle',
377 applyToEnvironment(e) {
378 return (
379 e.name === VITE_ENVIRONMENT_NAMES.client ||
380 e.name === VITE_ENVIRONMENT_NAMES.server
381 )
382 },
383 enforce: 'post',
384 generateBundle(_options, bundle) {
385 const environment = this.environment.name as ViteEnvironmentNames
386 if (!Object.values(VITE_ENVIRONMENT_NAMES).includes(environment)) {
387 throw new Error(`Unknown environment: ${environment}`)
388 }
389 capturedBundle[environment] = bundle
390 },
391 },
392 ]
394​
395function defineReplaceEnv<TKey extends string, TValue extends string>(
396 key: TKey,
397 value: TValue,
398): { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue } {
399 return {
400 [`process.env.${key}`]: JSON.stringify(value),
401 [`import.meta.env.${key}`]: JSON.stringify(value),
402 } as { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue }