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 options?: { rowUpdateMode?: `full` },
69): SourceHandle<T> {
70 const collection = createCollection(
71 mockSyncCollectionOptions<T>({
72 id: collectionId ?? `conformance-preact-${sourceSeq++}`,
73 getKey: (r) => r.id,
74 initialData: [...initialData],
75 rowUpdateMode: options?.rowUpdateMode,
76 }),
77 )
78 const write = writer<T>(collection)
79 return {
80 collection,
81 insert: (row) => write(`insert`, row),
82 update: (row) => write(`update`, row),
83 remove: (row) => write(`delete`, row),
84 }
85}
86
87function makeDeferredSource<
88 T extends { id: string },
89>(): DeferredSourceHandle<T> {
90 const collection = createCollection(
91 mockSyncCollectionOptionsNoInitialState<T>({
92 id: `conformance-preact-${sourceSeq++}`,
93 getKey: (r) => r.id,
94 }),
95 )
96 // Start sync so the sync fn binds utils and the collection sits in `loading`
97 // (NoInitialState never calls markReady on its own).
98 collection.startSyncImmediate()
99 const write = writer<T>(collection)
100 return {
101 collection,
102 insert: (row) => write(`insert`, row),
103 update: (row) => write(`update`, row),
104 remove: (row) => write(`delete`, row),
105 emit: (rows) => {
106 collection.utils.begin()
107 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
108 collection.utils.commit()
109 },
110 markReady: () => collection.utils.markReady(),
111 }
112}
113
114function makePrecreated(
115 build: QueryBuild,
116 opts?: { startSync?: boolean; gcTime?: number },
117) {
118 const collection = createLiveQueryCollection({
119 query: build as any,
120 startSync: opts?.startSync ?? true,
121 gcTime: opts?.gcTime,
122 })
123 return { collection }
124}
125
126function makeErrorSource(kind: `fail` | `crash`) {
127 return makeSharedErrorSource(
128 createCollection,
129 `conformance-preact-err-${sourceSeq++}`,
130 kind,
131 )
132}
133
134function makeHandle(hook: MountedHook<any>): LiveQueryHandle {
135 return {
136 collection: () => hook.result.current?.collection ?? null,
137 current(): ConformanceResult {
138 const r: any = hook.result.current
139 return expectResultSurface({
140 data: r?.data,
141 state: r?.state,
142 status: r?.status,
143 isReady: r?.isReady,
144 isLoadingError: r?.isLoadingError,
145 isCrashed: r?.isCrashed,
146 isSyncError: r?.isSyncError,
147 // Read the hook's real `isEnabled` field so the suite catches a broken
148 // one (deriving from status would mask it).
149 isEnabled: r?.isEnabled,
150 health: r?.health,
151 })
152 },
153 flush: settle,
154 async apply(fn: () => void) {
155 await act(async () => {
156 fn()
157 await new Promise((resolve) => setTimeout(resolve, 0))
158 })
159 },
160 unmount() {
161 hook.unmount()
162 },
163 }
164}
165
166function mount(build: QueryBuild) {
167 return makeHandle(renderHook(() => useLiveQuery(build as any)))
168}
169
170function mountCollection(collection: any) {
171 return makeHandle(renderHook(() => useLiveQuery(collection)))
172}
173
174function mountConfig(
175 build: QueryBuild,
176 opts?: {
177 gcTime?: number
178 pool?: PooledLiveQueries
179 queryKey?: ReadonlyArray<unknown>
180 },
181) {
182 return makeHandle(
183 renderHook(() => useLiveQuery({ query: build as any, ...opts })),
184 )
185}
186
187function mountDisabled() {
188 // Preact's disabled convention: the query callback returns null.
189 return makeHandle(renderHook(() => useLiveQuery(() => null as any)))
190}
191
192function mountControllable<P>(
193 build: (q: any, param: P) => any,
194 initial: P,
195 opts?: { pool?: PooledLiveQueries },
196): ControllableHandle<P> {
197 const published = createPublicationLog()
198 const hook = renderHook(
199 ({ param }: { param: P }) =>
200 opts?.pool !== undefined
201 ? // The config form derives identity from the query on each render.
202 useLiveQuery({ query: (q: any) => build(q, param), pool: opts.pool })
203 : useLiveQuery((q: any) => build(q, param)),
204 {
205 initialProps: { param: initial },
206 onCommit: (result) => published.record(result.data, result.state),
207 },
208 )
209 const handle = makeHandle(hook)
210 return {
211 ...handle,
212 publications: published.values,
213 statePublications: published.stateValues,
214 async setParam(param: P) {
215 hook.rerender({ param })
216 await settle()
217 },
218 }
219}
220
221// The config-object form with a queryKey chosen per step; an undefined key
222// leaves the hook to derive the identity.
223function mountKeyedControllable<P>(
224 build: (q: any, param: P) => any,
225 key: (param: P) => ReadonlyArray<unknown> | undefined,
226 initial: P,
227): ControllableHandle<P> {
228 const published = createPublicationLog()
229 const hook = renderHook(
230 ({ param }: { param: P }) =>
231 useLiveQuery({
232 query: (q: any) => build(q, param),
233 queryKey: key(param),
234 } as any),
235 {
236 initialProps: { param: initial },
237 onCommit: (result) => published.record(result.data, result.state),
238 },
239 )
240 const handle = makeHandle(hook)
241 return {
242 ...handle,
243 publications: published.values,
244 statePublications: published.stateValues,
245 async setParam(param: P) {
246 hook.rerender({ param })
247 await settle()
248 },
249 }
250}
251
252const preactDriver: LiveQueryDriver = {
253 name: `preact`,
254 // Each render re-runs the query input and compares its identity.
255 comparesQueryIdentity: true,
256 disabledRepresentation: `absent`,
257 ops: { eq, gt, count, sum, coalesce, groupKeys, createOptimisticAction },
258 makeSource,
259 makeDeferredSource,
260 makeLaggingSource: <T extends { id: string }>() =>
261 makeLaggingSource<T>(
262 createCollection,
263 `conformance-preact-lagging-${sourceSeq++}`,
264 ),
265 makeSyncSource: <T extends { id: string }>(data: ReadonlyArray<T>) =>
266 makeSyncSource<T>(
267 createCollection,
268 `conformance-preact-health-${sourceSeq++}`,
269 data,
270 ),
271 makePrecreated,
272 makeErrorSource,
273 mount,
274 mountControllable,
275 mountKeyedControllable,
276 mountCollection,
277 mountConfig,
278 mountDisabled,
279 knownGaps: [],
280 features: { serverSnapshot: false, suspense: false, pooledEqFilters: true },
281}
282
283runSuite(preactDriver)