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) => Promise<any>
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: Array<PendingMutation<TestItem>>) => 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: Array<PendingMutation<TestItem>>) => {
154 controller.begin()
155
156 for (const mutation of mutations) {
157 switch (mutation.type) {
158 case `insert`: {
159 const value = mutation.modified
160 serverState.set(value.id, value)
161 controller.write({ type: `insert`, value })
162 break
163 }
164 case `update`: {
165 const value = mutation.modified
166 serverState.set(value.id, value)
167 controller.write({ type: `update`, value })
168 break
169 }
170 case `delete`: {
171 const original = mutation.original as TestItem | undefined
172 const fallbackIdFromKey =
173 (typeof mutation.key === `string` ? mutation.key : undefined) ??
174 mutation.globalKey.split(`:`).pop()
175 const id = original?.id ?? fallbackIdFromKey
176
177 if (!id) {
178 throw new Error(
179 `Unable to determine id for delete mutation ${mutation.globalKey}`,
180 )
181 }
182
183 const previousValue = serverState.get(id)
184 serverState.delete(id)
185
186 const emittedValue: TestItem = previousValue ?? {
187 id,
188 value: original?.value ?? ``,
189 completed: original?.completed ?? false,
190 updatedAt: original?.updatedAt ?? new Date(),
191 }
192
193 controller.write({
194 type: `delete`,
195 value: emittedValue,
196 })
197 break
198 }
199 }
200 }
201
202 controller.commit()
203 controller.markReady()
204 }
205
206 const defaultMutation: TestMutationFn = (params) => {
207 const mutations = params.transaction.mutations as Array<
208 PendingMutation<TestItem>
209 >
210
211 applyMutations(mutations)
212
213 return { ok: true, mutations }
214 }
215
216 const mutationFn: TestMutationFn = options.mutationFn ?? defaultMutation
217
218 const leader = new FakeLeaderElection()
219
220 const wrappedMutation = async (
221 params: OfflineMutationFnParams,
222 ): Promise<any> => {
223 const currentAttempt = (attemptCounter.get(params.idempotencyKey) ?? 0) + 1
224 attemptCounter.set(params.idempotencyKey, currentAttempt)
225 const extendedParams = { ...params, attempt: currentAttempt }
226 mutationCalls.push(extendedParams)
227 return mutationFn(extendedParams)
228 }
229
230 const config: OfflineConfig = {
231 ...options.config,
232 collections: {
233 ...(options.config?.collections ?? {}),
234 [collection.id]: collection,
235 },
236 mutationFns: {
237 ...(options.config?.mutationFns ?? {}),
238 [mutationFnName]: wrappedMutation,
239 },
240 storage,
241 leaderElection: options.config?.leaderElection ?? leader,
242 }
243
244 const executor = startOfflineExecutor(config)
245
246 const waitForLeader = async () => {
247 // Wait for full initialization including loading pending transactions
248 await executor.waitForInit()
249 if (!executor.isOfflineEnabled) {
250 throw new Error(`Executor did not become leader`)
251 }
252 }
253
254 return {
255 executor,
256 storage,
257 collection,
258 mutationFnName,
259 mutationCalls,
260 waitForLeader,
261 leader,
262 serverState,
263 applyMutations,
264 }
265}