Open History to see the last commit
1import type { Collection } from '@tanstack/db'
2
3/**
4 * Wait for a condition to be true with timeout
5 */
6export async function waitFor(
7 condition: () => boolean | Promise<boolean>,
8 options: {
9 timeout?: number
10 interval?: number
11 message?: string
12 } = {},
13): Promise<void> {
14 const {
15 timeout = 5000,
16 interval = 50,
17 message = `Condition not met`,
18 } = options
19
20 const start = Date.now()
21 while (Date.now() - start < timeout) {
22 if (await condition()) {
23 return
24 }
25 await sleep(interval)
26 }
27
28 throw new Error(`${message} (timeout after ${timeout}ms)`)
29}
30
31/**
32 * Sleep for specified milliseconds
33 */
34export function sleep(ms: number): Promise<void> {
35 return new Promise((resolve) => setTimeout(resolve, ms))
36}
37
38/**
39 * Get all loaded item IDs from a collection
40 */
41export function getLoadedIds<T extends { id: string }>(
42 collection: Collection<T>,
43): Array<string> {
44 return Array.from(collection.state.values()).map((item) => item.id)
45}
46
47/**
48 * Get count of loaded items in a collection
49 */
50export function getLoadedCount<T extends object>(
51 collection: Collection<T>,
52): number {
53 return collection.size
54}
55
56/**
57 * Check if a collection has loaded specific IDs
58 */
59export function hasLoadedIds<T extends { id: string }>(
60 collection: Collection<T>,
61 ids: Array<string>,
62): boolean {
63 const loadedIds = getLoadedIds(collection)
64 return ids.every((id) => loadedIds.includes(id))
65}
66
67/**
68 * Check if a collection has ONLY loaded specific IDs (no extras)
69 */
70export function hasOnlyLoadedIds<T extends { id: string }>(
71 collection: Collection<T>,
72 ids: Array<string>,
73): boolean {
74 const loadedIds = getLoadedIds(collection)
75 const idsSet = new Set(ids)
76
77 // Check that all loaded IDs are in expected IDs
78 if (!loadedIds.every((id) => idsSet.has(id))) {
79 return false
80 }
81
82 // Check that all expected IDs are loaded
83 if (!ids.every((id) => loadedIds.includes(id))) {
84 return false
85 }
86
87 return true
88}
89
90/**
91 * Wait for a collection to reach a specific size
92 */
93export async function waitForCollectionSize<T extends object>(
94 collection: Collection<T>,
95 expectedSize: number,
96 timeout = 5000,
97): Promise<void> {
98 await waitFor(() => collection.size === expectedSize, {
99 timeout,
100 message: `Collection size did not reach ${expectedSize} (current: ${collection.size})`,
101 })
102}
103
104/**
105 * Wait for collection to finish loading (status === 'ready')
106 */
107export async function waitForCollectionReady<T extends object>(
108 collection: Collection<T>,
109 timeout = 5000,
110): Promise<void> {
111 await waitFor(() => collection.status === `ready`, {
112 timeout,
113 message: `Collection did not reach 'ready' status (current: ${collection.status})`,
114 })
115}
116
117/**
118 * Wait for a query to have data after preload.
119 * This is necessary for on-demand collections where Electric streams
120 * snapshot data asynchronously after loadSubset is triggered.
121 */
122export async function waitForQueryData<T extends object>(
123 query: Collection<T>,
124 options: {
125 minSize?: number
126 timeout?: number
127 } = {},
128): Promise<void> {
129 const { minSize = 1, timeout = 2000 } = options
130
131 await waitFor(() => query.size >= minSize, {
132 timeout,
133 interval: 10,
134 message: `Query did not load data (expected >= ${minSize}, got ${query.size})`,
135 })
136}
137
138/**
139 * Create a deduplication counter for testing
140 */
141export function createDeduplicationCounter() {
142 let actualLoads = 0
143 let deduplicatedLoads = 0
144
145 return {
146 onLoad: () => {
147 actualLoads++
148 },
149 onDeduplicate: () => {
150 deduplicatedLoads++
151 },
152 getActualLoads: () => actualLoads,
153 getDeduplicatedLoads: () => deduplicatedLoads,
154 getTotalAttempts: () => actualLoads + deduplicatedLoads,
155 reset: () => {
156 actualLoads = 0
157 deduplicatedLoads = 0
158 },
159 }
160}
161
162/**
163 * Sort array of objects by a field
164 */
165export function sortBy<T, K extends keyof T>(
166 array: Array<T>,
167 field: K,
168 direction: `asc` | `desc` = `asc`,
169): Array<T> {
170 return [...array].sort((a, b) => {
171 const aVal = a[field]
172 const bVal = b[field]
173
174 if (aVal < bVal) return direction === `asc` ? -1 : 1
175 if (aVal > bVal) return direction === `asc` ? 1 : -1
176 return 0
177 })
178}
179
180/**
181 * Filter array by predicate function
182 */
183export function filterBy<T>(
184 array: Array<T>,
185 predicate: (item: T) => boolean,
186): Array<T> {
187 return array.filter(predicate)
188}
189
190/**
191 * Paginate array
192 */
193export function paginate<T>(
194 array: Array<T>,
195 options: { limit?: number; offset?: number } = {},
196): Array<T> {
197 const { limit, offset = 0 } = options
198
199 let result = array.slice(offset)
200
201 if (limit !== undefined) {
202 result = result.slice(0, limit)
203 }
204
205 return result
206}