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 gt,
20 sum,
21} from '@tanstack/db'
22import { effectScope, nextTick, onScopeDispose, ref } from 'vue'
23import {
24 mockSyncCollectionOptions,
25 mockSyncCollectionOptionsNoInitialState,
26} from '../../db/tests/utils'
27import { useLiveQuery } from '../src/useLiveQuery'
28import { runSuite } from '../../db/tests/conformance/suite'
29import { expectResultSurface } from '../../db/tests/conformance/result-laws'
30import { withScopeSetup } from '../../db/tests/conformance/scope-setup'
31import type {
32 ConformanceResult,
33 ControllableHandle,
34 DeferredSourceHandle,
35 LiveQueryDriver,
36 LiveQueryHandle,
37 QueryBuild,
38 SourceHandle,
39} from '../../db/tests/conformance/contract'
40
41let sourceSeq = 0
42
43function writer<T extends { id: string }>(collection: any) {
44 return (type: `insert` | `update` | `delete`, value: T) => {
45 collection.utils.begin()
46 collection.utils.write({ type, value })
47 collection.utils.commit()
48 }
49}
50
51function makeSource<T extends { id: string }>(
52 initialData: ReadonlyArray<T>,
53): SourceHandle<T> {
54 const collection = createCollection(
55 mockSyncCollectionOptions<T>({
56 id: `conformance-vue-${sourceSeq++}`,
57 getKey: (r) => r.id,
58 initialData: [...initialData],
59 }),
60 )
61 const write = writer<T>(collection)
62 return {
63 collection,
64 insert: (row) => write(`insert`, row),
65 update: (row) => write(`update`, row),
66 remove: (row) => write(`delete`, row),
67 }
68}
69
70function makeDeferredSource<
71 T extends { id: string },
72>(): DeferredSourceHandle<T> {
73 const collection = createCollection(
74 mockSyncCollectionOptionsNoInitialState<T>({
75 id: `conformance-vue-${sourceSeq++}`,
76 getKey: (r) => r.id,
77 }),
78 )
79 collection.startSyncImmediate()
80 const write = writer<T>(collection)
81 return {
82 collection,
83 insert: (row) => write(`insert`, row),
84 update: (row) => write(`update`, row),
85 remove: (row) => write(`delete`, row),
86 emit: (rows) => {
87 collection.utils.begin()
88 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
89 collection.utils.commit()
90 },
91 markReady: () => collection.utils.markReady(),
92 }
93}
94
95function makePrecreated(build: QueryBuild, opts?: { startSync?: boolean }) {
96 const collection = createLiveQueryCollection({
97 query: build as any,
98 startSync: opts?.startSync ?? true,
99 })
100 return { collection }
101}
102
103function makeErrorSource() {
104 const expectedError = new Error(`conformance: sync failure`)
105 let startup: { returned: true } | { returned: false; error: unknown } = {
106 returned: true,
107 }
108 const collection = createCollection<{ id: string }>({
109 id: `conformance-vue-err-${sourceSeq++}`,
110 getKey: (r) => r.id,
111 startSync: false,
112 sync: {
113 sync: () => {
114 throw expectedError
115 },
116 },
117 })
118 try {
119 collection.startSyncImmediate()
120 } catch (error) {
121 startup = { returned: false, error }
122 }
123 return { collection, expectedError, startup }
124}
125
126async function settle() {
127 await nextTick()
128 await new Promise((resolve) => setTimeout(resolve, 10))
129}
130
131function makeHandle(result: any, scope: ReturnType<typeof effectScope>) {
132 const handle: LiveQueryHandle = {
133 current(): ConformanceResult {
134 return expectResultSurface({
135 data: result.data?.value,
136 state: result.state?.value,
137 status: result.status?.value,
138 isReady: result.isReady?.value,
139 isError: result.isError?.value,
140 // vue-db exposes no `isEnabled`; derive it from status (status-derived).
141 isEnabled: result.status?.value !== `disabled`,
142 })
143 },
144 flush: settle,
145 async apply(fn: () => void) {
146 fn()
147 await settle()
148 },
149 unmount() {
150 scope.stop()
151 },
152 }
153 return handle
154}
155
156function runInScope<R>(fn: () => R): {
157 result: R
158 scope: ReturnType<typeof effectScope>
159} {
160 const scope = effectScope()
161 let result!: R
162 withScopeSetup(
163 () =>
164 scope.run(() => {
165 result = fn()
166 }),
167 () => scope.stop(),
168 )
169 return { result, scope }
170}
171
172function mount(build: QueryBuild) {
173 const { result, scope } = runInScope(() => useLiveQuery(build as any))
174 return makeHandle(result, scope)
175}
176
177function mountCollection(collection: any) {
178 const { result, scope } = runInScope(() => useLiveQuery(collection))
179 return makeHandle(result, scope)
180}
181
182function mountConfig(build: QueryBuild) {
183 const { result, scope } = runInScope(() =>
184 useLiveQuery({ query: build } as any),
185 )
186 return makeHandle(result, scope)
187}
188
189function mountDisabled() {
190 // Vue's disabled convention: the query callback returns undefined.
191 const { result, scope } = runInScope(() =>
192 useLiveQuery(() => undefined as any),
193 )
194 return makeHandle(result, scope)
195}
196
197function mountControllable<P>(
198 build: (q: any, param: P) => any,
199 initial: P,
200): ControllableHandle<P> {
201 const param = ref(initial) as { value: P }
202 const { result, scope } = runInScope(() =>
203 useLiveQuery((q: any) => build(q, param.value), [() => param.value]),
204 )
205 const handle = makeHandle(result, scope)
206 return {
207 ...handle,
208 async setParam(next: P) {
209 param.value = next
210 await settle()
211 },
212 }
213}
214
215const vueDriver: LiveQueryDriver = {
216 name: `vue`,
217 disabledRepresentation: `empty-reactive`,
218 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
219 makeSource,
220 makeDeferredSource,
221 makePrecreated,
222 makeErrorSource,
223 mount,
224 mountControllable,
225 mountCollection,
226 mountConfig,
227 mountDisabled,
228 knownGaps: [],
229 features: { serverSnapshot: false, suspense: false },
230}
231
232describe(`owned native scope setup`, () => {
233 it(`keeps a successful scope alive until explicit disposal`, () => {
234 let calls = 0
235 const handle = runInScope(() => {
236 onScopeDispose(() => {
237 calls++
238 })
239 return 7
240 })
241 expect(calls).toBe(0)
242 handle.scope.stop()
243 expect(calls).toBe(1)
244 })
245
246 it.each([false, true])(
247 `disposes failed setup and retains errors, cleanupFails=%s`,
248 (cleanupFails) => {
249 const primary = new Error(`scope setup failure`)
250 const secondary = new Error(`scope cleanup failure`)
251 let calls = 0
252 let caught: unknown
253 try {
254 runInScope(() => {
255 onScopeDispose(() => {
256 calls++
257 if (cleanupFails) throw secondary
258 })
259 throw primary
260 })
261 } catch (error) {
262 caught = error
263 }
264 expect(calls).toBe(1)
265 if (cleanupFails) {
266 expect(caught).toBeInstanceOf(AggregateError)
267 expect((caught as AggregateError).errors).toEqual([primary, secondary])
268 expect((caught as AggregateError).cause).toBe(primary)
269 } else expect(caught).toBe(primary)
270 },
271 )
272})
273
274runSuite(vueDriver)
275it(`preserves raw result types through the actual driver reader`, () => {
276 const raw: Record<string, unknown> = {
277 data: [{ id: `a`, value: undefined }],
278 state: new Map(),
279 status: `disabled`,
280 isReady: false,
281 isError: false,
282 isEnabled: false,
283 }
284 const scope = effectScope()
285 const result = Object.fromEntries(
286 Object.keys(raw).map((key) => [
287 key,
288 {
289 get value() {
290 return raw[key]
291 },
292 },
293 ]),
294 )
295 const handle = makeHandle(result, scope)
296 try {
297 const healthy = handle.current()
298 expect(healthy.data).toBe(raw.data)
299 expect(healthy.state).toBe(raw.state)
300 expect(healthy.isReady).toBe(false)
301 expect(healthy.isError).toBe(false)
302 expect(healthy.isEnabled).toBe(false)
303 for (const key of [`status`, `isReady`, `isError`]) {
304 const original = raw[key]
305 delete raw[key]
306 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
307 for (const invalid of key === `status`
308 ? [undefined, 0]
309 : [undefined, 0, ``]) {
310 raw[key] = invalid
311 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
312 }
313 raw[key] = original
314 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
315 }
316 } finally {
317 handle.unmount()
318 }
319})