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

index.ts

197 lines5.6 KB

1import { build, copyPublicAssets, createNitro, prepare } from 'nitropack'
2import { dirname, resolve } from 'pathe'
3​
4import type { PluginOption, ResolvedConfig, Rollup } from 'vite'
5import type { NitroConfig } from 'nitropack'
6​
7let ssrBundle: Rollup.OutputBundle
8let ssrEntryFile: string
9​
10function isFullUrl(str: string): boolean {
11 try {
12 new URL(str)
13 return true
14 } catch {
15 return false
16 }
18​
19export function nitroV2Plugin(nitroConfig?: NitroConfig): Array<PluginOption> {
20 let resolvedConfig: ResolvedConfig
21 return [
22 {
23 name: 'tanstack-nitro-v2-vite-plugin',
24​
25 generateBundle: {
26 handler(_options, bundle) {
27 if (this.environment.name !== 'ssr') {
28 return
29 }
30​
31 // find entry point of ssr bundle
32 let entryFile: string | undefined
33 for (const [_name, file] of Object.entries(bundle)) {
34 if (file.type === 'chunk') {
35 if (file.isEntry) {
36 if (entryFile !== undefined) {
37 this.error(
38 `Multiple entry points found for service "${this.environment.name}". Only one entry point is allowed.`,
39 )
40 }
41 entryFile = file.fileName
42 }
43 }
44 }
45 if (entryFile === undefined) {
46 this.error(
47 `No entry point found for service "${this.environment.name}".`,
48 )
49 }
50 ssrEntryFile = entryFile!
51 ssrBundle = bundle
52 },
53 },
54​
55 configResolved(config) {
56 resolvedConfig = config
57 },
58 config(_, env) {
59 if (env.command !== 'build') {
60 return
61 }
62​
63 return {
64 environments: {
65 ssr: {
66 consumer: 'server',
67 build: {
68 ssr: true,
69 // we don't write to the file system as the below 'capture-output' plugin will
70 // capture the output and write it to the virtual file system
71 write: false,
72 copyPublicDir: false,
73 commonjsOptions: {
74 include: [/node_modules/],
75 },
76 },
77 },
78 },
79 builder: {
80 sharedPlugins: true,
81 async buildApp(builder) {
82 const client = builder.environments.client
83 const server = builder.environments.ssr
84​
85 if (!client) {
86 throw new Error('Client environment not found')
87 }
88​
89 if (!server) {
90 throw new Error('SSR environment not found')
91 }
92​
93 await builder.build(client)
94 await builder.build(server)
95​
96 const virtualEntry = '#tanstack/start/entry'
97 const baseURL = !isFullUrl(resolvedConfig.base)
98 ? resolvedConfig.base
99 : undefined
100 const config: NitroConfig = {
101 baseURL,
102 publicAssets: [
103 {
104 dir: client.config.build.outDir,
105 maxAge: 31536000, // 1 year
106 baseURL: '/',
107 },
108 ],
109 ...nitroConfig,
110 esbuild: {
111 options: {
112 target: server.config.build.target || undefined,
113 ...nitroConfig?.esbuild?.options,
114 },
115 },
116 renderer: virtualEntry,
117 rollupConfig: {
118 ...nitroConfig?.rollupConfig,
119 plugins: [virtualBundlePlugin(ssrBundle) as any],
120 },
121 virtual: {
122 ...nitroConfig?.virtual,
123 [virtualEntry]: `import { fromWebHandler } from 'h3'
124 import handler from '${ssrEntryFile}'
125 export default fromWebHandler(handler.fetch)`,
126 },
127 }
128​
129 const nitro = await createNitro(config)
130​
131 await prepare(nitro)
132 await copyPublicAssets(nitro)
133 await build(nitro)
134​
135 await nitro.close()
136 },
137 },
138 }
139 },
140 },
141 ]
143​
144function virtualBundlePlugin(bundle: Rollup.OutputBundle): Rollup.Plugin {
145 type VirtualModule = { code: string; map: string | null }
146 let _modules: Map<string, VirtualModule> | null = null
147​
148 // lazy initialize _modules since at the time of plugin creation, the bundles are not available yet
149 const getModules = () => {
150 if (_modules) {
151 return _modules
152 }
153 _modules = new Map()
154 // group chunks and source maps
155 for (const [fileName, content] of Object.entries(bundle)) {
156 if (content.type === 'chunk') {
157 const virtualModule: VirtualModule = {
158 code: content.code,
159 map: null,
160 }
161 const maybeMap = bundle[`${fileName}.map`]
162 if (maybeMap && maybeMap.type === 'asset') {
163 virtualModule.map = maybeMap.source as string
164 }
165 _modules.set(fileName, virtualModule)
166 _modules.set(resolve(fileName), virtualModule)
167 }
168 }
169 return _modules
170 }
171​
172 return {
173 name: 'virtual-bundle',
174 resolveId(id, importer) {
175 const modules = getModules()
176 if (modules.has(id)) {
177 return resolve(id)
178 }
179​
180 if (importer) {
181 const resolved = resolve(dirname(importer), id)
182 if (modules.has(resolved)) {
183 return resolved
184 }
185 }
186 return null
187 },
188 load(id) {
189 const modules = getModules()
190 const m = modules.get(id)
191 if (!m) {
192 return null
193 }
194 return m
195 },
196 }