Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

TransactionSerializer.ts

403 lines11.6 KB

1import type {
2 OfflineTransaction,
3 SerializedError,
4 SerializedMutation,
5 SerializedOfflineTransaction,
6} from '../types'
7import type { Collection, PendingMutation } from '@tanstack/db'
8​
9const temporalConstructorNames = [
10 `Duration`,
11 `Instant`,
12 `PlainDate`,
13 `PlainDateTime`,
14 `PlainMonthDay`,
15 `PlainTime`,
16 `PlainYearMonth`,
17 `ZonedDateTime`,
18] as const
19​
20type TemporalConstructorName = (typeof temporalConstructorNames)[number]
21type TemporalConstructor = {
22 from: (value: string) => unknown
23 prototype?: { toString?: () => string }
25​
26function getTemporalConstructorName(
27 type: unknown,
28): TemporalConstructorName | undefined {
29 if (typeof type !== `string` || !type.startsWith(`Temporal.`)) return
30 const constructorName = type.slice(
31 `Temporal.`.length,
32 ) as TemporalConstructorName
33 return temporalConstructorNames.includes(constructorName)
34 ? constructorName
35 : undefined
37​
38function requireTemporalConstructor(
39 name: TemporalConstructorName,
40): TemporalConstructor {
41 const constructor = (
42 globalThis as {
43 Temporal?: Partial<Record<TemporalConstructorName, TemporalConstructor>>
44 }
45 ).Temporal?.[name]
46 if (typeof constructor?.from !== `function`)
47 throw new MissingTemporalConstructorError(
48 `Missing global Temporal.${name} constructor`,
49 )
50 return constructor
52​
53function serializeTemporalValue(
54 value: object,
55 name: TemporalConstructorName,
56): string | undefined {
57 const constructor = requireTemporalConstructor(name)
58 const toString = constructor.prototype?.toString
59 if (typeof toString !== `function` || toString === Object.prototype.toString)
60 return
61 try {
62 const serialized = toString.call(value)
63 return typeof serialized === `string` ? serialized : undefined
64 } catch {
65 // Temporal prototype methods brand-check their receiver. A matching
66 // Symbol.toStringTag without the corresponding internal slots is user data.
67 return
68 }
70​
71function mayBeNativeScalar(value: object): boolean {
72 const prototype = Object.getPrototypeOf(value)
73 return (
74 prototype !== null &&
75 prototype !== Object.prototype &&
76 !Array.isArray(value)
77 )
79​
80export class MissingTemporalConstructorError extends Error {}
81​
82function setDataProperty(
83 object: Record<string, unknown>,
84 key: string,
85 value: unknown,
86): void {
87 if (key !== `__proto__`) object[key] = value
88 else
89 Object.defineProperty(object, key, {
90 value,
91 enumerable: true,
92 configurable: true,
93 writable: true,
94 })
96​
97function assertOutboxPhase(
98 phase: unknown,
99): asserts phase is `deletion-pending` | `rejection-pending` | undefined {
100 if (
101 phase !== undefined &&
102 phase !== `deletion-pending` &&
103 phase !== `rejection-pending`
104 )
105 throw new Error(`Unsupported transaction outbox phase`)
107​
108export class TransactionSerializer {
109 private collections: Record<string, Collection<any, any, any, any, any>>
110 private collectionIdToKey: Map<string, string>
111​
112 constructor(
113 collections: Record<string, Collection<any, any, any, any, any>>,
114 ) {
115 this.collections = collections
116 // Create reverse lookup from collection.id to registry key
117 this.collectionIdToKey = new Map()
118 for (const [key, collection] of Object.entries(collections)) {
119 this.collectionIdToKey.set(collection.id, key)
120 }
121 }
122​
123 serialize(transaction: OfflineTransaction): string {
124 assertOutboxPhase(transaction.outboxPhase)
125 const serialized: SerializedOfflineTransaction = {
126 ...transaction,
127 valueEncoding: 3,
128 createdAt: transaction.createdAt.toISOString(),
129 metadata: this.serializeValue(transaction.metadata, `metadata`),
130 mutations: transaction.mutations.map((mutation) =>
131 this.serializeMutation(mutation),
132 ),
133 }
134 return JSON.stringify(serialized)
135 }
136​
137 deserialize(data: string): OfflineTransaction {
138 // Old records retain their Date-marker meaning. New records also escape
139 // marker-shaped user objects; the encoding tag is not application metadata.
140 const {
141 valueEncoding,
142 outboxPhase,
143 ...parsed
144 }: Omit<SerializedOfflineTransaction, `valueEncoding` | `outboxPhase`> & {
145 valueEncoding?: unknown
146 outboxPhase?: unknown
147 } = JSON.parse(data)
148 if (
149 valueEncoding !== undefined &&
150 valueEncoding !== 2 &&
151 valueEncoding !== 3
152 ) {
153 throw new Error(
154 `Unsupported transaction value encoding: ${valueEncoding}`,
155 )
156 }
157 assertOutboxPhase(outboxPhase)
158​
159 const createdAt = new Date(parsed.createdAt)
160 if (isNaN(createdAt.getTime())) {
161 throw new Error(
162 `Failed to deserialize transaction: invalid createdAt value "${parsed.createdAt}"`,
163 )
164 }
165​
166 return {
167 ...parsed,
168 ...(outboxPhase === undefined ? {} : { outboxPhase }),
169 createdAt,
170 metadata:
171 valueEncoding === 3
172 ? this.deserializeValue(parsed.metadata, valueEncoding)
173 : parsed.metadata,
174 mutations: parsed.mutations.map((mutationData) =>
175 this.deserializeMutation(mutationData, valueEncoding),
176 ),
177 }
178 }
179​
180 private serializeMutation(mutation: PendingMutation): SerializedMutation {
181 const registryKey = this.collectionIdToKey.get(mutation.collection.id)
182 if (!registryKey) {
183 throw new Error(
184 `Collection with id ${mutation.collection.id} not found in registry`,
185 )
186 }
187​
188 return {
189 globalKey: mutation.globalKey,
190 type: mutation.type,
191 modified: this.serializeValue(mutation.modified),
192 original: this.serializeValue(mutation.original),
193 changes: this.serializeValue(mutation.changes),
194 collectionId: registryKey, // Store registry key instead of collection.id
195 }
196 }
197​
198 private deserializeMutation(
199 data: SerializedMutation,
200 valueEncoding: 2 | 3 | undefined,
201 ): PendingMutation {
202 const collection = this.collections[data.collectionId]
203 if (!collection) {
204 throw new Error(`Collection with id ${data.collectionId} not found`)
205 }
206​
207 const modified = this.deserializeValue(data.modified, valueEncoding)
208​
209 // Extract the key from the modified data using the collection's getKey function
210 // This is needed for optimistic state restoration to work correctly
211 const key = modified ? collection.getKeyFromItem(modified) : null
212​
213 // Create a partial PendingMutation - we can't fully reconstruct it but
214 // we provide what we can. The executor will need to handle the rest.
215 return {
216 globalKey: data.globalKey,
217 type: data.type as any,
218 modified,
219 original: this.deserializeValue(data.original, valueEncoding),
220 changes: this.deserializeValue(data.changes, valueEncoding) ?? {},
221 collection,
222 // These fields would need to be reconstructed by the executor
223 mutationId: ``, // Will be regenerated
224 key,
225 metadata: undefined,
226 syncMetadata: {},
227 optimistic: true,
228 createdAt: new Date(),
229 updatedAt: new Date(),
230 } as PendingMutation
231 }
232​
233 private serializeValue(
234 value: any,
235 jsonKey?: string | false,
236 ancestors = new WeakSet<object>(),
237 ): any {
238 if (value === null || typeof value !== `object`) return value
239​
240 if (jsonKey !== false && value instanceof Date) {
241 return { __type: `Date`, value: value.toISOString() }
242 }
243​
244 const temporalConstructorName =
245 jsonKey !== false && mayBeNativeScalar(value)
246 ? getTemporalConstructorName(value[Symbol.toStringTag])
247 : undefined
248 if (temporalConstructorName) {
249 const temporalValue = serializeTemporalValue(
250 value,
251 temporalConstructorName,
252 )
253 if (temporalValue !== undefined)
254 return {
255 __type: `Temporal`,
256 type: `Temporal.${temporalConstructorName}`,
257 value: temporalValue,
258 }
259 }
260​
261 if (ancestors.has(value))
262 throw new TypeError(`Converting circular structure to JSON`)
263​
264 const toJSON = typeof jsonKey === `string` && value.toJSON
265 if (typeof toJSON === `function`) {
266 const replacement = toJSON.call(value, jsonKey)
267 if (replacement === value) {
268 return this.serializeValue(replacement, false, ancestors)
269 }
270​
271 ancestors.add(value)
272 try {
273 return this.serializeValue(replacement, false, ancestors)
274 } finally {
275 ancestors.delete(value)
276 }
277 }
278 if (
279 jsonKey !== undefined &&
280 (value instanceof Boolean ||
281 value instanceof BigInt ||
282 value instanceof Number ||
283 value instanceof String)
284 ) {
285 return value.valueOf()
286 }
287​
288 ancestors.add(value)
289​
290 const isArray = Array.isArray(value)
291 const result: any = isArray ? [] : {}
292 try {
293 if (isArray) {
294 const length = value.length
295 for (let index = 0; index < length; index++) {
296 const key = String(index)
297 setDataProperty(
298 result,
299 key,
300 this.serializeValue(
301 value[index],
302 jsonKey === undefined ? undefined : key,
303 ancestors,
304 ),
305 )
306 }
307 } else {
308 for (const key of Object.keys(value)) {
309 setDataProperty(
310 result,
311 key,
312 this.serializeValue(
313 value[key],
314 jsonKey === undefined ? undefined : key,
315 ancestors,
316 ),
317 )
318 }
319 }
320 } finally {
321 ancestors.delete(value)
322 }
323 if (jsonKey === false && typeof result.toJSON === `function`)
324 delete result.toJSON
325 return !isArray && Object.prototype.hasOwnProperty.call(value, `__type`)
326 ? { __type: `Object`, value: result }
327 : result
328 }
329​
330 private deserializeValue(value: any, valueEncoding: 2 | 3 | undefined): any {
331 if (value === null || value === undefined) {
332 return value
333 }
334​
335 if (typeof value === `object` && value.__type === `Date`) {
336 if (value.value === undefined || value.value === null) {
337 throw new Error(`Corrupted Date marker: missing value field`)
338 }
339 const date = new Date(value.value)
340 if (isNaN(date.getTime())) {
341 throw new Error(
342 `Failed to deserialize Date marker: invalid date value "${value.value}"`,
343 )
344 }
345 return date
346 }
347​
348 if (
349 valueEncoding === 3 &&
350 typeof value === `object` &&
351 value.__type === `Temporal`
352 ) {
353 const constructorName = getTemporalConstructorName(value.type)
354 if (!constructorName)
355 throw new Error(`Corrupted Temporal marker: invalid type field`)
356 if (typeof value.value !== `string`)
357 throw new Error(`Corrupted Temporal marker: missing value field`)
358 return requireTemporalConstructor(constructorName).from(value.value)
359 }
360​
361 if (typeof value === `object`) {
362 // Unwrap once, then decode only the fields: the object's own __type is data.
363 if (valueEncoding !== undefined && value.__type === `Object`) {
364 if (
365 value.value === null ||
366 typeof value.value !== `object` ||
367 Array.isArray(value.value)
368 ) {
369 throw new Error(`Corrupted Object marker: expected an object value`)
370 }
371 value = value.value
372 }
373 const result: any = Array.isArray(value) ? [] : {}
374 for (const key in value) {
375 if (Object.prototype.hasOwnProperty.call(value, key)) {
376 setDataProperty(
377 result,
378 key,
379 this.deserializeValue(value[key], valueEncoding),
380 )
381 }
382 }
383 return result
384 }
385​
386 return value
387 }
388​
389 serializeError(error: Error): SerializedError {
390 return {
391 name: error.name,
392 message: error.message,
393 stack: error.stack,
394 }
395 }
396​
397 deserializeError(data: SerializedError): Error {
398 const error = new Error(data.message)
399 error.name = data.name
400 error.stack = data.stack
401 return error
402 }