Open History to see the last commit
1import { describe, expectTypeOf, it } from 'vitest'
2import { z } from 'zod'
3import {
4 and,
5 createCollection,
6 createLiveQueryCollection,
7 eq,
8 gt,
9} from '@tanstack/db'
10import { electricCollectionOptions } from '../src/electric'
11import type {
12 AwaitTxIdFn,
13 ElectricCollectionConfig,
14 ElectricCollectionUtils,
15} from '../src/electric'
16import type {
17 DeleteMutationFnParams,
18 InsertMutationFnParams,
19 UpdateMutationFnParams,
20} from '@tanstack/db'
21import type { OutputWithVirtual } from '../../db/tests/utils'
22
23describe(`Electric collection type resolution tests`, () => {
24 // Define test types
25 type ExplicitType = { id: string; explicit: boolean }
26 type FallbackType = { id: string; fallback: boolean }
27
28 // Define a schema
29 const testSchema = z.object({
30 id: z.string(),
31 schema: z.boolean(),
32 })
33
34 type SchemaType = z.infer<typeof testSchema>
35
36 it(`should prioritize explicit type in ElectricCollectionConfig`, () => {
37 const options = electricCollectionOptions<ExplicitType>({
38 shapeOptions: {
39 url: `foo`,
40 params: { table: `test_table` },
41 },
42 getKey: (item) => item.id,
43 })
44
45 // The getKey function should have the resolved type
46 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExplicitType]>()
47 })
48
49 it(`should use schema type when a schema is provided`, () => {
50 const options = electricCollectionOptions({
51 shapeOptions: {
52 url: `foo`,
53 params: { table: `test_table` },
54 },
55 schema: testSchema,
56 getKey: (item) => item.id,
57 })
58
59 // The getKey function should have the resolved type
60 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[SchemaType]>()
61 })
62
63 it(`should throw a type error when both a schema and an explicit type (that is not the type of the schema) are provided`, () => {
64 electricCollectionOptions<ExplicitType>({
65 shapeOptions: {
66 url: `foo`,
67 params: { table: `test_table` },
68 },
69 // @ts-expect-error – schema should be `undefined` because we passed an explicit type
70 schema: testSchema,
71 getKey: (item) => item.id,
72 })
73 })
74
75 it(`should use explicit type when no schema is provided`, () => {
76 const config: ElectricCollectionConfig<FallbackType> = {
77 shapeOptions: {
78 url: `foo`,
79 params: { table: `test_table` },
80 },
81 getKey: (item) => item.id,
82 }
83
84 const options = electricCollectionOptions(config)
85
86 // The getKey function should have the resolved type
87 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[FallbackType]>()
88 })
89
90 it(`should use getKey type when no schema and no explicit type is provided`, () => {
91 const config = {
92 shapeOptions: {
93 url: `foo`,
94 params: { table: `test_table` },
95 },
96 getKey: (item: FallbackType) => item.id,
97 }
98
99 const options = electricCollectionOptions(config)
100
101 // The getKey function should have the resolved type
102 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[FallbackType]>()
103 })
104
105 it(`should type collection.utils as ElectricCollectionUtils<T>`, () => {
106 const todoSchema = z.object({
107 id: z.string(),
108 title: z.string(),
109 completed: z.boolean(),
110 })
111
112 type TodoType = z.infer<typeof todoSchema>
113
114 const options = electricCollectionOptions({
115 id: `todos`,
116 getKey: (item) => item.id,
117 shapeOptions: {
118 url: `/api/todos`,
119 params: { table: `todos` },
120 },
121 schema: todoSchema,
122 onInsert: async ({ collection }) => {
123 const testCollectionUtils: ElectricCollectionUtils<TodoType> =
124 collection.utils
125 expectTypeOf(testCollectionUtils.awaitTxId).toBeFunction
126 expectTypeOf(collection.utils.awaitTxId).toBeFunction
127 return Promise.resolve({ txid: 1 })
128 },
129 onUpdate: async ({ collection }) => {
130 const testCollectionUtils: ElectricCollectionUtils<TodoType> =
131 collection.utils
132 expectTypeOf(testCollectionUtils.awaitTxId).toBeFunction
133 expectTypeOf(collection.utils.awaitTxId).toBeFunction
134 return Promise.resolve({ txid: 1 })
135 },
136 onDelete: async ({ collection }) => {
137 const testCollectionUtils: ElectricCollectionUtils<TodoType> =
138 collection.utils
139 expectTypeOf(testCollectionUtils.awaitTxId).toBeFunction
140 expectTypeOf(collection.utils.awaitTxId).toBeFunction
141 return Promise.resolve({ txid: 1 })
142 },
143 })
144
145 // Test that options.utils is typed as ElectricCollectionUtils<TodoType>
146 // The options object should have the correct type from electricCollectionOptions
147 const testOptionsUtils: ElectricCollectionUtils<TodoType> = options.utils
148
149 expectTypeOf(testOptionsUtils.awaitTxId).toBeFunction
150
151 const todosCollection = createCollection(options)
152
153 expectTypeOf(todosCollection.utils).toEqualTypeOf<
154 ElectricCollectionUtils<TodoType>
155 >()
156
157 // Verify the specific properties that define ElectricCollectionUtils exist and are functions
158 expectTypeOf(todosCollection.utils.awaitTxId).toBeFunction
159 expectTypeOf(todosCollection.utils.awaitMatch).toBeFunction
160 })
161
162 it(`should preserve ElectricCollectionUtils type on collection.utils after createCollection with handlers`, () => {
163 const todoSchema = z.object({
164 id: z.string(),
165 title: z.string(),
166 completed: z.boolean(),
167 })
168
169 type TodoType = z.infer<typeof todoSchema>
170
171 const options = electricCollectionOptions({
172 shapeOptions: {
173 url: `/api/todos`,
174 },
175 schema: todoSchema,
176 getKey: (item) => item.id,
177 onInsert: async () => {
178 return Promise.resolve({ txid: 1 })
179 },
180 onUpdate: async () => {
181 return Promise.resolve({ txid: 1 })
182 },
183 onDelete: async () => {
184 return Promise.resolve({ txid: 1 })
185 },
186 })
187
188 const todosCollection = createCollection(options)
189
190 // After createCollection, utils should be typed as ElectricCollectionUtils<TodoType>
191 // and not widened to UtilsRecord
192 const testUtils: ElectricCollectionUtils<TodoType> = todosCollection.utils
193
194 expectTypeOf(testUtils.awaitTxId).toBeFunction
195 expectTypeOf(testUtils.awaitMatch).toBeFunction
196 expectTypeOf(todosCollection.utils.awaitTxId).toBeFunction
197 expectTypeOf(todosCollection.utils.awaitMatch).toBeFunction
198 })
199
200 it(`should properly type the onInsert, onUpdate, and onDelete handlers`, () => {
201 const options = electricCollectionOptions<ExplicitType>({
202 shapeOptions: {
203 url: `test_shape`,
204 params: { table: `test_table` },
205 },
206 getKey: (item) => item.id,
207 onInsert: (params) => {
208 // Verify that the mutation value has the correct type
209 expectTypeOf(
210 params.transaction.mutations[0].modified,
211 ).toEqualTypeOf<ExplicitType>()
212 expectTypeOf(params.transaction.mutations[0].key).toEqualTypeOf<
213 string | number
214 >()
215 expectTypeOf(
216 params.transaction.mutations[0].collection.utils.awaitTxId,
217 ).toEqualTypeOf<AwaitTxIdFn>()
218 // @ts-expect-error Electric Collection does not expose Query refetch utilities
219 params.transaction.mutations[0].collection.utils.refetch()
220 return Promise.resolve({ txid: 1 })
221 },
222 onUpdate: (params) => {
223 // Verify that the mutation value has the correct type
224 expectTypeOf(
225 params.transaction.mutations[0].modified,
226 ).toEqualTypeOf<ExplicitType>()
227 expectTypeOf(params.transaction.mutations[0].key).toEqualTypeOf<
228 string | number
229 >()
230 expectTypeOf(
231 params.transaction.mutations[0].collection.utils.awaitTxId,
232 ).toEqualTypeOf<AwaitTxIdFn>()
233 return Promise.resolve({ txid: 1 })
234 },
235 onDelete: (params) => {
236 // Verify that the mutation value has the correct type
237 expectTypeOf(
238 params.transaction.mutations[0].original,
239 ).toEqualTypeOf<ExplicitType>()
240 expectTypeOf(params.transaction.mutations[0].key).toEqualTypeOf<
241 string | number
242 >()
243 expectTypeOf(
244 params.transaction.mutations[0].collection.utils.awaitTxId,
245 ).toEqualTypeOf<AwaitTxIdFn>()
246 return Promise.resolve({ txid: 1 })
247 },
248 })
249
250 // Verify that the handlers are properly typed with ElectricCollectionUtils
251 expectTypeOf(options.onInsert).parameters.toEqualTypeOf<
252 [
253 InsertMutationFnParams<
254 ExplicitType,
255 string | number,
256 ElectricCollectionUtils<ExplicitType>
257 >,
258 ]
259 >()
260
261 expectTypeOf(options.onUpdate).parameters.toEqualTypeOf<
262 [
263 UpdateMutationFnParams<
264 ExplicitType,
265 string | number,
266 ElectricCollectionUtils<ExplicitType>
267 >,
268 ]
269 >()
270
271 expectTypeOf(options.onDelete).parameters.toEqualTypeOf<
272 [
273 DeleteMutationFnParams<
274 ExplicitType,
275 string | number,
276 ElectricCollectionUtils<ExplicitType>
277 >,
278 ]
279 >()
280 })
281
282 it(`should correctly type mutations in transaction handlers when mapping over mutations array`, () => {
283 const schema = z.object({
284 id: z.string(),
285 title: z.string(),
286 completed: z.boolean(),
287 })
288
289 type TodoType = z.infer<typeof schema>
290
291 const options = electricCollectionOptions({
292 id: `todos`,
293 schema,
294 getKey: (item) => item.id,
295 shapeOptions: {
296 url: `/api/todos`,
297 params: { table: `todos` },
298 },
299 onDelete: (params) => {
300 // Direct index access should be correctly typed
301 expectTypeOf(
302 params.transaction.mutations[0].original,
303 ).toEqualTypeOf<TodoType>()
304
305 // Non-null assertion on second element should be correctly typed
306 expectTypeOf(
307 params.transaction.mutations[1]!.original,
308 ).toEqualTypeOf<TodoType>()
309
310 // When mapping over mutations, each mutation.original should be correctly typed
311 params.transaction.mutations.map((mutation) => {
312 expectTypeOf(mutation.original).toEqualTypeOf<TodoType>()
313 return mutation.original.id
314 })
315
316 return Promise.resolve({ txid: 1 })
317 },
318 onInsert: (params) => {
319 // Direct index access should be correctly typed
320 expectTypeOf(
321 params.transaction.mutations[0].modified,
322 ).toEqualTypeOf<TodoType>()
323
324 // When mapping over mutations, each mutation.modified should be correctly typed
325 params.transaction.mutations.map((mutation) => {
326 expectTypeOf(mutation.modified).toEqualTypeOf<TodoType>()
327 return mutation.modified.id
328 })
329
330 return Promise.resolve({ txid: 1 })
331 },
332 onUpdate: (params) => {
333 // Direct index access should be correctly typed
334 expectTypeOf(
335 params.transaction.mutations[0].original,
336 ).toEqualTypeOf<TodoType>()
337 expectTypeOf(
338 params.transaction.mutations[0].modified,
339 ).toEqualTypeOf<TodoType>()
340
341 // When mapping over mutations, each mutation should be correctly typed
342 params.transaction.mutations.map((mutation) => {
343 expectTypeOf(mutation.original).toEqualTypeOf<TodoType>()
344 expectTypeOf(mutation.modified).toEqualTypeOf<TodoType>()
345 return mutation.modified.id
346 })
347
348 return Promise.resolve({ txid: 1 })
349 },
350 })
351
352 // Verify that the handlers are properly typed with ElectricCollectionUtils
353 expectTypeOf(options.onDelete).parameters.toEqualTypeOf<
354 [
355 DeleteMutationFnParams<
356 TodoType,
357 string | number,
358 ElectricCollectionUtils<TodoType>
359 >,
360 ]
361 >()
362 expectTypeOf(options.onInsert).parameters.toEqualTypeOf<
363 [
364 InsertMutationFnParams<
365 TodoType,
366 string | number,
367 ElectricCollectionUtils<TodoType>
368 >,
369 ]
370 >()
371 expectTypeOf(options.onUpdate).parameters.toEqualTypeOf<
372 [
373 UpdateMutationFnParams<
374 TodoType,
375 string | number,
376 ElectricCollectionUtils<TodoType>
377 >,
378 ]
379 >()
380 })
381
382 it(`should infer types from Zod schema through electric collection options to live query`, () => {
383 // Define a Zod schema for a user with basic field types
384 const userSchema = z.object({
385 id: z.string(),
386 name: z.string(),
387 age: z.number(),
388 email: z.string().email(),
389 active: z.boolean(),
390 })
391
392 type UserType = z.infer<typeof userSchema>
393
394 // Create electric collection options with the schema
395 const electricOptions = electricCollectionOptions({
396 shapeOptions: {
397 url: `test_shape`,
398 params: { table: `users` },
399 },
400 schema: userSchema,
401 getKey: (item) => item.id,
402 })
403
404 // Create a collection using the electric options
405 const usersCollection = createCollection(electricOptions)
406
407 // Create a live query collection that uses the users collection
408 const activeUsersQuery = createLiveQueryCollection({
409 query: (q) =>
410 q
411 .from({ user: usersCollection })
412 .where(({ user }) => eq(user.active, true))
413 .select(({ user }) => ({
414 id: user.id,
415 name: user.name,
416 age: user.age,
417 email: user.email,
418 isActive: user.active,
419 })),
420 })
421
422 // Test that the query results have the correct inferred types
423 const results = activeUsersQuery.toArray
424 expectTypeOf(results).toMatchTypeOf<
425 Array<
426 OutputWithVirtual<{
427 id: string
428 name: string
429 age: number
430 email: string
431 isActive: boolean
432 }>
433 >
434 >()
435
436 // Test that the collection itself has the correct type
437 expectTypeOf(usersCollection.toArray).toMatchTypeOf<
438 Array<OutputWithVirtual<UserType>>
439 >()
440
441 // Test that we can access schema-inferred fields in the query with WHERE conditions
442 const ageFilterQuery = createLiveQueryCollection({
443 query: (q) =>
444 q
445 .from({ user: usersCollection })
446 .where(({ user }) => and(eq(user.active, true), gt(user.age, 18)))
447 .select(({ user }) => ({
448 id: user.id,
449 name: user.name,
450 age: user.age,
451 })),
452 })
453
454 const ageFilterResults = ageFilterQuery.toArray
455 expectTypeOf(ageFilterResults).toMatchTypeOf<
456 Array<
457 OutputWithVirtual<{
458 id: string
459 name: string
460 age: number
461 }>
462 >
463 >()
464
465 // Test that the getKey function has the correct parameter type
466 expectTypeOf(electricOptions.getKey).parameters.toEqualTypeOf<[UserType]>()
467 })
468
469 it(`should demonstrate the difference between electric options and direct createCollection with schema`, () => {
470 // Define a Zod schema with basic fields
471 const userSchema = z.object({
472 id: z.string(),
473 name: z.string(),
474 age: z.number(),
475 email: z.string().email(),
476 active: z.boolean(),
477 })
478
479 type UserType = z.infer<typeof userSchema>
480
481 // Method 1: Using electric collection options (WORKS)
482 const electricOptions = electricCollectionOptions({
483 shapeOptions: {
484 url: `test_shape`,
485 params: { table: `users` },
486 },
487 schema: userSchema,
488 getKey: (item) => item.id,
489 })
490
491 const electricCollection = createCollection(electricOptions)
492
493 // Method 2: Using direct createCollection with schema (FAILS with never types)
494 const directCollection = createCollection({
495 id: `test-direct`,
496 schema: userSchema,
497 getKey: (item) => item.id,
498 sync: {
499 sync: ({ begin, commit, markReady }) => {
500 begin()
501 commit()
502 markReady()
503 },
504 },
505 })
506
507 // Test that electric collection works correctly
508 const electricQuery = createLiveQueryCollection({
509 query: (q) =>
510 q.from({ user: electricCollection }).select(({ user }) => ({
511 id: user.id,
512 name: user.name,
513 age: user.age,
514 })),
515 })
516
517 expectTypeOf(electricCollection.utils).toEqualTypeOf<
518 ElectricCollectionUtils<UserType>
519 >()
520
521 const electricResults = electricQuery.toArray
522 expectTypeOf(electricResults).toMatchTypeOf<
523 Array<
524 OutputWithVirtual<{
525 id: string
526 name: string
527 age: number
528 }>
529 >
530 >()
531
532 // Test that direct collection has the correct type
533 expectTypeOf(directCollection.toArray).toMatchTypeOf<
534 Array<OutputWithVirtual<UserType>>
535 >()
536
537 // The key insight: electric collection options properly resolve schema types
538 // while direct createCollection with schema doesn't work in query builder
539 expectTypeOf(electricOptions.getKey).parameters.toEqualTypeOf<[UserType]>()
540 })
541})