Open History to see the last commit
1import {
2 DeleteOperationItemNotFoundError,
3 DuplicateKeyInBatchError,
4 SyncNotInitializedError,
5 UpdateOperationItemNotFoundError,
6} from './errors'
7import type { QueryClient } from '@tanstack/query-core'
8import type {
9 ChangeMessage,
10 Collection,
11 SyncAppliedReceipt,
12} from '@tanstack/db'
13
14// Track active batch operations per context to prevent cross-collection contamination
15const activeBatchContexts = new WeakMap<
16 SyncContext<any, any>,
17 {
18 operations: Array<SyncOperation<any, any, any>>
19 isActive: boolean
20 }
21>()
22
23// Types for sync operations
24export type SyncOperation<
25 TRow extends object,
26 TKey extends string | number = string | number,
27 TInsertInput extends object = TRow,
28> =
29 | { type: `insert`; data: TInsertInput | Array<TInsertInput> }
30 | { type: `update`; data: Partial<TRow> | Array<Partial<TRow>> }
31 | { type: `delete`; key: TKey | Array<TKey> }
32 | { type: `upsert`; data: Partial<TRow> | Array<Partial<TRow>> }
33
34export interface SyncContext<
35 TRow extends object,
36 TKey extends string | number = string | number,
37> {
38 collection: Collection<TRow>
39 queryClient: QueryClient
40 queryKey: Array<unknown>
41 getKey: (item: TRow) => TKey
42 /**
43 * Begin a new sync transaction.
44 * @param options.immediate - When true, the transaction will be processed immediately
45 * even if there are persisting user transactions. Used by manual write operations.
46 */
47 begin: (options?: { immediate?: boolean }) => void
48 write: (message: Omit<ChangeMessage<TRow>, `key`>) => void
49 commit: () => SyncAppliedReceipt
50 /**
51 * Optional function to update the query cache with the latest synced data.
52 * Handles both direct array caches and wrapped response formats (when `select` is used).
53 * If not provided, falls back to directly setting the cache with the raw array.
54 */
55 updateCacheData?: (getItems: () => Array<TRow>) => void
56}
57
58interface NormalizedOperation<
59 TRow extends object,
60 TKey extends string | number = string | number,
61> {
62 type: `insert` | `update` | `delete` | `upsert`
63 key: TKey
64 data?: TRow | Partial<TRow>
65}
66
67// Normalize operations into a consistent format
68function normalizeOperations<
69 TRow extends object,
70 TKey extends string | number = string | number,
71 TInsertInput extends object = TRow,
72>(
73 ops:
74 | SyncOperation<TRow, TKey, TInsertInput>
75 | Array<SyncOperation<TRow, TKey, TInsertInput>>,
76 ctx: SyncContext<TRow, TKey>,
77): Array<NormalizedOperation<TRow, TKey>> {
78 const operations = Array.isArray(ops) ? ops : [ops]
79 const normalized: Array<NormalizedOperation<TRow, TKey>> = []
80
81 for (const op of operations) {
82 if (op.type === `delete`) {
83 const keys = Array.isArray(op.key) ? op.key : [op.key]
84 for (const key of keys) {
85 normalized.push({ type: `delete`, key })
86 }
87 } else {
88 const items = Array.isArray(op.data) ? op.data : [op.data]
89 for (const item of items) {
90 let key: TKey
91 if (op.type === `update`) {
92 // For updates, we need to get the key from the partial data
93 key = ctx.getKey(item as TRow)
94 } else {
95 // For insert/upsert, validate and resolve the full item first
96 const resolved = ctx.collection.validateData(
97 item,
98 op.type === `upsert` ? `insert` : op.type,
99 )
100 key = ctx.getKey(resolved)
101 }
102 normalized.push({ type: op.type, key, data: item })
103 }
104 }
105 }
106
107 return normalized
108}
109
110// Validate operations before executing
111function validateOperations<
112 TRow extends object,
113 TKey extends string | number = string | number,
114>(
115 operations: Array<NormalizedOperation<TRow, TKey>>,
116 ctx: SyncContext<TRow, TKey>,
117): void {
118 const seenKeys = new Set<TKey>()
119
120 for (const op of operations) {
121 // Check for duplicate keys within the batch
122 if (seenKeys.has(op.key)) {
123 throw new DuplicateKeyInBatchError(op.key)
124 }
125 seenKeys.add(op.key)
126
127 // Validate operation-specific requirements
128 // NOTE: These validations check the synced store only, not the combined view (synced + optimistic)
129 // This allows write operations to work correctly even when items are optimistically modified
130 if (op.type === `update`) {
131 if (!ctx.collection._state.syncedData.has(op.key)) {
132 throw new UpdateOperationItemNotFoundError(op.key)
133 }
134 } else if (op.type === `delete`) {
135 if (!ctx.collection._state.syncedData.has(op.key)) {
136 throw new DeleteOperationItemNotFoundError(op.key)
137 }
138 }
139 }
140}
141
142// Execute a batch of operations
143export function performWriteOperations<
144 TRow extends object,
145 TKey extends string | number = string | number,
146 TInsertInput extends object = TRow,
147>(
148 operations:
149 | SyncOperation<TRow, TKey, TInsertInput>
150 | Array<SyncOperation<TRow, TKey, TInsertInput>>,
151 ctx: SyncContext<TRow, TKey>,
152): void {
153 const normalized = normalizeOperations(operations, ctx)
154 validateOperations(normalized, ctx)
155
156 // Use immediate: true to ensure syncedData is updated synchronously,
157 // even when called from within a mutationFn with an active persisting transaction
158 ctx.begin({ immediate: true })
159
160 for (const op of normalized) {
161 switch (op.type) {
162 case `insert`: {
163 const resolved = ctx.collection.validateData(op.data, `insert`)
164 ctx.write({
165 type: `insert`,
166 value: resolved,
167 })
168 break
169 }
170 case `update`: {
171 // Get from synced store only, not the combined view
172 const currentItem = ctx.collection._state.syncedData.get(op.key)!
173 const updatedItem = {
174 ...currentItem,
175 ...op.data,
176 }
177 const resolved = ctx.collection.validateData(
178 updatedItem,
179 `update`,
180 op.key,
181 )
182 ctx.write({
183 type: `update`,
184 value: resolved,
185 })
186 break
187 }
188 case `delete`: {
189 // Get from synced store only, not the combined view
190 const currentItem = ctx.collection._state.syncedData.get(op.key)!
191 ctx.write({
192 type: `delete`,
193 value: currentItem,
194 })
195 break
196 }
197 case `upsert`: {
198 // Check synced store only, not the combined view
199 const existsInSyncedStore = ctx.collection._state.syncedData.has(op.key)
200 const resolved = ctx.collection.validateData(
201 op.data,
202 existsInSyncedStore ? `update` : `insert`,
203 op.key,
204 )
205 if (existsInSyncedStore) {
206 ctx.write({
207 type: `update`,
208 value: resolved,
209 })
210 } else {
211 ctx.write({
212 type: `insert`,
213 value: resolved,
214 })
215 }
216 break
217 }
218 }
219 }
220
221 ctx.commit()
222
223 // Update query cache after successful commit
224 if (ctx.updateCacheData) {
225 ctx.updateCacheData(() =>
226 Array.from(ctx.collection._state.syncedData.values()),
227 )
228 } else {
229 // Fallback: directly set the cache with raw array (for non-Query Collection consumers)
230 ctx.queryClient.setQueryData(
231 ctx.queryKey,
232 Array.from(ctx.collection._state.syncedData.values()),
233 )
234 }
235}
236
237// Factory function to create write utils
238export function createWriteUtils<
239 TRow extends object,
240 TKey extends string | number = string | number,
241 TInsertInput extends object = TRow,
242>(getContext: () => SyncContext<TRow, TKey> | null) {
243 function ensureContext(): SyncContext<TRow, TKey> {
244 const context = getContext()
245 if (!context) {
246 throw new SyncNotInitializedError()
247 }
248 return context
249 }
250
251 return {
252 writeInsert(data: TInsertInput | Array<TInsertInput>) {
253 const operation: SyncOperation<TRow, TKey, TInsertInput> = {
254 type: `insert`,
255 data,
256 }
257
258 const ctx = ensureContext()
259 const batchContext = activeBatchContexts.get(ctx)
260
261 // If we're in a batch, just add to the batch operations
262 if (batchContext?.isActive) {
263 batchContext.operations.push(operation)
264 return
265 }
266
267 // Otherwise, perform the operation immediately
268 performWriteOperations(operation, ctx)
269 },
270
271 writeUpdate(data: Partial<TRow> | Array<Partial<TRow>>) {
272 const operation: SyncOperation<TRow, TKey, TInsertInput> = {
273 type: `update`,
274 data,
275 }
276
277 const ctx = ensureContext()
278 const batchContext = activeBatchContexts.get(ctx)
279
280 if (batchContext?.isActive) {
281 batchContext.operations.push(operation)
282 return
283 }
284
285 performWriteOperations(operation, ctx)
286 },
287
288 writeDelete(key: TKey | Array<TKey>) {
289 const operation: SyncOperation<TRow, TKey, TInsertInput> = {
290 type: `delete`,
291 key,
292 }
293
294 const ctx = ensureContext()
295 const batchContext = activeBatchContexts.get(ctx)
296
297 if (batchContext?.isActive) {
298 batchContext.operations.push(operation)
299 return
300 }
301
302 performWriteOperations(operation, ctx)
303 },
304
305 writeUpsert(data: Partial<TRow> | Array<Partial<TRow>>) {
306 const operation: SyncOperation<TRow, TKey, TInsertInput> = {
307 type: `upsert`,
308 data,
309 }
310
311 const ctx = ensureContext()
312 const batchContext = activeBatchContexts.get(ctx)
313
314 if (batchContext?.isActive) {
315 batchContext.operations.push(operation)
316 return
317 }
318
319 performWriteOperations(operation, ctx)
320 },
321
322 writeBatch(callback: () => void) {
323 const ctx = ensureContext()
324
325 // Check if we're already in a batch (nested batch)
326 const existingBatch = activeBatchContexts.get(ctx)
327 if (existingBatch?.isActive) {
328 throw new Error(
329 `Cannot nest writeBatch calls. Complete the current batch before starting a new one.`,
330 )
331 }
332
333 // Set up the batch context for this specific collection
334 const batchContext = {
335 operations: [] as Array<SyncOperation<TRow, TKey, TInsertInput>>,
336 isActive: true,
337 }
338 activeBatchContexts.set(ctx, batchContext)
339
340 try {
341 // Execute the callback - any write operations will be collected
342 const result = callback()
343
344 // Check if callback returns a promise (async function)
345 if (
346 // @ts-expect-error - Runtime check for async callback, callback is typed as () => void but user might pass async
347 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
348 result &&
349 typeof result === `object` &&
350 `then` in result &&
351 // @ts-expect-error - Runtime check for async callback, callback is typed as () => void but user might pass async
352 typeof result.then === `function`
353 ) {
354 throw new Error(
355 `writeBatch does not support async callbacks. The callback must be synchronous.`,
356 )
357 }
358
359 // Perform all collected operations
360 if (batchContext.operations.length > 0) {
361 performWriteOperations(batchContext.operations, ctx)
362 }
363 } finally {
364 // Always clear the batch context
365 batchContext.isActive = false
366 activeBatchContexts.delete(ctx)
367 }
368 },
369 }
370}