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

hydration-utils.ts

165 lines4.5 KB

1/**
2 * Shared harness for the SSR β†’ hydration tests.
3 *
4 * The fixture app in `fixtures/hydration/` is built with vite in a plain node
5 * subprocess (vite/esbuild cannot run inside the jsdom worker): a server
6 * bundle, a streaming server bundle, a boundary-less disabled-query bundle,
7 * and a hydratable client bundle. The subprocess also executes every server
8 * entry and returns their reports.
9 */
10import { execFileSync } from 'node:child_process'
11import { mkdirSync, rmSync } from 'node:fs'
12import * as path from 'node:path'
13import { pathToFileURL } from 'node:url'
14import type { QueryClient } from '..'
15​
16// vitest runs with the package root as cwd; import.meta.url is not a file URL
17// inside the jsdom worker.
18const fixtureDir = path.join(
19 process.cwd(),
20 'src',
21 '__tests__',
22 'fixtures',
23 'hydration',
25​
26interface QuerySnapshot {
27 queryKey: Array<string>
28 queryHash: string
29 state: { data: unknown; dataUpdatedAt: number; status: string }
31​
32interface ServerReport {
33 string: {
34 html: string
35 counts: {
36 fresh: number
37 stale: number
38 placeholder: number
39 prefetched: number
40 }
41 queries: Array<QuerySnapshot>
42 /** Whether the provider's dispose-time teardown emptied the cache. */
43 cacheEmptyAfterDispose: boolean
44 /** Same app rendered on a client whose `defaultOptions.dehydrate.
45 * shouldDehydrateQuery` excludes the stale query. */
46 filteredHtml: string
47 }
48 stream: {
49 chunks: Array<{ t: number; payload: string }>
50 counts: { header: number; feed: number }
51 queries: Array<QuerySnapshot>
52 cacheEmptyAfterDispose: boolean
53 }
54 /** Boundary-less render of a single disabled query β€” see
55 * `fixtures/hydration/entry-server-disabled.tsx`. */
56 disabled: {
57 /** False if the render timed out instead of completing. */
58 finished: boolean
59 html: string
60 fetches: number
61 }
63​
64export interface ClientBundle {
65 createApp: () => {
66 queryClient: QueryClient
67 counts: {
68 fresh: number
69 stale: number
70 placeholder: number
71 prefetched: number
72 }
73 showLate: () => void
74 mount: (container: HTMLElement) => () => void
75 }
76 createStreamApp: () => {
77 queryClient: QueryClient
78 counts: { header: number; feed: number }
79 mount: (container: HTMLElement) => () => void
80 }
82​
83export interface Harness {
84 outDir: string
85 report: ServerReport
86 clientBundleUrl: string
88​
89export function buildFixture(): Harness {
90 // Must live inside the package so vitest can import the client bundle.
91 const outDir = path.join(
92 process.cwd(),
93 'node_modules',
94 '.tmp',
95 'hydration-fixture',
96 )
97 rmSync(outDir, { recursive: true, force: true })
98 mkdirSync(outDir, { recursive: true })
99​
100 const report = JSON.parse(
101 execFileSync(
102 process.execPath,
103 [path.join(fixtureDir, 'build-and-render.mjs'), outDir],
104 { encoding: 'utf-8' },
105 ),
106 ) as ServerReport
107 return {
108 outDir,
109 report,
110 clientBundleUrl: pathToFileURL(path.join(outDir, 'entry-client.mjs')).href,
111 }
113​
114export function cleanupFixture(harness: Harness | undefined): void {
115 if (harness) rmSync(harness.outDir, { recursive: true, force: true })
117​
118/**
119 * Reset the hydration bootstrap the way a fresh document would provide it
120 * (normally injected via generateHydrationScript).
121 */
122export function bootstrapHydrationGlobals(): void {
123 ;(globalThis as any)._$HY = {
124 events: [],
125 completed: new WeakSet(),
126 r: {},
127 fe() {},
128 }
130​
131/**
132 * Append streamed SSR payloads to the container and execute any scripts they
133 * carry, in document order, the way a browser's parser would.
134 */
135export function applyChunks(
136 container: HTMLElement,
137 payloads: Array<string>,
138): void {
139 for (const payload of payloads) {
140 container.insertAdjacentHTML('beforeend', payload)
141 for (const script of Array.from(
142 container.querySelectorAll('script:not([data-executed])'),
143 )) {
144 script.setAttribute('data-executed', 'true')
145 if (script.textContent) {
146 window.eval(script.textContent)
147 }
148 }
149 }
151​
152/** Flush microtasks plus one timer turn. */
153export function tick(ms = 0): Promise<void> {
154 return new Promise((resolve) => setTimeout(resolve, ms))
156​
157/**
158 * Drain `n` rounds of the microtask queue without yielding to timers.
159 * Used to assert that hydration work happens at microtask timing (i.e.
160 * before the task ends β€” before the browser would paint), not on some
161 * later timer or stream event.
162 */
163export async function microtasks(n = 10): Promise<void> {
164 for (let i = 0; i < n; i++) await Promise.resolve()