Open History to see the last commit
1import { Transform } from 'node:stream'
2import { renderToPipeableStream } from 'preact-render-to-string/stream-node'
3import { uneval } from 'devalue'
4import { QueryClientProvider, dehydrate, noop } from '@tanstack/preact-query'
5import { PreactQueryDevtools } from '@tanstack/preact-query-devtools'
6import App, { combinedWaits, waits } from './App'
7import { makeQueryClient } from './makeQueryClient'
8import { waitQueries } from './services/wait/queries'
9import type { DehydratedState } from '@tanstack/preact-query'
10import type { Writable } from 'node:stream'
11β
12export function render(callbacks: {
13 onShellReady: () => void
14 onError: (error: unknown) => void
15}) {
16 const queryClient = makeQueryClient()
17β
18 // Start every query the page renders up front, so a Suspense boundary
19 // never waits for another one to finish before its own fetch starts
20 for (const wait of [...waits, ...combinedWaits]) {
21 void queryClient.query(waitQueries.detail(wait)).catch(noop)
22 }
23β
24 // Collect each query's state as soon as it succeeds on the server
25 const states: Array<DehydratedState> = []
26 const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
27 if (event.type === 'updated' && event.action.type === 'success') {
28 states.push(
29 dehydrate(queryClient, {
30 shouldDehydrateQuery: (query) => query === event.query,
31 }),
32 )
33 }
34 })
35β
36 // Send the collected states right before the next streamed chunk, so the
37 // client has the data of every boundary by the time it hydrates
38 const flushStates = () =>
39 states
40 .splice(0)
41 .map(
42 (state) =>
43 `<script>window.__QUERY_STATES__.push(${uneval(state)});document.currentScript.remove()</script>`,
44 )
45 .join('')
46β
47 const injectStates = new Transform({
48 transform(chunk, _encoding, callback) {
49 callback(null, flushStates() + chunk)
50 },
51 flush(callback) {
52 callback(null, flushStates())
53 },
54 })
55β
56 const stream = renderToPipeableStream(
57 <QueryClientProvider client={queryClient}>
58 <App />
59 <PreactQueryDevtools />
60 </QueryClientProvider>,
61 {
62 onShellReady: callbacks.onShellReady,
63 onAllReady: unsubscribe,
64 onError: (error) => {
65 // The renderer destroys its own stream on errors and aborts, so end
66 // ours as well to let the response finish
67 unsubscribe()
68 injectStates.end()
69 callbacks.onError(error)
70 },
71 },
72 )
73β
74 return {
75 pipe: (writable: Writable) => {
76 injectStates.pipe(writable, { end: false })
77 stream.pipe(injectStates)
78 return injectStates
79 },
80 abort: stream.abort,
81 }
82}