Open History to see the last commit
1/**
2 * Vue driver for the shared live-query conformance suite.
3 *
4 * Realm-sensitive pieces (collection factories, query operators) are imported
5 * from Vue's `@tanstack/db` and handed to the shared scenarios. Vue composables
6 * run inside an `effectScope` so `unmount` can dispose them via `scope.stop()`,
7 * which triggers the `watchEffect` `onInvalidate` cleanup.
8 *
9 * All registered laws must pass; the driver has no whole-test waivers.
10 */
11import { describe, expect, it } from 'vitest'
12import {
13 coalesce,
14 count,
15 createCollection,
16 createLiveQueryCollection,
17 createOptimisticAction,
18 eq,
19 groupKeys,
20 gt,
21 sum,
22} from '@tanstack/db'
23import { effectScope, nextTick, onScopeDispose, ref, watch } from 'vue'
24import {
25 mockSyncCollectionOptions,
26 mockSyncCollectionOptionsNoInitialState,
27} from '../../db/tests/utils'
28import { useLiveQuery } from '../src/useLiveQuery'
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 { withScopeSetup } from '../../db/tests/conformance/scope-setup'
36import type { PooledLiveQueries } from '@tanstack/db'
37import type {
38 ConformanceResult,
39 ControllableHandle,
40 DeferredSourceHandle,
41 LiveQueryDriver,
42 LiveQueryHandle,
43 QueryBuild,
44 SourceHandle,
45} from '../../db/tests/conformance/contract'
46
47let sourceSeq = 0
48
49function writer<T extends { id: string }>(collection: any) {
50 return (type: `insert` | `update` | `delete`, value: T) => {
51 collection.utils.begin()
52 collection.utils.write({ type, value })
53 collection.utils.commit()
54 }
55}
56
57function makeSource<T extends { id: string }>(
58 initialData: ReadonlyArray<T>,
59 collectionId?: string,
60 options?: { rowUpdateMode?: `full` },
61): SourceHandle<T> {
62 const collection = createCollection(
63 mockSyncCollectionOptions<T>({
64 id: collectionId ?? `conformance-vue-${sourceSeq++}`,
65 getKey: (r) => r.id,
66 initialData: [...initialData],
67 rowUpdateMode: options?.rowUpdateMode,
68 }),
69 )
70 const write = writer<T>(collection)
71 return {
72 collection,
73 insert: (row) => write(`insert`, row),
74 update: (row) => write(`update`, row),
75 remove: (row) => write(`delete`, row),
76 }
77}
78
79function makeDeferredSource<
80 T extends { id: string },
81>(): DeferredSourceHandle<T> {
82 const collection = createCollection(
83 mockSyncCollectionOptionsNoInitialState<T>({
84 id: `conformance-vue-${sourceSeq++}`,
85 getKey: (r) => r.id,
86 }),
87 )
88 collection.startSyncImmediate()
89 const write = writer<T>(collection)
90 return {
91 collection,
92 insert: (row) => write(`insert`, row),
93 update: (row) => write(`update`, row),
94 remove: (row) => write(`delete`, row),
95 emit: (rows) => {
96 collection.utils.begin()
97 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
98 collection.utils.commit()
99 },
100 markReady: () => collection.utils.markReady(),
101 }
102}
103
104function makePrecreated(
105 build: QueryBuild,
106 opts?: { startSync?: boolean; gcTime?: number },
107) {
108 const collection = createLiveQueryCollection({
109 query: build as any,
110 startSync: opts?.startSync ?? true,
111 gcTime: opts?.gcTime,
112 })
113 return { collection }
114}
115
116function makeErrorSource(kind: `fail` | `crash`) {
117 return makeSharedErrorSource(
118 createCollection,
119 `conformance-vue-err-${sourceSeq++}`,
120 kind,
121 )
122}
123
124async function settle() {
125 await nextTick()
126 await new Promise((resolve) => setTimeout(resolve, 10))
127}
128
129function makeHandle(result: any, scope: ReturnType<typeof effectScope>) {
130 const handle: LiveQueryHandle = {
131 collection: () => result.collection?.value ?? null,
132 current(): ConformanceResult {
133 return expectResultSurface({
134 data: result.data?.value,
135 state: result.state?.value,
136 status: result.status?.value,
137 isReady: result.isReady?.value,
138 isLoadingError: result.isLoadingError?.value,
139 isCrashed: result.isCrashed?.value,
140 isSyncError: result.isSyncError?.value,
141 // vue-db exposes no `isEnabled`; derive it from status (status-derived).
142 isEnabled: result.status?.value !== `disabled`,
143 health: result.health?.value,
144 })
145 },
146 flush: settle,
147 async apply(fn: () => void) {
148 fn()
149 await settle()
150 },
151 unmount() {
152 scope.stop()
153 },
154 }
155 return handle
156}
157
158function runInScope<R>(fn: () => R): {
159 result: R
160 scope: ReturnType<typeof effectScope>
161} {
162 const scope = effectScope()
163 let result!: R
164 withScopeSetup(
165 () =>
166 scope.run(() => {
167 result = fn()
168 }),
169 () => scope.stop(),
170 )
171 return { result, scope }
172}
173
174function mount(build: QueryBuild) {
175 const { result, scope } = runInScope(() => useLiveQuery(build as any))
176 return makeHandle(result, scope)
177}
178
179function mountCollection(collection: any) {
180 const { result, scope } = runInScope(() => useLiveQuery(collection))
181 return makeHandle(result, scope)
182}
183
184function mountConfig(
185 build: QueryBuild,
186 opts?: { gcTime?: number; pool?: PooledLiveQueries },
187) {
188 const { result, scope } = runInScope(() =>
189 useLiveQuery({ query: build, ...opts } as any),
190 )
191 return makeHandle(result, scope)
192}
193
194function mountDisabled() {
195 // Vue's disabled convention: the query callback returns undefined.
196 const { result, scope } = runInScope(() =>
197 useLiveQuery(() => undefined as any),
198 )
199 return makeHandle(result, scope)
200}
201
202function mountControllable<P>(
203 build: (q: any, param: P) => any,
204 initial: P,
205 opts?: { pool?: PooledLiveQueries },
206): ControllableHandle<P> {
207 const param = ref(initial) as { value: P }
208 const published = createPublicationLog()
209 const { result, scope } = runInScope(() => {
210 const query =
211 opts?.pool !== undefined
212 ? useLiveQuery(
213 {
214 query: (q: any) => build(q, param.value),
215 pool: opts.pool,
216 } as any,
217 [() => param.value],
218 )
219 : useLiveQuery((q: any) => build(q, param.value), [() => param.value])
220 // Vue renders the value present at each pre-flush.
221 watch(
222 () => [query.data.value, [...query.state.value.values()]],
223 ([data]) => published.record(data, query.state.value),
224 { flush: `pre`, immediate: true },
225 )
226 return query
227 })
228 const handle = makeHandle(result, scope)
229 return {
230 ...handle,
231 publications: published.values,
232 statePublications: published.stateValues,
233 async setParam(next: P) {
234 param.value = next
235 // The first paint after the change: the framework has flushed its
236 // reactive work, but no later task has run.
237 await nextTick()
238 published.record(result.data.value, result.state.value)
239 await settle()
240 },
241 }
242}
243
244const vueDriver: LiveQueryDriver = {
245 name: `vue`,
246 // Reactive reads decide when the query compiles again.
247 comparesQueryIdentity: false,
248 disabledRepresentation: `empty-reactive`,
249 ops: { eq, gt, count, sum, coalesce, groupKeys, createOptimisticAction },
250 makeSource,
251 makeDeferredSource,
252 makeLaggingSource: <T extends { id: string }>() =>
253 makeLaggingSource<T>(
254 createCollection,
255 `conformance-vue-lagging-${sourceSeq++}`,
256 ),
257 makeSyncSource: <T extends { id: string }>(data: ReadonlyArray<T>) =>
258 makeSyncSource<T>(
259 createCollection,
260 `conformance-vue-health-${sourceSeq++}`,
261 data,
262 ),
263 makePrecreated,
264 makeErrorSource,
265 mount,
266 mountControllable,
267 mountCollection,
268 mountConfig,
269 mountDisabled,
270 knownGaps: [],
271 features: { serverSnapshot: false, suspense: false, pooledEqFilters: true },
272}
273
274describe(`owned native scope setup`, () => {
275 it(`keeps a successful scope alive until explicit disposal`, () => {
276 let calls = 0
277 const handle = runInScope(() => {
278 onScopeDispose(() => {
279 calls++
280 })
281 return 7
282 })
283 expect(calls).toBe(0)
284 handle.scope.stop()
285 expect(calls).toBe(1)
286 })
287
288 it.each([false, true])(
289 `disposes failed setup and retains errors, cleanupFails=%s`,
290 (cleanupFails) => {
291 const primary = new Error(`scope setup failure`)
292 const secondary = new Error(`scope cleanup failure`)
293 let calls = 0
294 let caught: unknown
295 try {
296 runInScope(() => {
297 onScopeDispose(() => {
298 calls++
299 if (cleanupFails) throw secondary
300 })
301 throw primary
302 })
303 } catch (error) {
304 caught = error
305 }
306 expect(calls).toBe(1)
307 if (cleanupFails) {
308 expect(caught).toBeInstanceOf(AggregateError)
309 expect((caught as AggregateError).errors).toEqual([primary, secondary])
310 expect((caught as AggregateError).cause).toBe(primary)
311 } else expect(caught).toBe(primary)
312 },
313 )
314})
315
316runSuite(vueDriver)
317it(`preserves raw result types through the actual driver reader`, () => {
318 const raw: Record<string, unknown> = {
319 data: [{ id: `a`, value: undefined }],
320 state: new Map(),
321 status: `disabled`,
322 isReady: false,
323 isLoadingError: false,
324 isCrashed: false,
325 isSyncError: false,
326 isEnabled: false,
327 }
328 const scope = effectScope()
329 const result = Object.fromEntries(
330 Object.keys(raw).map((key) => [
331 key,
332 {
333 get value() {
334 return raw[key]
335 },
336 },
337 ]),
338 )
339 const handle = makeHandle(result, scope)
340 try {
341 const healthy = handle.current()
342 expect(healthy.data).toBe(raw.data)
343 expect(healthy.state).toBe(raw.state)
344 expect(healthy.isReady).toBe(false)
345 expect(healthy.isLoadingError).toBe(false)
346 expect(healthy.isEnabled).toBe(false)
347 for (const key of [`status`, `isReady`, `isLoadingError`]) {
348 const original = raw[key]
349 delete raw[key]
350 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
351 for (const invalid of key === `status`
352 ? [undefined, 0]
353 : [undefined, 0, ``]) {
354 raw[key] = invalid
355 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
356 }
357 raw[key] = original
358 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
359 }
360 } finally {
361 handle.unmount()
362 }
363})