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

prerender.ts

271 lines7.9 KB

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