Open History to see the last commit
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 gt,
19 sum,
20} from '@tanstack/db'
21import { flushSync } from 'svelte'
22import { expect, it } from 'vitest'
23import {
24 mockSyncCollectionOptions,
25 mockSyncCollectionOptionsNoInitialState,
26} from '../../db/tests/utils'
27import { useLiveQuery } from '../src/useLiveQuery.svelte.js'
28import { runSuite } from '../../db/tests/conformance/suite'
29import { expectResultSurface } from '../../db/tests/conformance/result-laws'
30import type {
31 ConformanceResult,
32 ControllableHandle,
33 DeferredSourceHandle,
34 LiveQueryDriver,
35 LiveQueryHandle,
36 QueryBuild,
37 SourceHandle,
38} from '../../db/tests/conformance/contract'
39
40let sourceSeq = 0
41
42function writer<T extends { id: string }>(collection: any) {
43 return (type: `insert` | `update` | `delete`, value: T) => {
44 collection.utils.begin()
45 collection.utils.write({ type, value })
46 collection.utils.commit()
47 }
48}
49
50function makeSource<T extends { id: string }>(
51 initialData: ReadonlyArray<T>,
52): SourceHandle<T> {
53 const collection = createCollection(
54 mockSyncCollectionOptions<T>({
55 id: `conformance-svelte-${sourceSeq++}`,
56 getKey: (r) => r.id,
57 initialData: [...initialData],
58 }),
59 )
60 const write = writer<T>(collection)
61 return {
62 collection,
63 insert: (row) => write(`insert`, row),
64 update: (row) => write(`update`, row),
65 remove: (row) => write(`delete`, row),
66 }
67}
68
69function makeDeferredSource<
70 T extends { id: string },
71>(): DeferredSourceHandle<T> {
72 const collection = createCollection(
73 mockSyncCollectionOptionsNoInitialState<T>({
74 id: `conformance-svelte-${sourceSeq++}`,
75 getKey: (r) => r.id,
76 }),
77 )
78 collection.startSyncImmediate()
79 const write = writer<T>(collection)
80 return {
81 collection,
82 insert: (row) => write(`insert`, row),
83 update: (row) => write(`update`, row),
84 remove: (row) => write(`delete`, row),
85 emit: (rows) => {
86 collection.utils.begin()
87 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
88 collection.utils.commit()
89 },
90 markReady: () => collection.utils.markReady(),
91 }
92}
93
94function makePrecreated(build: QueryBuild, opts?: { startSync?: boolean }) {
95 const collection = createLiveQueryCollection({
96 query: build as any,
97 startSync: opts?.startSync ?? true,
98 })
99 return { collection }
100}
101
102function makeErrorSource() {
103 const expectedError = new Error(`conformance: sync failure`)
104 let startup: { returned: true } | { returned: false; error: unknown } = {
105 returned: true,
106 }
107 const collection = createCollection<{ id: string }>({
108 id: `conformance-svelte-err-${sourceSeq++}`,
109 getKey: (r) => r.id,
110 startSync: false,
111 sync: {
112 sync: () => {
113 throw expectedError
114 },
115 },
116 })
117 try {
118 collection.startSyncImmediate()
119 } catch (error) {
120 startup = { returned: false, error }
121 }
122 return { collection, expectedError, startup }
123}
124
125async function settle() {
126 flushSync()
127 await new Promise((resolve) => setTimeout(resolve, 10))
128 flushSync()
129}
130
131function makeHandle(getQuery: () => any, dispose: () => void): LiveQueryHandle {
132 return {
133 current(): ConformanceResult {
134 const query = getQuery()
135 return expectResultSurface({
136 data: query?.data,
137 state: query?.state,
138 status: query?.status,
139 isReady: query?.isReady,
140 isError: query?.isError,
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 }
154}
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)
162}
163
164function mountCollection(collection: any) {
165 let query: any
166 const dispose = $effect.root(() => {
167 query = useLiveQuery(collection)
168 })
169 return makeHandle(() => query, dispose)
170}
171
172function mountConfig(build: QueryBuild) {
173 let query: any
174 const dispose = $effect.root(() => {
175 query = useLiveQuery({ query: build } as any)
176 })
177 return makeHandle(() => query, dispose)
178}
179
180function mountDisabled() {
181 // Svelte's disabled convention: the query callback returns null.
182 let query: any
183 const dispose = $effect.root(() => {
184 query = useLiveQuery(() => null as any)
185 })
186 return makeHandle(() => query, dispose)
187}
188
189function mountControllable<P>(
190 build: (q: any, param: P) => any,
191 initial: P,
192): ControllableHandle<P> {
193 let param = $state(initial)
194 let query: any
195 const dispose = $effect.root(() => {
196 query = useLiveQuery((q: any) => build(q, param), [() => param])
197 })
198 const handle = makeHandle(() => query, dispose)
199 return {
200 ...handle,
201 async setParam(next: P) {
202 param = next
203 await settle()
204 },
205 }
206}
207
208const svelteDriver: LiveQueryDriver = {
209 name: `svelte`,
210 disabledRepresentation: `empty-reactive`,
211 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
212 makeSource,
213 makeDeferredSource,
214 makePrecreated,
215 makeErrorSource,
216 mount,
217 mountControllable,
218 mountCollection,
219 mountConfig,
220 mountDisabled,
221 knownGaps: [],
222 features: { serverSnapshot: false, suspense: false },
223}
224
225runSuite(svelteDriver)
226it(`preserves raw result types through the actual driver reader`, () => {
227 const raw: Record<string, unknown> = {
228 data: [{ id: `a`, value: undefined }],
229 state: new Map(),
230 status: `disabled`,
231 isReady: false,
232 isError: false,
233 isEnabled: false,
234 }
235 const handle = makeHandle(
236 () => raw,
237 () => {},
238 )
239 try {
240 const healthy = handle.current()
241 expect(healthy.data).toBe(raw.data)
242 expect(healthy.state).toBe(raw.state)
243 expect(healthy.isReady).toBe(false)
244 expect(healthy.isError).toBe(false)
245 expect(healthy.isEnabled).toBe(false)
246 for (const key of [`status`, `isReady`, `isError`]) {
247 const original = raw[key]
248 delete raw[key]
249 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
250 for (const invalid of key === `status`
251 ? [undefined, 0]
252 : [undefined, 0, ``]) {
253 raw[key] = invalid
254 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
255 }
256 raw[key] = original
257 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
258 }
259 } finally {
260 handle.unmount()
261 }
262})