Open History to see the last commit
1import { createCollection } from '@tanstack/db'
2import { startOfflineExecutor } from '../src/index'
3import type { ChangeMessage, Collection, PendingMutation } from '@tanstack/db'
4import type {
5 LeaderElection,
6 OfflineConfig,
7 OfflineMutationFnParams,
8 StorageAdapter,
9} from '../src/types'
10
11export class FakeStorageAdapter implements StorageAdapter {
12 private store = new Map<string, string>()
13
14 async get(key: string): Promise<string | null> {
15 return Promise.resolve(this.store.has(key) ? this.store.get(key)! : null)
16 }
17
18 async set(key: string, value: string): Promise<void> {
19 this.store.set(key, value)
20 return Promise.resolve()
21 }
22
23 async delete(key: string): Promise<void> {
24 this.store.delete(key)
25 return Promise.resolve()
26 }
27
28 async keys(): Promise<Array<string>> {
29 return Promise.resolve(Array.from(this.store.keys()))
30 }
31
32 async clear(): Promise<void> {
33 this.store.clear()
34 return Promise.resolve()
35 }
36
37 snapshot(): Record<string, string> {
38 return Object.fromEntries(this.store.entries())
39 }
40}
41
42export interface TestItem {
43 id: string
44 value: string
45 completed: boolean
46 updatedAt: Date
47}
48
49interface SyncController {
50 begin: () => void
51 write: (message: Omit<ChangeMessage<TestItem>, `key`>) => void
52 commit: () => void
53 markReady: () => void
54}
55
56class FakeLeaderElection implements LeaderElection {
57 private listeners = new Set<(isLeader: boolean) => void>()
58 private leader = true
59
60 // eslint-disable-next-line
61 async requestLeadership(): Promise<boolean> {
62 this.notify(this.leader)
63 return this.leader
64 }
65
66 releaseLeadership(): void {
67 this.leader = false
68 this.notify(false)
69 }
70
71 isLeader(): boolean {
72 return this.leader
73 }
74
75 onLeadershipChange(callback: (isLeader: boolean) => void): () => void {
76 this.listeners.add(callback)
77 // Don't call callback immediately - matches real BaseLeaderElection behavior
78 return () => {
79 this.listeners.delete(callback)
80 }
81 }
82
83 setLeader(isLeader: boolean): void {
84 this.leader = isLeader
85 this.notify(isLeader)
86 }
87
88 private notify(isLeader: boolean): void {
89 for (const listener of this.listeners) {
90 listener(isLeader)
91 }
92 }
93}
94
95type TestMutationFn = (
96 params: OfflineMutationFnParams & { attempt: number },
97) => unknown | Promise<unknown>
98
99interface TestOfflineEnvironmentOptions {
100 mutationFnName?: string
101 mutationFn?: TestMutationFn
102 storage?: FakeStorageAdapter
103 config?: Partial<OfflineConfig>
104}
105
106function createDefaultCollection(): {
107 collection: Collection<TestItem, string, {}>
108 controller: SyncController
109} {
110 let controller!: SyncController
111
112 const collection = createCollection<TestItem, string, {}>({
113 id: `test-items`,
114 getKey: (item) => item.id,
115 startSync: true,
116 sync: {
117 sync: (params) => {
118 controller = {
119 begin: params.begin,
120 write: params.write,
121 commit: params.commit,
122 markReady: params.markReady,
123 }
124 params.markReady()
125 },
126 },
127 })
128
129 return { collection, controller }
130}
131
132export function createTestOfflineEnvironment(
133 options: TestOfflineEnvironmentOptions = {},
134): {
135 executor: ReturnType<typeof startOfflineExecutor>
136 storage: FakeStorageAdapter
137 collection: Collection<TestItem, string, {}>
138 mutationFnName: string
139 mutationCalls: Array<OfflineMutationFnParams & { attempt: number }>
140 waitForLeader: () => Promise<void>
141 leader: FakeLeaderElection
142 serverState: Map<string, TestItem>
143 applyMutations: (mutations: ReadonlyArray<PendingMutation>) => void
144} {
145 const mutationFnName = options.mutationFnName ?? `syncData`
146 const storage = options.storage ?? new FakeStorageAdapter()
147 const mutationCalls: Array<OfflineMutationFnParams & { attempt: number }> = []
148 const attemptCounter = new Map<string, number>()
149
150 const { collection, controller } = createDefaultCollection()
151 const serverState = new Map<string, TestItem>()
152
153 const applyMutations = (mutations: ReadonlyArray<PendingMutation>) => {
154 controller.begin()
155
156 for (const mutation of mutations) {
157 switch (mutation.type) {
158 case `insert`:
159 case `update`: {
160 const value = requireTestItem(mutation.modified, mutation.globalKey)
161 serverState.set(value.id, value)
162 controller.write({ type: mutation.type, value })
163 break
164 }
165 case `delete`: {
166 const original = isTestItem(mutation.original)
167 ? mutation.original
168 : undefined
169 const fallbackIdFromKey =
170 (typeof mutation.key === `string` ? mutation.key : undefined) ??
171 mutation.globalKey.split(`:`).pop()
172 const id = original?.id ?? fallbackIdFromKey
173
174 if (!id) {
175 throw new Error(
176 `Unable to determine id for delete mutation ${mutation.globalKey}`,
177 )
178 }
179
180 const previousValue = serverState.get(id)
181 serverState.delete(id)
182
183 const emittedValue: TestItem = previousValue ?? {
184 id,
185 value: original?.value ?? ``,
186 completed: original?.completed ?? false,
187 updatedAt: original?.updatedAt ?? new Date(),
188 }
189
190 controller.write({
191 type: `delete`,
192 value: emittedValue,
193 })
194 break
195 }
196 }
197 }
198
199 controller.commit()
200 controller.markReady()
201 }
202
203 const defaultMutation: TestMutationFn = (params) => {
204 const mutations = params.transaction.mutations
205
206 applyMutations(mutations)
207
208 return { ok: true, mutations }
209 }
210
211 const mutationFn: TestMutationFn = options.mutationFn ?? defaultMutation
212
213 const leader = new FakeLeaderElection()
214
215 const wrappedMutation = async (
216 params: OfflineMutationFnParams,
217 ): Promise<unknown> => {
218 const currentAttempt = (attemptCounter.get(params.idempotencyKey) ?? 0) + 1
219 attemptCounter.set(params.idempotencyKey, currentAttempt)
220 const extendedParams = { ...params, attempt: currentAttempt }
221 mutationCalls.push(extendedParams)
222 return await mutationFn(extendedParams)
223 }
224
225 const config: OfflineConfig = {
226 ...options.config,
227 collections: {
228 ...(options.config?.collections ?? {}),
229 [collection.id]: collection,
230 },
231 mutationFns: {
232 ...(options.config?.mutationFns ?? {}),
233 [mutationFnName]: wrappedMutation,
234 },
235 storage,
236 leaderElection: options.config?.leaderElection ?? leader,
237 }
238
239 const executor = startOfflineExecutor(config)
240
241 const waitForLeader = async () => {
242 // Wait for full initialization including loading pending transactions
243 await executor.waitForInit()
244 if (!executor.isOfflineEnabled) {
245 throw new Error(`Executor did not become leader`)
246 }
247 }
248
249 return {
250 executor,
251 storage,
252 collection,
253 mutationFnName,
254 mutationCalls,
255 waitForLeader,
256 leader,
257 serverState,
258 applyMutations,
259 }
260}
261
262function isTestItem(value: unknown): value is TestItem {
263 return (
264 typeof value === `object` &&
265 value !== null &&
266 `id` in value &&
267 typeof value.id === `string` &&
268 `value` in value &&
269 typeof value.value === `string` &&
270 `completed` in value &&
271 typeof value.completed === `boolean` &&
272 `updatedAt` in value &&
273 value.updatedAt instanceof Date
274 )
275}
276
277function requireTestItem(value: unknown, mutationKey: string): TestItem {
278 if (!isTestItem(value)) {
279 throw new Error(`Invalid test item in mutation ${mutationKey}`)
280 }
281 return value
282}
283
284/** A promise that a test resolves to release one controlled step. */
285export function gate() {
286 let resolve!: () => void
287 const promise = new Promise<void>((done) => {
288 resolve = done
289 })
290 return { promise, resolve }
291}
292
293/** Yields one macrotask, after the microtasks that the step queued. */
294export const turn = () => new Promise<void>((resolve) => setTimeout(resolve, 0))