Open History to see the last commit
1/**
2 * Preact driver for the shared live-query conformance suite.
3 *
4 * Everything realm-sensitive — collection creation and query operators — is
5 * imported here (Preact package's `@tanstack/db`) and handed to the shared
6 * scenarios, so instances match what this package's `useLiveQuery` expects.
7 *
8 * Observation cut: `render-probe.ts` records the hook result at each Preact
9 * commit. `flush` is one `act` around a macrotask, so framework updates and
10 * core sync settle before the suite reads the last committed result. A
11 * rejected query throws from the mount or from `setParam`'s rerender.
12 *
13 * `mountControllable` captures its parameter in the query callback instead of
14 * passing a dependency list. The hook derives identity from the query IR, so
15 * this exercises recompilation through the public API that Preact offers.
16 *
17 * All registered laws must pass; the driver has no whole-test waivers.
18 */
19import { act } from 'preact/test-utils'
20import {
21 coalesce,
22 count,
23 createCollection,
24 createLiveQueryCollection,
25 createOptimisticAction,
26 eq,
27 groupKeys,
28 gt,
29 sum,
30} from '@tanstack/db'
31import {
32 mockSyncCollectionOptions,
33 mockSyncCollectionOptionsNoInitialState,
34} from '../../db/tests/utils'
35import { useLiveQuery } from '../src/useLiveQuery'
36import { runSuite } from '../../db/tests/conformance/suite'
37import { createPublicationLog } from '../../db/tests/conformance/publication-log'
38import { makeLaggingSource } from '../../db/tests/conformance/lagging-source'
39import { makeSyncSource } from '../../db/tests/conformance/sync-source'
40import { makeErrorSource as makeSharedErrorSource } from '../../db/tests/conformance/error-source'
41import { expectResultSurface } from '../../db/tests/conformance/result-laws'
42import { renderHook, settle } from './render-probe'
43import type { MountedHook } from './render-probe'
44import type { PooledLiveQueries } from '@tanstack/db'
45import type {
46 ConformanceResult,
47 ControllableHandle,
48 DeferredSourceHandle,
49 LiveQueryDriver,
50 LiveQueryHandle,
51 QueryBuild,
52 SourceHandle,
53} from '../../db/tests/conformance/contract'
54
55let sourceSeq = 0
56
57function writer<T extends { id: string }>(collection: any) {
58 return (type: `insert` | `update` | `delete`, value: T) => {
59 collection.utils.begin()
60 collection.utils.write({ type, value })
61 collection.utils.commit()
62 }
63}
64
65function makeSource<T extends { id: string }>(
66 initialData: ReadonlyArray<T>,
67 collectionId?: string,
68): SourceHandle<T> {
69 const collection = createCollection(
70 mockSyncCollectionOptions<T>({
71 id: collectionId ?? `conformance-preact-${sourceSeq++}`,
72 getKey: (r) => r.id,
73 initialData: [...initialData],
74 }),
75 )
76 const write = writer<T>(collection)
77 return {
78 collection,
79 insert: (row) => write(`insert`, row),
80 update: (row) => write(`update`, row),
81 remove: (row) => write(`delete`, row),
82 }
83}
84
85function makeDeferredSource<
86 T extends { id: string },
87>(): DeferredSourceHandle<T> {
88 const collection = createCollection(
89 mockSyncCollectionOptionsNoInitialState<T>({
90 id: `conformance-preact-${sourceSeq++}`,
91 getKey: (r) => r.id,
92 }),
93 )
94 // Start sync so the sync fn binds utils and the collection sits in `loading`
95 // (NoInitialState never calls markReady on its own).
96 collection.startSyncImmediate()
97 const write = writer<T>(collection)
98 return {
99 collection,
100 insert: (row) => write(`insert`, row),
101 update: (row) => write(`update`, row),
102 remove: (row) => write(`delete`, row),
103 emit: (rows) => {
104 collection.utils.begin()
105 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
106 collection.utils.commit()
107 },
108 markReady: () => collection.utils.markReady(),
109 }
110}
111
112function makePrecreated(
113 build: QueryBuild,
114 opts?: { startSync?: boolean; gcTime?: number },
115) {
116 const collection = createLiveQueryCollection({
117 query: build as any,
118 startSync: opts?.startSync ?? true,
119 gcTime: opts?.gcTime,
120 })
121 return { collection }
122}
123
124function makeErrorSource(kind: `fail` | `crash`) {
125 return makeSharedErrorSource(
126 createCollection,
127 `conformance-preact-err-${sourceSeq++}`,
128 kind,
129 )
130}
131
132function makeHandle(hook: MountedHook<any>): LiveQueryHandle {
133 return {
134 collection: () => hook.result.current?.collection ?? null,
135 current(): ConformanceResult {
136 const r: any = hook.result.current
137 return expectResultSurface({
138 data: r?.data,
139 state: r?.state,
140 status: r?.status,
141 isReady: r?.isReady,
142 isLoadingError: r?.isLoadingError,
143 isCrashed: r?.isCrashed,
144 isSyncError: r?.isSyncError,
145 // Read the hook's real `isEnabled` field so the suite catches a broken
146 // one (deriving from status would mask it).
147 isEnabled: r?.isEnabled,
148 health: r?.health,
149 })
150 },
151 flush: settle,
152 async apply(fn: () => void) {
153 await act(async () => {
154 fn()
155 await new Promise((resolve) => setTimeout(resolve, 0))
156 })
157 },
158 unmount() {
159 hook.unmount()
160 },
161 }
162}
163
164function mount(build: QueryBuild) {
165 return makeHandle(renderHook(() => useLiveQuery(build as any)))
166}
167
168function mountCollection(collection: any) {
169 return makeHandle(renderHook(() => useLiveQuery(collection)))
170}
171
172function mountConfig(
173 build: QueryBuild,
174 opts?: {
175 gcTime?: number
176 pool?: PooledLiveQueries
177 queryKey?: ReadonlyArray<unknown>
178 },
179) {
180 return makeHandle(
181 renderHook(() => useLiveQuery({ query: build as any, ...opts })),
182 )
183}
184
185function mountDisabled() {
186 // Preact's disabled convention: the query callback returns null.
187 return makeHandle(renderHook(() => useLiveQuery(() => null as any)))
188}
189
190function mountControllable<P>(
191 build: (q: any, param: P) => any,
192 initial: P,
193 opts?: { pool?: PooledLiveQueries },
194): ControllableHandle<P> {
195 const published = createPublicationLog()
196 const hook = renderHook(
197 ({ param }: { param: P }) =>
198 opts?.pool !== undefined
199 ? // The config form derives identity from the query on each render.
200 useLiveQuery({ query: (q: any) => build(q, param), pool: opts.pool })
201 : useLiveQuery((q: any) => build(q, param)),
202 {
203 initialProps: { param: initial },
204 onCommit: (result) => published.record(result.data, result.state),
205 },
206 )
207 const handle = makeHandle(hook)
208 return {
209 ...handle,
210 publications: published.values,
211 statePublications: published.stateValues,
212 async setParam(param: P) {
213 hook.rerender({ param })
214 await settle()
215 },
216 }
217}
218
219// The config-object form with a queryKey chosen per step; an undefined key
220// leaves the hook to derive the identity.
221function mountKeyedControllable<P>(
222 build: (q: any, param: P) => any,
223 key: (param: P) => ReadonlyArray<unknown> | undefined,
224 initial: P,
225): ControllableHandle<P> {
226 const published = createPublicationLog()
227 const hook = renderHook(
228 ({ param }: { param: P }) =>
229 useLiveQuery({
230 query: (q: any) => build(q, param),
231 queryKey: key(param),
232 } as any),
233 {
234 initialProps: { param: initial },
235 onCommit: (result) => published.record(result.data, result.state),
236 },
237 )
238 const handle = makeHandle(hook)
239 return {
240 ...handle,
241 publications: published.values,
242 statePublications: published.stateValues,
243 async setParam(param: P) {
244 hook.rerender({ param })
245 await settle()
246 },
247 }
248}
249
250const preactDriver: LiveQueryDriver = {
251 name: `preact`,
252 // Each render re-runs the query input and compares its identity.
253 comparesQueryIdentity: true,
254 disabledRepresentation: `absent`,
255 ops: { eq, gt, count, sum, coalesce, groupKeys, createOptimisticAction },
256 makeSource,
257 makeDeferredSource,
258 makeLaggingSource: <T extends { id: string }>() =>
259 makeLaggingSource<T>(
260 createCollection,
261 `conformance-preact-lagging-${sourceSeq++}`,
262 ),
263 makeSyncSource: <T extends { id: string }>(data: ReadonlyArray<T>) =>
264 makeSyncSource<T>(
265 createCollection,
266 `conformance-preact-health-${sourceSeq++}`,
267 data,
268 ),
269 makePrecreated,
270 makeErrorSource,
271 mount,
272 mountControllable,
273 mountKeyedControllable,
274 mountCollection,
275 mountConfig,
276 mountDisabled,
277 knownGaps: [],
278 features: { serverSnapshot: false, suspense: false, pooledEqFilters: true },
279}
280
281runSuite(preactDriver)