Open History to see the last commit
1import { createCollection } from '@tanstack/db'
2import { describe, expect, it } from 'vitest'
3import { TransactionSerializer } from '../src/outbox/TransactionSerializer'
4import type { PendingMutation } from '@tanstack/db'
5import type { OfflineTransaction } from '../src/types'
6
7const mockCollection = createCollection<Record<string, unknown>, string>({
8 id: `test-collection`,
9 getKey: (item) => {
10 if (typeof item.id !== `string`) {
11 throw new Error(`Expected serialized test records to have a string id`)
12 }
13 return item.id
14 },
15 startSync: true,
16 sync: {
17 sync: ({ markReady }) => markReady(),
18 },
19})
20
21function createSerializer(): TransactionSerializer {
22 return new TransactionSerializer({
23 'test-collection': mockCollection,
24 })
25}
26
27function createInsertMutation(
28 modified: Record<string, unknown>,
29): PendingMutation {
30 return {
31 globalKey: `key-1`,
32 type: `insert`,
33 modified,
34 original: {},
35 collection: mockCollection,
36 mutationId: `mut-1`,
37 key: `1`,
38 changes: modified,
39 metadata: undefined,
40 syncMetadata: {},
41 optimistic: true,
42 createdAt: new Date(),
43 updatedAt: new Date(),
44 }
45}
46
47function createTransaction(
48 modified: Record<string, unknown>,
49 createdAt = new Date(`2024-01-01T00:00:00.000Z`),
50): OfflineTransaction {
51 return {
52 id: `tx-1`,
53 createdAt,
54 mutationFnName: `syncData`,
55 mutations: [createInsertMutation(modified)],
56 keys: [`key-1`],
57 idempotencyKey: `idempotency-key-1`,
58 retryCount: 0,
59 nextAttemptAt: 0,
60 version: 1,
61 }
62}
63
64function expectDate(value: unknown): Date {
65 expect(value).toBeInstanceOf(Date)
66 if (!(value instanceof Date)) {
67 throw new Error(`Expected value to be a Date`)
68 }
69 return value
70}
71
72function expectRecord(value: unknown): Record<string, unknown> {
73 expect(value).toBeTypeOf(`object`)
74 if (!isRecord(value)) {
75 throw new Error(`Expected value to be a record`)
76 }
77 return value
78}
79
80function isRecord(value: unknown): value is Record<string, unknown> {
81 return typeof value === `object` && value !== null && !Array.isArray(value)
82}
83
84describe(`TransactionSerializer`, () => {
85 describe(`date handling`, () => {
86 it(`should preserve plain ISO date strings without converting to Date objects`, () => {
87 const serializer = createSerializer()
88
89 // This is the bug: a plain string that looks like an ISO date
90 // should NOT be converted to a Date object after round-trip
91 const isoDateString = `2024-01-15T10:30:00.000Z`
92 const transaction = createTransaction({
93 id: `1`,
94 eventId: isoDateString,
95 description: `Some event`,
96 })
97
98 // Serialize and deserialize (simulating app restart)
99 const serialized = serializer.serialize(transaction)
100 const deserialized = serializer.deserialize(serialized)
101
102 // The eventId should still be a string, not a Date object
103 const eventId = deserialized.mutations[0]!.modified.eventId
104 expect(typeof eventId).toBe(`string`)
105 expect(eventId).toBe(isoDateString)
106 })
107
108 it(`should correctly restore actual Date objects using the marker system`, () => {
109 const serializer = createSerializer()
110 const actualDate = new Date(`2024-01-15T10:30:00.000Z`)
111 const transaction = createTransaction({
112 id: `1`,
113 createdAt: actualDate,
114 name: `Test`,
115 })
116
117 const serialized = serializer.serialize(transaction)
118 const deserialized = serializer.deserialize(serialized)
119
120 // The createdAt should be restored as a Date object
121 const restoredDate = expectDate(
122 deserialized.mutations[0]!.modified.createdAt,
123 )
124 expect(restoredDate.toISOString()).toBe(actualDate.toISOString())
125 })
126
127 it(`should handle mixed Date objects and ISO string values correctly`, () => {
128 const serializer = createSerializer()
129 const actualDate = new Date(`2024-06-15T14:00:00.000Z`)
130 const isoStringValue = `2024-01-15T10:30:00.000Z`
131 const transaction = createTransaction({
132 id: `1`,
133 timestamp: actualDate,
134 scheduledFor: isoStringValue,
135 notes: `Meeting scheduled`,
136 })
137
138 const serialized = serializer.serialize(transaction)
139 const deserialized = serializer.deserialize(serialized)
140 const modified = deserialized.mutations[0]!.modified
141
142 // The actual Date should be restored as Date
143 const restoredTimestamp = expectDate(modified.timestamp)
144 expect(restoredTimestamp.toISOString()).toBe(actualDate.toISOString())
145
146 // The string should remain a string
147 expect(typeof modified.scheduledFor).toBe(`string`)
148 expect(modified.scheduledFor).toBe(isoStringValue)
149 })
150
151 it(`should not corrupt nested ISO string values`, () => {
152 const serializer = createSerializer()
153 const transaction = createTransaction({
154 id: `1`,
155 metadata: {
156 // Nested ISO strings should also be preserved
157 lastSync: `2024-03-20T08:00:00.000Z`,
158 importedFrom: `external-system`,
159 },
160 })
161
162 const serialized = serializer.serialize(transaction)
163 const deserialized = serializer.deserialize(serialized)
164 const metadata = expectRecord(
165 deserialized.mutations[0]!.modified.metadata,
166 )
167
168 expect(typeof metadata.lastSync).toBe(`string`)
169 expect(metadata.lastSync).toBe(`2024-03-20T08:00:00.000Z`)
170 })
171
172 it(`should correctly restore top-level createdAt as Date`, () => {
173 const serializer = createSerializer()
174 const transactionDate = new Date(`2024-05-15T12:30:00.000Z`)
175 const transaction = createTransaction({ id: `1` }, transactionDate)
176
177 const serialized = serializer.serialize(transaction)
178 const deserialized = serializer.deserialize(serialized)
179
180 // Top-level createdAt should be a Date object
181 expect(deserialized.createdAt).toBeInstanceOf(Date)
182 expect(deserialized.createdAt.toISOString()).toBe(
183 transactionDate.toISOString(),
184 )
185 })
186 })
187})