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 persistedStatus: result.persistedStatus?.value,
140 isPersistedReady: result.isPersistedReady?.value,
141 persistedError: result.persistedError?.value,
142 isError: result.isError?.value,
143 // vue-db exposes no `isEnabled`; derive it from status (status-derived).
144 isEnabled: result.status?.value !== `disabled`,
145 })
146 },
147 flush: settle,
148 async apply(fn: () => void) {
149 fn()
150 await settle()
151 },
152 unmount() {
153 scope.stop()
154 },
155 }
156 return handle
157}
158
159function runInScope<R>(fn: () => R): {
160 result: R
161 scope: ReturnType<typeof effectScope>
162} {
163 const scope = effectScope()
164 let result!: R
165 withScopeSetup(
166 () =>
167 scope.run(() => {
168 result = fn()
169 }),
170 () => scope.stop(),
171 )
172 return { result, scope }
173}
174
175function mount(build: QueryBuild) {
176 const { result, scope } = runInScope(() => useLiveQuery(build as any))
177 return makeHandle(result, scope)
178}
179
180function mountCollection(collection: any) {
181 const { result, scope } = runInScope(() => useLiveQuery(collection))
182 return makeHandle(result, scope)
183}
184
185function mountConfig(build: QueryBuild) {
186 const { result, scope } = runInScope(() =>
187 useLiveQuery({ query: build } as any),
188 )
189 return makeHandle(result, scope)
190}
191
192function mountDisabled() {
193 // Vue's disabled convention: the query callback returns undefined.
194 const { result, scope } = runInScope(() =>
195 useLiveQuery(() => undefined as any),
196 )
197 return makeHandle(result, scope)
198}
199
200function mountControllable<P>(
201 build: (q: any, param: P) => any,
202 initial: P,
203): ControllableHandle<P> {
204 const param = ref(initial) as { value: P }
205 const { result, scope } = runInScope(() =>
206 useLiveQuery((q: any) => build(q, param.value), [() => param.value]),
207 )
208 const handle = makeHandle(result, scope)
209 return {
210 ...handle,
211 async setParam(next: P) {
212 param.value = next
213 await settle()
214 },
215 }
216}
217
218const vueDriver: LiveQueryDriver = {
219 name: `vue`,
220 disabledRepresentation: `empty-reactive`,
221 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
222 makeSource,
223 makeDeferredSource,
224 makePrecreated,
225 makeErrorSource,
226 mount,
227 mountControllable,
228 mountCollection,
229 mountConfig,
230 mountDisabled,
231 knownGaps: [],
232 features: { serverSnapshot: false, suspense: false, pooledEqFilters: true },
233}
234
235describe(`owned native scope setup`, () => {
236 it(`keeps a successful scope alive until explicit disposal`, () => {
237 let calls = 0
238 const handle = runInScope(() => {
239 onScopeDispose(() => {
240 calls++
241 })
242 return 7
243 })
244 expect(calls).toBe(0)
245 handle.scope.stop()
246 expect(calls).toBe(1)
247 })
248
249 it.each([false, true])(
250 `disposes failed setup and retains errors, cleanupFails=%s`,
251 (cleanupFails) => {
252 const primary = new Error(`scope setup failure`)
253 const secondary = new Error(`scope cleanup failure`)
254 let calls = 0
255 let caught: unknown
256 try {
257 runInScope(() => {
258 onScopeDispose(() => {
259 calls++
260 if (cleanupFails) throw secondary
261 })
262 throw primary
263 })
264 } catch (error) {
265 caught = error
266 }
267 expect(calls).toBe(1)
268 if (cleanupFails) {
269 expect(caught).toBeInstanceOf(AggregateError)
270 expect((caught as AggregateError).errors).toEqual([primary, secondary])
271 expect((caught as AggregateError).cause).toBe(primary)
272 } else expect(caught).toBe(primary)
273 },
274 )
275})
276
277runSuite(vueDriver)
278it(`preserves raw result types through the actual driver reader`, () => {
279 const raw: Record<string, unknown> = {
280 data: [{ id: `a`, value: undefined }],
281 state: new Map(),
282 status: `disabled`,
283 isReady: false,
284 isError: false,
285 isEnabled: false,
286 }
287 const scope = effectScope()
288 const result = Object.fromEntries(
289 Object.keys(raw).map((key) => [
290 key,
291 {
292 get value() {
293 return raw[key]
294 },
295 },
296 ]),
297 )
298 const handle = makeHandle(result, scope)
299 try {
300 const healthy = handle.current()
301 expect(healthy.data).toBe(raw.data)
302 expect(healthy.state).toBe(raw.state)
303 expect(healthy.isReady).toBe(false)
304 expect(healthy.isError).toBe(false)
305 expect(healthy.isEnabled).toBe(false)
306 for (const key of [`status`, `isReady`, `isError`]) {
307 const original = raw[key]
308 delete raw[key]
309 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
310 for (const invalid of key === `status`
311 ? [undefined, 0]
312 : [undefined, 0, ``]) {
313 raw[key] = invalid
314 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
315 }
316 raw[key] = original
317 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
318 }
319 } finally {
320 handle.unmount()
321 }
322})