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

TransactionSerializer.ts

387 lines11.1 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​
97export class TransactionSerializer {
98 private collections: Record<string, Collection<any, any, any, any, any>>
99 private collectionIdToKey: Map<string, string>
100​
101 constructor(
102 collections: Record<string, Collection<any, any, any, any, any>>,
103 ) {
104 this.collections = collections
105 // Create reverse lookup from collection.id to registry key
106 this.collectionIdToKey = new Map()
107 for (const [key, collection] of Object.entries(collections)) {
108 this.collectionIdToKey.set(collection.id, key)
109 }
110 }
111​
112 serialize(transaction: OfflineTransaction): string {
113 const serialized: SerializedOfflineTransaction = {
114 ...transaction,
115 valueEncoding: 3,
116 createdAt: transaction.createdAt.toISOString(),
117 metadata: this.serializeValue(transaction.metadata, `metadata`),
118 mutations: transaction.mutations.map((mutation) =>
119 this.serializeMutation(mutation),
120 ),
121 }
122 return JSON.stringify(serialized)
123 }
124​
125 deserialize(data: string): OfflineTransaction {
126 // Old records retain their Date-marker meaning. New records also escape
127 // marker-shaped user objects; the encoding tag is not application metadata.
128 const {
129 valueEncoding,
130 ...parsed
131 }: Omit<SerializedOfflineTransaction, `valueEncoding`> & {
132 valueEncoding?: unknown
133 } = JSON.parse(data)
134 if (
135 valueEncoding !== undefined &&
136 valueEncoding !== 2 &&
137 valueEncoding !== 3
138 ) {
139 throw new Error(
140 `Unsupported transaction value encoding: ${valueEncoding}`,
141 )
142 }
143​
144 const createdAt = new Date(parsed.createdAt)
145 if (isNaN(createdAt.getTime())) {
146 throw new Error(
147 `Failed to deserialize transaction: invalid createdAt value "${parsed.createdAt}"`,
148 )
149 }
150​
151 return {
152 ...parsed,
153 createdAt,
154 metadata:
155 valueEncoding === 3
156 ? this.deserializeValue(parsed.metadata, valueEncoding)
157 : parsed.metadata,
158 mutations: parsed.mutations.map((mutationData) =>
159 this.deserializeMutation(mutationData, valueEncoding),
160 ),
161 }
162 }
163​
164 private serializeMutation(mutation: PendingMutation): SerializedMutation {
165 const registryKey = this.collectionIdToKey.get(mutation.collection.id)
166 if (!registryKey) {
167 throw new Error(
168 `Collection with id ${mutation.collection.id} not found in registry`,
169 )
170 }
171​
172 return {
173 globalKey: mutation.globalKey,
174 type: mutation.type,
175 modified: this.serializeValue(mutation.modified),
176 original: this.serializeValue(mutation.original),
177 changes: this.serializeValue(mutation.changes),
178 collectionId: registryKey, // Store registry key instead of collection.id
179 }
180 }
181​
182 private deserializeMutation(
183 data: SerializedMutation,
184 valueEncoding: 2 | 3 | undefined,
185 ): PendingMutation {
186 const collection = this.collections[data.collectionId]
187 if (!collection) {
188 throw new Error(`Collection with id ${data.collectionId} not found`)
189 }
190​
191 const modified = this.deserializeValue(data.modified, valueEncoding)
192​
193 // Extract the key from the modified data using the collection's getKey function
194 // This is needed for optimistic state restoration to work correctly
195 const key = modified ? collection.getKeyFromItem(modified) : null
196​
197 // Create a partial PendingMutation - we can't fully reconstruct it but
198 // we provide what we can. The executor will need to handle the rest.
199 return {
200 globalKey: data.globalKey,
201 type: data.type as any,
202 modified,
203 original: this.deserializeValue(data.original, valueEncoding),
204 changes: this.deserializeValue(data.changes, valueEncoding) ?? {},
205 collection,
206 // These fields would need to be reconstructed by the executor
207 mutationId: ``, // Will be regenerated
208 key,
209 metadata: undefined,
210 syncMetadata: {},
211 optimistic: true,
212 createdAt: new Date(),
213 updatedAt: new Date(),
214 } as PendingMutation
215 }
216​
217 private serializeValue(
218 value: any,
219 jsonKey?: string | false,
220 ancestors = new WeakSet<object>(),
221 ): any {
222 if (value === null || typeof value !== `object`) return value
223​
224 if (jsonKey !== false && value instanceof Date) {
225 return { __type: `Date`, value: value.toISOString() }
226 }
227​
228 const temporalConstructorName =
229 jsonKey !== false && mayBeNativeScalar(value)
230 ? getTemporalConstructorName(value[Symbol.toStringTag])
231 : undefined
232 if (temporalConstructorName) {
233 const temporalValue = serializeTemporalValue(
234 value,
235 temporalConstructorName,
236 )
237 if (temporalValue !== undefined)
238 return {
239 __type: `Temporal`,
240 type: `Temporal.${temporalConstructorName}`,
241 value: temporalValue,
242 }
243 }
244​
245 if (ancestors.has(value))
246 throw new TypeError(`Converting circular structure to JSON`)
247​
248 const toJSON = typeof jsonKey === `string` && value.toJSON
249 if (typeof toJSON === `function`) {
250 const replacement = toJSON.call(value, jsonKey)
251 if (replacement === value) {
252 return this.serializeValue(replacement, false, ancestors)
253 }
254​
255 ancestors.add(value)
256 try {
257 return this.serializeValue(replacement, false, ancestors)
258 } finally {
259 ancestors.delete(value)
260 }
261 }
262 if (
263 jsonKey !== undefined &&
264 (value instanceof Boolean ||
265 value instanceof BigInt ||
266 value instanceof Number ||
267 value instanceof String)
268 ) {
269 return value.valueOf()
270 }
271​
272 ancestors.add(value)
273​
274 const isArray = Array.isArray(value)
275 const result: any = isArray ? [] : {}
276 try {
277 if (isArray) {
278 const length = value.length
279 for (let index = 0; index < length; index++) {
280 const key = String(index)
281 setDataProperty(
282 result,
283 key,
284 this.serializeValue(
285 value[index],
286 jsonKey === undefined ? undefined : key,
287 ancestors,
288 ),
289 )
290 }
291 } else {
292 for (const key of Object.keys(value)) {
293 setDataProperty(
294 result,
295 key,
296 this.serializeValue(
297 value[key],
298 jsonKey === undefined ? undefined : key,
299 ancestors,
300 ),
301 )
302 }
303 }
304 } finally {
305 ancestors.delete(value)
306 }
307 if (jsonKey === false && typeof result.toJSON === `function`)
308 delete result.toJSON
309 return !isArray && Object.prototype.hasOwnProperty.call(value, `__type`)
310 ? { __type: `Object`, value: result }
311 : result
312 }
313​
314 private deserializeValue(value: any, valueEncoding: 2 | 3 | undefined): any {
315 if (value === null || value === undefined) {
316 return value
317 }
318​
319 if (typeof value === `object` && value.__type === `Date`) {
320 if (value.value === undefined || value.value === null) {
321 throw new Error(`Corrupted Date marker: missing value field`)
322 }
323 const date = new Date(value.value)
324 if (isNaN(date.getTime())) {
325 throw new Error(
326 `Failed to deserialize Date marker: invalid date value "${value.value}"`,
327 )
328 }
329 return date
330 }
331​
332 if (
333 valueEncoding === 3 &&
334 typeof value === `object` &&
335 value.__type === `Temporal`
336 ) {
337 const constructorName = getTemporalConstructorName(value.type)
338 if (!constructorName)
339 throw new Error(`Corrupted Temporal marker: invalid type field`)
340 if (typeof value.value !== `string`)
341 throw new Error(`Corrupted Temporal marker: missing value field`)
342 return requireTemporalConstructor(constructorName).from(value.value)
343 }
344​
345 if (typeof value === `object`) {
346 // Unwrap once, then decode only the fields: the object's own __type is data.
347 if (valueEncoding !== undefined && value.__type === `Object`) {
348 if (
349 value.value === null ||
350 typeof value.value !== `object` ||
351 Array.isArray(value.value)
352 ) {
353 throw new Error(`Corrupted Object marker: expected an object value`)
354 }
355 value = value.value
356 }
357 const result: any = Array.isArray(value) ? [] : {}
358 for (const key in value) {
359 if (Object.prototype.hasOwnProperty.call(value, key)) {
360 setDataProperty(
361 result,
362 key,
363 this.deserializeValue(value[key], valueEncoding),
364 )
365 }
366 }
367 return result
368 }
369​
370 return value
371 }
372​
373 serializeError(error: Error): SerializedError {
374 return {
375 name: error.name,
376 message: error.message,
377 stack: error.stack,
378 }
379 }
380​
381 deserializeError(data: SerializedError): Error {
382 const error = new Error(data.message)
383 error.name = data.name
384 error.stack = data.stack
385 return error
386 }