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

TransactionSerializer.ts

443 lines12.9 KB

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