Open History to see the last commit
1import { existsSync, promises as fsp, rmSync } from 'node:fs'
2import { pathToFileURL } from 'node:url'
3import os from 'node:os'
4import path from 'pathe'
5import { joinURL, withBase, withoutBase } from 'ufo'
6import { VITE_ENVIRONMENT_NAMES } from './constants'
7import { createLogger } from './utils'
8import { Queue } from './queue'
9import type { Rollup, ViteBuilder } from 'vite'
10import type { Page, TanStackStartOutputConfig } from './schema'
11β
12export async function prerender({
13 startConfig,
14 builder,
15 serverBundle,
16}: {
17 startConfig: TanStackStartOutputConfig
18 builder: ViteBuilder
19 serverBundle: Rollup.OutputBundle
20}) {
21 const logger = createLogger('prerender')
22 logger.info('Prerendering pages...')
23β
24 // If prerender is enabled
25 if (startConfig.prerender?.enabled) {
26 // default to root page if no pages are defined
27 let pages = startConfig.pages.length ? startConfig.pages : [{ path: '/' }]
28β
29 if (startConfig.prerender.autoStaticPathsDiscovery ?? true) {
30 // merge discovered static pages with user-defined pages
31 const pagesMap = new Map(pages.map((item) => [item.path, item]))
32 const discoveredPages = globalThis.TSS_PRERENDABLE_PATHS || []
33β
34 for (const page of discoveredPages) {
35 if (!pagesMap.has(page.path)) {
36 pagesMap.set(page.path, page)
37 }
38 }
39β
40 pages = Array.from(pagesMap.values())
41 }
42β
43 startConfig.pages = pages
44 }
45β
46 const serverEnv = builder.environments[VITE_ENVIRONMENT_NAMES.server]
47β
48 if (!serverEnv) {
49 throw new Error(
50 `Vite's "${VITE_ENVIRONMENT_NAMES.server}" environment not found`,
51 )
52 }
53β
54 const clientEnv = builder.environments[VITE_ENVIRONMENT_NAMES.client]
55 if (!clientEnv) {
56 throw new Error(
57 `Vite's "${VITE_ENVIRONMENT_NAMES.client}" environment not found`,
58 )
59 }
60β
61 const outputDir = clientEnv.config.build.outDir
62β
63 const entryFile = findEntryFileInBundle(serverBundle)
64 let fullEntryFilePath = path.join(serverEnv.config.build.outDir, entryFile)
65 process.env.TSS_PRERENDERING = 'true'
66β
67 if (!existsSync(fullEntryFilePath)) {
68 // if the file does not exist, we need to write the bundle to a temporary directory
69 // this can happen e.g. with nitro that postprocesses the bundle and thus does not write SSR build to disk
70 const bundleOutputDir = path.resolve(
71 serverEnv.config.root,
72 '.tanstack',
73 'start',
74 'prerender',
75 )
76 rmSync(bundleOutputDir, { recursive: true, force: true })
77 await writeBundleToDisk({ bundle: serverBundle, outDir: bundleOutputDir })
78 fullEntryFilePath = path.join(bundleOutputDir, entryFile)
79 }
80β
81 const { default: serverEntrypoint } = await import(
82 pathToFileURL(fullEntryFilePath).toString()
83 )
84β
85 const isRedirectResponse = (res: Response) => {
86 return res.status >= 300 && res.status < 400 && res.headers.get('location')
87 }
88 async function localFetch(
89 path: string,
90 options?: RequestInit,
91 maxRedirects: number = 5,
92 ): Promise<Response> {
93 const url = new URL(`http://localhost${path}`)
94 const response = await serverEntrypoint.fetch(new Request(url, options))
95β
96 if (isRedirectResponse(response) && maxRedirects > 0) {
97 const location = response.headers.get('location')!
98 if (location.startsWith('http://localhost') || location.startsWith('/')) {
99 const newUrl = location.replace('http://localhost', '')
100 return localFetch(newUrl, options, maxRedirects - 1)
101 } else {
102 logger.warn(`Skipping redirect to external location: ${location}`)
103 }
104 }
105β
106 return response
107 }
108β
109 try {
110 // Crawl all pages
111 const pages = await prerenderPages({ outputDir })
112β
113 logger.info(`Prerendered ${pages.length} pages:`)
114 pages.forEach((page) => {
115 logger.info(`- ${page}`)
116 })
117 } catch (error) {
118 logger.error(error)
119 }
120β
121 function extractLinks(html: string): Array<string> {
122 const linkRegex = /<a[^>]+href=["']([^"']+)["'][^>]*>/g
123 const links: Array<string> = []
124 let match
125β
126 while ((match = linkRegex.exec(html)) !== null) {
127 const href = match[1]
128 if (href && (href.startsWith('/') || href.startsWith('./'))) {
129 links.push(href)
130 }
131 }
132β
133 return links
134 }
135β
136 async function prerenderPages({ outputDir }: { outputDir: string }) {
137 const seen = new Set<string>()
138 const prerendered = new Set<string>()
139 const retriesByPath = new Map<string, number>()
140 const concurrency = startConfig.prerender?.concurrency ?? os.cpus().length
141 logger.info(`Concurrency: ${concurrency}`)
142 const queue = new Queue({ concurrency })
143 const routerBasePath = joinURL('/', startConfig.router.basepath ?? '')
144β
145 startConfig.pages.forEach((page) => addCrawlPageTask(page))
146β
147 await queue.start()
148β
149 return Array.from(prerendered)
150β
151 function addCrawlPageTask(page: Page) {
152 // Was the page already seen?
153 if (seen.has(page.path)) return
154β
155 // Add the page to the seen set
156 seen.add(page.path)
157β
158 if (page.fromCrawl) {
159 startConfig.pages.push(page)
160 }
161β
162 // If not enabled, skip
163 if (!(page.prerender?.enabled ?? true)) return
164β
165 // If there is a filter link, check if the page should be prerendered
166 if (startConfig.prerender?.filter && !startConfig.prerender.filter(page))
167 return
168β
169 // Resolve the merged default and page-specific prerender options
170 const prerenderOptions = {
171 ...startConfig.prerender,
172 ...page.prerender,
173 }
174β
175 // Add the task
176 queue.add(async () => {
177 logger.info(`Crawling: ${page.path}`)
178 const retries = retriesByPath.get(page.path) || 0
179 try {
180 // Fetch the route
181 const encodedRoute = encodeURI(page.path)
182β
183 const res = await localFetch(
184 withBase(encodedRoute, routerBasePath),
185 {
186 headers: {
187 ...(prerenderOptions.headers ?? {}),
188 },
189 },
190 prerenderOptions.maxRedirects,
191 )
192β
193 if (!res.ok) {
194 if (isRedirectResponse(res)) {
195 logger.warn(`Max redirects reached for ${page.path}`)
196 }
197 throw new Error(`Failed to fetch ${page.path}: ${res.statusText}`, {
198 cause: res,
199 })
200 }
201β
202 const cleanPagePath = (
203 prerenderOptions.outputPath || page.path
204 ).split(/[?#]/)[0]!
205β
206 // Guess route type and populate fileName
207 const contentType = res.headers.get('content-type') || ''
208 const isImplicitHTML =
209 !cleanPagePath.endsWith('.html') && contentType.includes('html')
210 // &&
211 // !JsonSigRx.test(dataBuff.subarray(0, 32).toString('utf8'))
212 const routeWithIndex = cleanPagePath.endsWith('/')
213 ? cleanPagePath + 'index'
214 : cleanPagePath
215β
216 const htmlPath =
217 cleanPagePath.endsWith('/') ||
218 (prerenderOptions.autoSubfolderIndex ?? true)
219 ? joinURL(cleanPagePath, 'index.html')
220 : cleanPagePath + '.html'
221β
222 const filename = withoutBase(
223 isImplicitHTML ? htmlPath : routeWithIndex,
224 routerBasePath,
225 )
226β
227 const html = await res.text()
228β
229 const filepath = path.join(outputDir, filename)
230β
231 await fsp.mkdir(path.dirname(filepath), {
232 recursive: true,
233 })
234β
235 await fsp.writeFile(filepath, html)
236β
237 prerendered.add(page.path)
238β
239 const newPage = await prerenderOptions.onSuccess?.({ page, html })
240β
241 if (newPage) {
242 Object.assign(page, newPage)
243 }
244β
245 // Find new links
246 if (prerenderOptions.crawlLinks ?? true) {
247 const links = extractLinks(html)
248 for (const link of links) {
249 addCrawlPageTask({ path: link, fromCrawl: true })
250 }
251 }
252 } catch (error) {
253 if (retries < (prerenderOptions.retryCount ?? 0)) {
254 logger.warn(`Encountered error, retrying: ${page.path} in 500ms`)
255 await new Promise((resolve) =>
256 setTimeout(resolve, prerenderOptions.retryDelay),
257 )
258 retriesByPath.set(page.path, retries + 1)
259 addCrawlPageTask(page)
260 } else {
261 if (prerenderOptions.failOnError ?? true) {
262 throw error
263 }
264 }
265 }
266 })
267 }
268 }
269}
270β
271function findEntryFileInBundle(bundle: Rollup.OutputBundle): string {
272 let entryFile: string | undefined
273β
274 for (const [_name, file] of Object.entries(bundle)) {
275 if (file.type === 'chunk') {
276 if (file.isEntry) {
277 if (entryFile !== undefined) {
278 throw new Error(
279 `Multiple entry points found. Only one entry point is allowed.`,
280 )
281 }
282 entryFile = file.fileName
283 }
284 }
285 }
286 if (entryFile === undefined) {
287 throw new Error(`No entry point found in the bundle.`)
288 }
289 return entryFile
290}
291β
292export async function writeBundleToDisk({
293 bundle,
294 outDir,
295}: {
296 bundle: Rollup.OutputBundle
297 outDir: string
298}) {
299 const createdDirs = new Set<string>()
300β
301 for (const [fileName, asset] of Object.entries(bundle)) {
302 const fullPath = path.join(outDir, fileName)
303 const dir = path.dirname(fullPath)
304 const content = asset.type === 'asset' ? asset.source : asset.code
305β
306 if (!createdDirs.has(dir)) {
307 await fsp.mkdir(dir, { recursive: true })
308 createdDirs.add(dir)
309 }
310β
311 await fsp.writeFile(fullPath, content)
312 }
313}