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

conformance.svelte.test.ts

298 lines8.3 KB

1/**
2 * Svelte driver for the shared live-query conformance suite.
3 *
4 * Svelte 5 runes: each mount runs inside a persistent `$effect.root` so the
5 * internal `$effect` keeps updating rune state after mount; `unmount` disposes
6 * the root. Reads happen after `flushSync()`. Realm-sensitive pieces come from
7 * Svelte's `@tanstack/db`.
8 *
9 * All registered laws must pass; the driver has no whole-test waivers.
10 */
11import {
12 coalesce,
13 count,
14 createCollection,
15 createLiveQueryCollection,
16 createOptimisticAction,
17 eq,
18 groupKeys,
19 gt,
20 sum,
21} from '@tanstack/db'
22import { flushSync } from 'svelte'
23import { expect, it } from 'vitest'
24import {
25 mockSyncCollectionOptions,
26 mockSyncCollectionOptionsNoInitialState,
27} from '../../db/tests/utils'
28import { useLiveQuery } from '../src/useLiveQuery.svelte.js'
29import { runSuite } from '../../db/tests/conformance/suite'
30import { createPublicationLog } from '../../db/tests/conformance/publication-log'
31import { makeLaggingSource } from '../../db/tests/conformance/lagging-source'
32import { makeSyncSource } from '../../db/tests/conformance/sync-source'
33import { makeErrorSource as makeSharedErrorSource } from '../../db/tests/conformance/error-source'
34import { expectResultSurface } from '../../db/tests/conformance/result-laws'
35import type { PooledLiveQueries } from '@tanstack/db'
36import type {
37 ConformanceResult,
38 ControllableHandle,
39 DeferredSourceHandle,
40 LiveQueryDriver,
41 LiveQueryHandle,
42 QueryBuild,
43 SourceHandle,
44} from '../../db/tests/conformance/contract'
45​
46let sourceSeq = 0
47​
48function writer<T extends { id: string }>(collection: any) {
49 return (type: `insert` | `update` | `delete`, value: T) => {
50 collection.utils.begin()
51 collection.utils.write({ type, value })
52 collection.utils.commit()
53 }
55​
56function makeSource<T extends { id: string }>(
57 initialData: ReadonlyArray<T>,
58 collectionId?: string,
59): SourceHandle<T> {
60 const collection = createCollection(
61 mockSyncCollectionOptions<T>({
62 id: collectionId ?? `conformance-svelte-${sourceSeq++}`,
63 getKey: (r) => r.id,
64 initialData: [...initialData],
65 }),
66 )
67 const write = writer<T>(collection)
68 return {
69 collection,
70 insert: (row) => write(`insert`, row),
71 update: (row) => write(`update`, row),
72 remove: (row) => write(`delete`, row),
73 }
75​
76function makeDeferredSource<
77 T extends { id: string },
78>(): DeferredSourceHandle<T> {
79 const collection = createCollection(
80 mockSyncCollectionOptionsNoInitialState<T>({
81 id: `conformance-svelte-${sourceSeq++}`,
82 getKey: (r) => r.id,
83 }),
84 )
85 collection.startSyncImmediate()
86 const write = writer<T>(collection)
87 return {
88 collection,
89 insert: (row) => write(`insert`, row),
90 update: (row) => write(`update`, row),
91 remove: (row) => write(`delete`, row),
92 emit: (rows) => {
93 collection.utils.begin()
94 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
95 collection.utils.commit()
96 },
97 markReady: () => collection.utils.markReady(),
98 }
100​
101function makePrecreated(
102 build: QueryBuild,
103 opts?: { startSync?: boolean; gcTime?: number },
104) {
105 const collection = createLiveQueryCollection({
106 query: build as any,
107 startSync: opts?.startSync ?? true,
108 gcTime: opts?.gcTime,
109 })
110 return { collection }
112​
113function makeErrorSource(kind: `fail` | `crash`) {
114 return makeSharedErrorSource(
115 createCollection,
116 `conformance-svelte-err-${sourceSeq++}`,
117 kind,
118 )
120​
121async function settle() {
122 flushSync()
123 await new Promise((resolve) => setTimeout(resolve, 10))
124 flushSync()
126​
127function makeHandle(getQuery: () => any, dispose: () => void): LiveQueryHandle {
128 return {
129 collection: () => getQuery()?.collection ?? null,
130 current(): ConformanceResult {
131 const query = getQuery()
132 return expectResultSurface({
133 data: query?.data,
134 state: query?.state,
135 status: query?.status,
136 isReady: query?.isReady,
137 isLoadingError: query?.isLoadingError,
138 isCrashed: query?.isCrashed,
139 isSyncError: query?.isSyncError,
140 health: query?.health,
141 // svelte-db exposes no `isEnabled`; derive it from status (status-derived).
142 isEnabled: query?.status !== `disabled`,
143 })
144 },
145 flush: settle,
146 async apply(fn: () => void) {
147 fn()
148 await settle()
149 },
150 unmount() {
151 dispose()
152 },
153 }
155​
156function mount(build: QueryBuild) {
157 let query: any
158 const dispose = $effect.root(() => {
159 query = useLiveQuery(build as any)
160 })
161 return makeHandle(() => query, dispose)
163​
164function mountCollection(collection: any) {
165 let query: any
166 const dispose = $effect.root(() => {
167 query = useLiveQuery(collection)
168 })
169 return makeHandle(() => query, dispose)
171​
172function mountConfig(
173 build: QueryBuild,
174 opts?: { gcTime?: number; pool?: PooledLiveQueries },
175) {
176 let query: any
177 const dispose = $effect.root(() => {
178 query = useLiveQuery({ query: build, ...opts } as any)
179 })
180 return makeHandle(() => query, dispose)
182​
183function mountDisabled() {
184 // Svelte's disabled convention: the query callback returns null.
185 let query: any
186 const dispose = $effect.root(() => {
187 query = useLiveQuery(() => null as any)
188 })
189 return makeHandle(() => query, dispose)
191​
192function mountControllable<P>(
193 build: (q: any, param: P) => any,
194 initial: P,
195 opts?: { pool?: PooledLiveQueries },
196): ControllableHandle<P> {
197 let param = $state(initial)
198 let query: any
199 const published = createPublicationLog()
200 const dispose = $effect.root(() => {
201 query =
202 opts?.pool !== undefined
203 ? useLiveQuery(
204 { query: (q: any) => build(q, param), pool: opts.pool } as any,
205 [() => param],
206 )
207 : useLiveQuery((q: any) => build(q, param), [() => param])
208 // Svelte renders the value each pre-effect run reads.
209 $effect.pre(() => {
210 published.record(query.data, query.state)
211 })
212 })
213 const handle = makeHandle(() => query, dispose)
214 return {
215 ...handle,
216 publications: published.values,
217 statePublications: published.stateValues,
218 async setParam(next: P) {
219 param = next
220 // The first paint after the change: the framework has flushed its
221 // reactive work, but no later task has run.
222 flushSync()
223 published.record(query.data, query.state)
224 await settle()
225 },
226 }
228​
229const svelteDriver: LiveQueryDriver = {
230 name: `svelte`,
231 // Reactive reads decide when the query compiles again.
232 comparesQueryIdentity: false,
233 disabledRepresentation: `empty-reactive`,
234 ops: { eq, gt, count, sum, coalesce, groupKeys, createOptimisticAction },
235 makeSource,
236 makeDeferredSource,
237 makeLaggingSource: <T extends { id: string }>() =>
238 makeLaggingSource<T>(
239 createCollection,
240 `conformance-svelte-lagging-${sourceSeq++}`,
241 ),
242 makeSyncSource: <T extends { id: string }>(data: ReadonlyArray<T>) =>
243 makeSyncSource<T>(
244 createCollection,
245 `conformance-svelte-health-${sourceSeq++}`,
246 data,
247 ),
248 makePrecreated,
249 makeErrorSource,
250 mount,
251 mountControllable,
252 mountCollection,
253 mountConfig,
254 mountDisabled,
255 knownGaps: [],
256 features: { serverSnapshot: false, suspense: false, pooledEqFilters: true },
258​
259runSuite(svelteDriver)
260it(`preserves raw result types through the actual driver reader`, () => {
261 const raw: Record<string, unknown> = {
262 data: [{ id: `a`, value: undefined }],
263 state: new Map(),
264 status: `disabled`,
265 isReady: false,
266 isLoadingError: false,
267 isCrashed: false,
268 isSyncError: false,
269 isEnabled: false,
270 }
271 const handle = makeHandle(
272 () => raw,
273 () => {},
274 )
275 try {
276 const healthy = handle.current()
277 expect(healthy.data).toBe(raw.data)
278 expect(healthy.state).toBe(raw.state)
279 expect(healthy.isReady).toBe(false)
280 expect(healthy.isLoadingError).toBe(false)
281 expect(healthy.isEnabled).toBe(false)
282 for (const key of [`status`, `isReady`, `isLoadingError`]) {
283 const original = raw[key]
284 delete raw[key]
285 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
286 for (const invalid of key === `status`
287 ? [undefined, 0]
288 : [undefined, 0, ``]) {
289 raw[key] = invalid
290 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
291 }
292 raw[key] = original
293 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
294 }
295 } finally {
296 handle.unmount()
297 }
298})