Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { flushSync } from 'svelte'
3import { DbClient, Query, collectionOptions } from '@tanstack/db'
4import { useLiveQuery } from '../src/useLiveQuery.svelte.js'
5import { expectedSsrSnapshot } from '../../db/tests/ssr-snapshot-admission-oracle'
6import { createPeopleDescriptor, peopleQuery } from './ssr-test-utils.js'
7
8describe(`Svelte hydration`, () => {
9 it(`keeps the hydrated result until the browser source is authoritative`, async () => {
10 const { descriptor, resolveBrowserLoad } = createPeopleDescriptor()
11 const serverClient = new DbClient({ runtime: `server` })
12 await serverClient.preloadLiveQuery(peopleQuery(descriptor))
13 const dehydrated = serverClient.dehydrate({
14 shouldDehydrateCollection: () => false,
15 shouldDehydrateLiveQuery: () => true,
16 })
17
18 const browserClient = new DbClient({ runtime: `browser` })
19 browserClient.hydrate(dehydrated)
20 const createQuery = () =>
21 useLiveQuery({
22 ...peopleQuery(descriptor),
23 client: browserClient,
24 })
25 let query!: ReturnType<typeof createQuery>
26 const dispose = $effect.root(() => {
27 query = createQuery()
28 })
29
30 flushSync()
31 expect(query.data).toEqual([
32 expect.objectContaining({ id: `server`, name: `Server snapshot` }),
33 ])
34
35 resolveBrowserLoad()
36 await vi.waitFor(() => {
37 flushSync()
38 expect(query.data).toEqual([
39 expect.objectContaining({ id: `browser`, name: `Browser source` }),
40 ])
41 })
42 dispose()
43 })
44
45 // An empty queryKey counts as none, so with a dependency list it must match
46 // the hydrated query exactly as an omitted key does. The server preload has
47 // no dependency list, so a query with one does not match it. The control
48 // case without a dependency list shows this harness does hydrate, so the two
49 // dependency-list cases agree on a real miss, not on a broken harness.
50 it(`hydrates an empty queryKey with a dependency list as it hydrates no key`, async () => {
51 const firstRows = async (
52 queryKey: Array<unknown> | undefined,
53 deps: Array<() => unknown> | undefined,
54 ) => {
55 const { descriptor } = createPeopleDescriptor()
56 const serverClient = new DbClient({ runtime: `server` })
57 await serverClient.preloadLiveQuery(peopleQuery(descriptor))
58 const browserClient = new DbClient({ runtime: `browser` })
59 browserClient.hydrate(
60 serverClient.dehydrate({
61 shouldDehydrateCollection: () => false,
62 shouldDehydrateLiveQuery: () => true,
63 }),
64 )
65 let query!: ReturnType<typeof useLiveQuery>
66 const dispose = $effect.root(() => {
67 const config = {
68 ...peopleQuery(descriptor),
69 client: browserClient,
70 queryKey,
71 } as any
72 query = deps ? useLiveQuery(config, deps) : useLiveQuery(config)
73 })
74 flushSync()
75 const rows = query.data
76 dispose()
77 return rows
78 }
79 const serverRows = [
80 expect.objectContaining({ id: `server`, name: `Server snapshot` }),
81 ]
82 // Control: the same query and harness hydrate the server rows.
83 expect(await firstRows(undefined, undefined)).toEqual(serverRows)
84 expect(await firstRows([], undefined)).toEqual(serverRows)
85
86 const dependency = [() => `dependency`]
87 const omittedKey = await firstRows(undefined, dependency)
88 expect(await firstRows([], dependency)).toEqual(omittedKey)
89 })
90})
91
92// Normal browser initialization must not use the stricter SSR admission rule.
93// Source-only hydration is provisional until the browser's own sync is ready.
94describe(`Svelte SSR receiving controls`, () => {
95 for (const preparation of [`warm-browser`, `normalized`] as const) {
96 for (const count of [0, 1]) {
97 it(`${preparation} with ${count} rows remains legal`, async () => {
98 const rows = Array.from({ length: count }, (_, index) => ({
99 id: String(index),
100 name: `seed ${index}`,
101 }))
102 const expected = expectedSsrSnapshot({
103 preparation: `source`,
104 sourceState: `ready`,
105 rows,
106 })
107 const client = new DbClient()
108 const descriptor = collectionOptions(`svelte-ssr-receiving`, () => ({
109 id: `svelte-ssr-receiving`,
110 getKey: (row: { id: string; name: string }) => row.id,
111 sync: {
112 sync: ({ begin, write, commit, markReady }) => {
113 if (preparation === `warm-browser`) {
114 begin()
115 for (const row of rows) write({ type: `insert`, value: row })
116 commit()
117 }
118 markReady()
119 },
120 },
121 }))
122 if (preparation === `warm-browser`)
123 await client.preloadLiveQuery({
124 query: new Query()
125 .from({ row: descriptor })
126 .select(({ row }) => ({ id: row.id })),
127 })
128 else
129 client.hydrate({
130 collections: [
131 {
132 collectionId: descriptor.id,
133 rows: rows.map((value) => ({ key: value.id, value })),
134 },
135 ],
136 })
137 const createQuery = () =>
138 useLiveQuery({
139 query: (q) =>
140 q
141 .from({ row: descriptor })
142 .select(({ row }) => ({ id: row.id, name: row.name })),
143 client,
144 })
145 let query!: ReturnType<typeof createQuery>
146 let dispose: (() => void) | undefined
147 let initializationError: unknown
148 try {
149 try {
150 dispose = $effect.root(() => {
151 query = createQuery()
152 })
153 } catch (error) {
154 initializationError = error
155 }
156 expect(
157 initializationError,
158 `valid browser initialization does not throw`,
159 ).toBeUndefined()
160 expect(query.status).toBe(
161 preparation === `warm-browser` ? `ready` : `loading`,
162 )
163 expect(query.data).toEqual(
164 expected.rows.map((row) => expect.objectContaining(row)),
165 )
166 flushSync()
167 await vi.waitFor(() => {
168 flushSync()
169 expect(query.status).toBe(`ready`)
170 })
171 } finally {
172 dispose?.()
173 await client.cleanup()
174 }
175 })
176 }
177 }
178})