Open History to see the last commit
1import { createServer } from 'node:http'
2import { readFile } from 'node:fs/promises'
3import { dirname, extname, resolve, sep } from 'node:path'
4import { setTimeout as sleep } from 'node:timers/promises'
5import { fileURLToPath } from 'node:url'
6import { render } from '@lit-labs/ssr'
7import { collectResult } from '@lit-labs/ssr/lib/render-result.js'
8import { html } from 'lit'
9import { QueryClient, dehydrate } from '@tanstack/lit-query'
10import {
11 SSR_BASE_URL,
12 SSR_HOST,
13 SSR_PORT,
14 SSR_PUBLIC_ORIGIN,
15} from '../config/ports.js'
16import {
17 DATA_QUERY_KEY,
18 DEFAULT_MESSAGE,
19 QUERY_STALE_TIME,
20 createDataQueryOptions,
21} from '../src/api.js'
22import {
23 getSsrQueryControllerCreationCount,
24 resetSsrQueryControllerCreationCount,
25} from '../src/app.ts'
26β
27const serverDir = dirname(fileURLToPath(import.meta.url))
28const distDir = resolve(serverDir, '../dist')
29const templatePath = resolve(distDir, 'index.html')
30β
31const contentTypes = {
32 '.css': 'text/css; charset=utf-8',
33 '.js': 'text/javascript; charset=utf-8',
34 '.json': 'application/json; charset=utf-8',
35 '.svg': 'image/svg+xml; charset=utf-8',
36}
37β
38let requestCount = 0
39let failNextDataRequest = false
40let nextDataDelayMs = 0
41β
42const apiCorsHeaders = {
43 'access-control-allow-headers': 'content-type',
44 'access-control-allow-methods': 'GET,POST,OPTIONS',
45 'access-control-allow-origin': '*',
46}
47β
48function createBrowserQueryClient() {
49 return new QueryClient({
50 defaultOptions: {
51 queries: {
52 retry: false,
53 staleTime: QUERY_STALE_TIME,
54 },
55 },
56 })
57}
58β
59function nextDataResponse() {
60 requestCount += 1
61 return {
62 message: DEFAULT_MESSAGE,
63 requestCount,
64 servedAt: new Date().toISOString(),
65 }
66}
67β
68function resetApiState() {
69 requestCount = 0
70 failNextDataRequest = false
71 nextDataDelayMs = 0
72}
73β
74function parseNonNegativeDelayMs(value) {
75 const parsedDelayMs = Number.parseInt(value ?? '', 10)
76 if (!Number.isInteger(parsedDelayMs) || parsedDelayMs < 0) {
77 return undefined
78 }
79β
80 return parsedDelayMs
81}
82β
83async function consumeNextDataDelay() {
84 const delayMs = nextDataDelayMs
85 nextDataDelayMs = 0
86β
87 if (delayMs > 0) {
88 await sleep(delayMs)
89 }
90}
91β
92function consumeFailNextDataRequest() {
93 if (!failNextDataRequest) {
94 return false
95 }
96β
97 failNextDataRequest = false
98 return true
99}
100β
101function writeBuffer(res, statusCode, contentType, payload, extraHeaders = {}) {
102 res.writeHead(statusCode, {
103 'cache-control': 'no-store',
104 'content-length': payload.byteLength,
105 'content-type': contentType,
106 ...extraHeaders,
107 })
108 res.end(payload)
109}
110β
111function writeHtml(res, statusCode, body, extraHeaders = {}) {
112 const payload = Buffer.from(body)
113 writeBuffer(
114 res,
115 statusCode,
116 'text/html; charset=utf-8',
117 payload,
118 extraHeaders,
119 )
120}
121β
122function writeJson(res, statusCode, body) {
123 const payload = Buffer.from(JSON.stringify(body))
124 writeBuffer(
125 res,
126 statusCode,
127 'application/json; charset=utf-8',
128 payload,
129 apiCorsHeaders,
130 )
131}
132β
133function serializeJsonForHtml(value) {
134 return JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (character) => {
135 switch (character) {
136 case '<':
137 return '\\u003c'
138 case '>':
139 return '\\u003e'
140 case '&':
141 return '\\u0026'
142 case '\u2028':
143 return '\\u2028'
144 case '\u2029':
145 return '\\u2029'
146 default:
147 return character
148 }
149 })
150}
151β
152async function readTemplate() {
153 try {
154 return await readFile(templatePath, 'utf8')
155 } catch (error) {
156 if (error && typeof error === 'object' && 'code' in error) {
157 throw new Error(
158 'Missing built client assets. Run "pnpm --dir examples/lit/ssr run build" from the repo root first.',
159 )
160 }
161β
162 throw error
163 }
164}
165β
166async function serveAsset(pathname, res) {
167 if (!pathname.startsWith('/assets/')) {
168 return false
169 }
170β
171 const assetPath = resolve(distDir, `.${pathname}`)
172 const distRootPrefix = `${distDir}${sep}`
173 if (!assetPath.startsWith(distRootPrefix)) {
174 return false
175 }
176β
177 try {
178 const file = await readFile(assetPath)
179 const contentType =
180 contentTypes[extname(assetPath)] ?? 'application/octet-stream'
181 writeBuffer(res, 200, contentType, file)
182 return true
183 } catch {
184 return false
185 }
186}
187β
188async function renderPage(res) {
189 const queryClient = createBrowserQueryClient()
190 resetSsrQueryControllerCreationCount(queryClient)
191 await queryClient.prefetchQuery(createDataQueryOptions(SSR_PUBLIC_ORIGIN))
192β
193 const prefetchedQueryState = queryClient.getQueryState(DATA_QUERY_KEY)
194 if (prefetchedQueryState?.status !== 'success') {
195 throw new Error(
196 'SSR prefetch did not complete successfully. Refusing to render loading HTML.',
197 )
198 }
199β
200 const appHtml = await collectResult(
201 render(
202 html`<ssr-app
203 api-base-url=${SSR_PUBLIC_ORIGIN}
204 .queryClient=${queryClient}
205 ></ssr-app>`,
206 ),
207 )
208β
209 const dehydratedState = dehydrate(queryClient)
210 const controllerCreationCount =
211 getSsrQueryControllerCreationCount(queryClient)
212 if (controllerCreationCount < 1) {
213 throw new Error('SSR render did not exercise createQueryController.')
214 }
215β
216 const template = await readTemplate()
217 const htmlDocument = template
218 .replace('__SSR_APP_HTML__', appHtml)
219 .replace('__QUERY_STATE_JSON__', serializeJsonForHtml(dehydratedState))
220β
221 writeHtml(res, 200, htmlDocument, {
222 'x-ssr-query-controller-created': String(controllerCreationCount),
223 })
224}
225β
226const server = createServer(async (req, res) => {
227 const requestUrl = new URL(req.url ?? '/', SSR_BASE_URL)
228 const method = req.method ?? 'GET'
229β
230 if (method === 'OPTIONS' && requestUrl.pathname.startsWith('/api/')) {
231 res.writeHead(204, {
232 'cache-control': 'no-store',
233 ...apiCorsHeaders,
234 })
235 res.end()
236 return
237 }
238β
239 if (method === 'GET' && requestUrl.pathname === '/api/data') {
240 await consumeNextDataDelay()
241β
242 if (consumeFailNextDataRequest()) {
243 writeJson(res, 500, { error: 'Forced data failure (test)' })
244 return
245 }
246β
247 writeJson(res, 200, nextDataResponse())
248 return
249 }
250β
251 if (method === 'GET' && requestUrl.pathname === '/api/request-count') {
252 writeJson(res, 200, { count: requestCount })
253 return
254 }
255β
256 if (method === 'POST' && requestUrl.pathname === '/api/reset') {
257 resetApiState()
258 writeJson(res, 200, { ok: true })
259 return
260 }
261β
262 if (method === 'POST' && requestUrl.pathname === '/api/test/fail-next-data') {
263 failNextDataRequest = true
264 writeJson(res, 200, { ok: true })
265 return
266 }
267β
268 if (
269 method === 'POST' &&
270 requestUrl.pathname === '/api/test/delay-next-data'
271 ) {
272 const delayMs = parseNonNegativeDelayMs(requestUrl.searchParams.get('ms'))
273 if (delayMs === undefined) {
274 writeJson(res, 400, { error: 'Invalid ms query parameter.' })
275 return
276 }
277β
278 nextDataDelayMs = delayMs
279 writeJson(res, 200, { ok: true, delayMs })
280 return
281 }
282β
283 if (method === 'GET' && requestUrl.pathname === '/') {
284 try {
285 await renderPage(res)
286 } catch (error) {
287 console.error('[ssr] render failed:', error)
288 writeHtml(
289 res,
290 500,
291 '<!doctype html><html><body>SSR render failed.</body></html>',
292 )
293 }
294 return
295 }
296β
297 if (method === 'GET' && (await serveAsset(requestUrl.pathname, res))) {
298 return
299 }
300β
301 writeJson(res, 404, { error: 'Not found' })
302})
303β
304server.listen(SSR_PORT, SSR_HOST, () => {
305 console.log(
306 `[ssr] listening on ${SSR_BASE_URL} (public origin ${SSR_PUBLIC_ORIGIN})`,
307 )
308})