Open History to see the last commit
1// Focused serializer witnesses: metadata toJSON and boxed-scalar rules,
2// cycles, Temporal markers, legacy phases, and malformed wire. The serializer
3// law that these examples instantiate is owned by
4// transaction-serializer-oracle.property.test.ts.
5import { createCollection } from '@tanstack/db'
6import { expect, it } from 'vitest'
7import { OutboxManager } from '../src/outbox/OutboxManager'
8import {
9 MissingTemporalConstructorError,
10 TransactionSerializer,
11} from '../src/outbox/TransactionSerializer'
12import { FakeStorageAdapter } from './harness'
13import type { OfflineTransaction } from '../src/types'
14import type { PendingMutation } from '@tanstack/db'
15
16const temporalCases = [
17 [`Duration`, `PT1H30M`],
18 [`Instant`, `2026-09-16T12:34:56Z`],
19 [`PlainDate`, `2026-09-16`],
20 [`PlainDateTime`, `2026-09-16T12:34:56`],
21 [`PlainMonthDay`, `09-16`],
22 [`PlainTime`, `12:34:56`],
23 [`PlainYearMonth`, `2026-09`],
24 [`ZonedDateTime`, `2026-09-16T12:34:56-06:00[America/Denver]`],
25] as const
26
27type TemporalName = (typeof temporalCases)[number][0]
28
29class TemporalStub {
30 readonly #name: TemporalName
31 readonly #value: string
32
33 constructor(name: TemporalName, value: string) {
34 this.#name = name
35 this.#value = value
36 }
37
38 get [Symbol.toStringTag](): `Temporal.${TemporalName}` {
39 return `Temporal.${this.#name}`
40 }
41
42 toString(): string {
43 return this.#value
44 }
45}
46
47function temporalStubConstructor(name: TemporalName) {
48 return class extends TemporalStub {
49 constructor(value: string) {
50 super(name, value)
51 }
52
53 static from(value: string): TemporalStub {
54 return new TemporalStub(name, value)
55 }
56 }
57}
58
59function metadataTransaction(
60 metadata: Record<string, unknown>,
61): OfflineTransaction {
62 return {
63 id: `metadata-json`,
64 mutationFnName: `persist`,
65 mutations: [],
66 keys: [],
67 idempotencyKey: `once`,
68 createdAt: new Date(0),
69 retryCount: 0,
70 nextAttemptAt: 0,
71 metadata,
72 version: 1,
73 }
74}
75
76it(`rejects cyclic metadata with a bounded JSON-style error`, () => {
77 const metadata: Record<string, unknown> = {}
78 metadata.self = metadata
79
80 expect(() =>
81 new TransactionSerializer({}).serialize(metadataTransaction(metadata)),
82 ).toThrowError(new TypeError(`Converting circular structure to JSON`))
83})
84
85it(`rejects cyclic mutation values with a bounded JSON-style error`, () => {
86 const collection = { id: `cycle-writer` } as any
87 const modified: Record<string, unknown> = { id: `one` }
88 modified.self = modified
89 const transaction: OfflineTransaction = {
90 ...metadataTransaction({}),
91 mutations: [
92 {
93 globalKey: `cycle-writer:one`,
94 type: `insert`,
95 modified,
96 original: {},
97 changes: modified,
98 collection,
99 } as PendingMutation,
100 ],
101 keys: [`cycle-writer:one`],
102 }
103
104 expect(() =>
105 new TransactionSerializer({ rows: collection }).serialize(transaction),
106 ).toThrowError(new TypeError(`Converting circular structure to JSON`))
107})
108
109it(`preserves repeated references that do not form a cycle`, () => {
110 const shared = { nested: [`value`] }
111 const transaction = metadataTransaction({ left: shared, right: shared })
112
113 const wire = JSON.parse(new TransactionSerializer({}).serialize(transaction))
114
115 expect(wire.metadata).toEqual({
116 left: { nested: [`value`] },
117 right: { nested: [`value`] },
118 })
119})
120
121it(`preserves spoofed Temporal tags as data while restoring branded values`, async () => {
122 class PlainDateStub {
123 readonly #value: string
124
125 constructor(value: string) {
126 this.#value = value
127 }
128
129 static from(value: string): PlainDateStub {
130 return new PlainDateStub(value)
131 }
132
133 get [Symbol.toStringTag](): `Temporal.PlainDate` {
134 return `Temporal.PlainDate`
135 }
136
137 toString(): string {
138 return this.#value
139 }
140 }
141
142 const temporalGlobal = globalThis as { Temporal?: Record<string, unknown> }
143 const previousTemporal = temporalGlobal.Temporal
144 temporalGlobal.Temporal = { PlainDate: PlainDateStub }
145 const storage = new FakeStorageAdapter()
146 const outbox = new OutboxManager(storage, {})
147 const transaction = metadataTransaction({
148 spoofed: {
149 keep: `user data`,
150 [Symbol.toStringTag]: `Temporal.PlainDate`,
151 toString: () => `not-a-date`,
152 },
153 genuine: new PlainDateStub(`2026-09-22`),
154 })
155
156 try {
157 await outbox.add(transaction)
158 const restored = await outbox.get(transaction.id)
159
160 expect(restored?.metadata).toMatchObject({
161 spoofed: { keep: `user data` },
162 genuine: expect.any(PlainDateStub),
163 })
164 expect(String((restored?.metadata as any).genuine)).toBe(`2026-09-22`)
165 } finally {
166 if (previousTemporal === undefined) delete temporalGlobal.Temporal
167 else temporalGlobal.Temporal = previousTemporal
168 }
169})
170
171it(`preserves plain user data with a Temporal tag when Temporal is unavailable`, () => {
172 const temporalGlobal = globalThis as { Temporal?: Record<string, unknown> }
173 const previousTemporal = temporalGlobal.Temporal
174 delete temporalGlobal.Temporal
175 const transaction = metadataTransaction({
176 spoofed: {
177 keep: `user data`,
178 [Symbol.toStringTag]: `Temporal.Instant`,
179 },
180 })
181
182 try {
183 const wire = JSON.parse(
184 new TransactionSerializer({}).serialize(transaction),
185 )
186
187 expect(wire.metadata).toEqual({ spoofed: { keep: `user data` } })
188 } finally {
189 if (previousTemporal === undefined) delete temporalGlobal.Temporal
190 else temporalGlobal.Temporal = previousTemporal
191 }
192})
193
194it(`does not invoke a mutation value's plain Symbol.toStringTag getter`, () => {
195 let reads = 0
196 const value = { keep: `user data` }
197 Object.defineProperty(value, Symbol.toStringTag, {
198 get() {
199 reads++
200 throw new Error(`do not inspect user getters`)
201 },
202 })
203 const collection = { id: `tag-getter-writer` } as any
204 const modified = { id: `one`, value }
205 const transaction: OfflineTransaction = {
206 ...metadataTransaction({}),
207 mutations: [
208 {
209 globalKey: `tag-getter-writer:one`,
210 type: `insert`,
211 modified,
212 original: {},
213 changes: modified,
214 collection,
215 } as unknown as PendingMutation,
216 ],
217 keys: [`tag-getter-writer:one`],
218 }
219
220 const wire = JSON.parse(
221 new TransactionSerializer({ rows: collection }).serialize(transaction),
222 )
223
224 expect({ reads, modified: wire.mutations[0].modified }).toEqual({
225 reads: 0,
226 modified: { id: `one`, value: { keep: `user data` } },
227 })
228})
229
230it(`rejects native scalars before storage when global restoration is unavailable`, async () => {
231 const temporalGlobal = globalThis as { Temporal?: Record<string, unknown> }
232 const previousTemporal = temporalGlobal.Temporal
233 temporalGlobal.Temporal = {}
234 const storage = new FakeStorageAdapter()
235 const outbox = new OutboxManager(storage, {})
236 const transaction: OfflineTransaction = {
237 id: `unrestorable-native-scalar`,
238 mutationFnName: `persist`,
239 mutations: [],
240 keys: [],
241 idempotencyKey: `once`,
242 createdAt: new Date(0),
243 retryCount: 0,
244 nextAttemptAt: 0,
245 metadata: {
246 due: new TemporalStub(`PlainDate`, `2026-09-16`),
247 },
248 version: 1,
249 }
250
251 try {
252 await expect(outbox.add(transaction)).rejects.toThrow(
253 MissingTemporalConstructorError,
254 )
255 expect(storage.snapshot()).toEqual({})
256 } finally {
257 if (previousTemporal === undefined) delete temporalGlobal.Temporal
258 else temporalGlobal.Temporal = previousTemporal
259 }
260})
261
262it(`uses one validated Temporal tag when writing a marker`, () => {
263 const temporalGlobal = globalThis as { Temporal?: Record<string, unknown> }
264 const previousTemporal = temporalGlobal.Temporal
265 let reads = 0
266 class PlainDateStub {
267 readonly #value: string
268
269 constructor(value: string) {
270 this.#value = value
271 }
272
273 static from(value: string): PlainDateStub {
274 return new PlainDateStub(value)
275 }
276
277 get [Symbol.toStringTag]() {
278 reads++
279 return reads === 1 ? `Temporal.PlainDate` : `Temporal.Invalid`
280 }
281
282 toString(): string {
283 return this.#value
284 }
285 }
286 temporalGlobal.Temporal = { PlainDate: PlainDateStub }
287 const value = new PlainDateStub(`2026-09-16`)
288
289 try {
290 const wire = JSON.parse(
291 new TransactionSerializer({}).serialize(metadataTransaction({ value })),
292 )
293 expect(wire.metadata.value).toEqual({
294 __type: `Temporal`,
295 type: `Temporal.PlainDate`,
296 value: `2026-09-16`,
297 })
298 expect(reads).toBe(1)
299 } finally {
300 if (previousTemporal === undefined) delete temporalGlobal.Temporal
301 else temporalGlobal.Temporal = previousTemporal
302 }
303})
304
305it(`preserves metadata toJSON values without changing mutation value semantics`, () => {
306 class JsonValue {
307 toJSON(key: string) {
308 return `from-toJSON:${key}`
309 }
310 }
311 const collection = {
312 id: `metadata-json-writer`,
313 getKeyFromItem: (value: { id: string }) => value.id,
314 } as any
315 const serializer = new TransactionSerializer({ rows: collection })
316 const url = new URL(`https://example.com/path`)
317 const jsonValue = new JsonValue()
318 const metadata = {
319 url,
320 jsonValue,
321 nested: [jsonValue],
322 boxed: [Object(7), Object(`value`), Object(false)],
323 }
324 Object.defineProperty(metadata, `toJSON`, {
325 value: (key: string) => ({ ...metadata, metadataKey: key }),
326 })
327 const transaction: OfflineTransaction = {
328 id: `metadata-json`,
329 mutationFnName: `persist`,
330 mutations: [
331 {
332 globalKey: `metadata-json-writer:one`,
333 type: `insert`,
334 modified: { id: `one`, url, jsonValue },
335 original: {},
336 changes: {},
337 collection,
338 } as unknown as PendingMutation,
339 ],
340 keys: [`metadata-json-writer:one`],
341 idempotencyKey: `once`,
342 createdAt: new Date(0),
343 retryCount: 0,
344 nextAttemptAt: 0,
345 metadata,
346 version: 1,
347 }
348
349 const encoded = serializer.serialize(transaction)
350 const wire = JSON.parse(encoded)
351 expect(wire.metadata).toEqual({
352 url: `https://example.com/path`,
353 jsonValue: `from-toJSON:jsonValue`,
354 nested: [`from-toJSON:0`],
355 boxed: [7, `value`, false],
356 metadataKey: `metadata`,
357 })
358 expect(wire.mutations[0].modified).toEqual({
359 id: `one`,
360 url: {},
361 jsonValue: {},
362 })
363
364 const decoded = serializer.deserialize(encoded)
365 expect(decoded.metadata).toEqual(wire.metadata)
366 expect(decoded.mutations[0]!.modified).toEqual(wire.mutations[0].modified)
367})
368
369it(`does not invoke toJSON again on its immediate replacement`, () => {
370 const nested = {
371 toJSON(key: string) {
372 return `nested:${key}`
373 },
374 }
375 const replacement = {
376 nested,
377 toJSON() {
378 return `incorrect second invocation`
379 },
380 }
381 const transaction = metadataTransaction({
382 value: {
383 toJSON(key: string) {
384 return key === `value` ? replacement : `incorrect key:${key}`
385 },
386 },
387 })
388
389 const wire = JSON.parse(new TransactionSerializer({}).serialize(transaction))
390
391 expect(wire.metadata).toEqual({ value: { nested: `nested:nested` } })
392})
393
394it(`rejects a toJSON replacement that references its receiver`, () => {
395 const source = {
396 toJSON() {
397 return { back: source }
398 },
399 }
400
401 expect(() =>
402 new TransactionSerializer({}).serialize(
403 metadataTransaction({ value: source }),
404 ),
405 ).toThrowError(new TypeError(`Converting circular structure to JSON`))
406})
407
408it(`treats immediate native-scalar replacements as ordinary JSON values`, () => {
409 const temporalReplacement = {
410 [Symbol.toStringTag]: `Temporal.PlainDate`,
411 toString() {
412 return `2026-09-16`
413 },
414 }
415 const transaction = metadataTransaction({
416 date: { toJSON: () => new Date(0) },
417 temporal: { toJSON: () => temporalReplacement },
418 })
419
420 const wire = JSON.parse(new TransactionSerializer({}).serialize(transaction))
421
422 expect(wire.metadata).toEqual({ date: {}, temporal: {} })
423})
424
425it(`preserves JSON array length and indexed-property semantics in metadata`, () => {
426 const values = Array(3) as Array<string | undefined>
427 Object.defineProperty(values, 0, { enumerable: false, value: `hidden` })
428 values[1] = `visible`
429 const shrinking = Array(3) as Array<string | undefined>
430 Object.defineProperty(shrinking, 0, {
431 enumerable: true,
432 get() {
433 shrinking.length = 1
434 return `first`
435 },
436 })
437 const transaction = metadataTransaction({ values, shrinking })
438
439 const wire = JSON.parse(new TransactionSerializer({}).serialize(transaction))
440
441 expect(wire.metadata).toEqual({
442 values: [`hidden`, `visible`, null],
443 shrinking: [`first`, null, null],
444 })
445})
446
447it(`retains JSON's error for boxed BigInt metadata`, () => {
448 const transaction = metadataTransaction({ value: Object(1n) })
449
450 expect(() => new TransactionSerializer({}).serialize(transaction)).toThrow(
451 TypeError,
452 )
453})
454
455it(`does not recurse through fresh toJSON replacement objects`, () => {
456 const freshReplacement = (): Record<string, unknown> => ({
457 toJSON: freshReplacement,
458 })
459 const transaction = metadataTransaction({
460 value: { toJSON: freshReplacement },
461 })
462
463 const wire = JSON.parse(new TransactionSerializer({}).serialize(transaction))
464
465 expect(wire.metadata).toEqual({ value: {} })
466})
467
468it(`reads metadata toJSON once with its object as the receiver`, () => {
469 let reads = 0
470 let selfCalls = 0
471 const value = {
472 marker: `receiver`,
473 get toJSON() {
474 reads++
475 if (reads > 1) throw new Error(`toJSON read more than once`)
476 return function (this: { marker: string }, key: string) {
477 return `${this.marker}:${key}`
478 }
479 },
480 }
481 const self = {
482 keep: `value`,
483 toJSON() {
484 selfCalls++
485 return this
486 },
487 }
488 const transaction = metadataTransaction({ value, self })
489
490 const wire = JSON.parse(new TransactionSerializer({}).serialize(transaction))
491
492 expect(wire.metadata).toEqual({
493 value: `receiver:value`,
494 self: { keep: `value` },
495 })
496 expect(reads).toBe(1)
497 expect(selfCalls).toBe(1)
498})
499
500it(`preserves native scalar identity across storage restart`, async () => {
501 type NativeRow = {
502 id: string
503 values: Record<TemporalName, TemporalStub>
504 }
505 const writer = createCollection<NativeRow>({
506 id: `native-scalar-writer`,
507 getKey: (row) => row.id,
508 sync: { sync: ({ markReady }) => markReady() },
509 })
510 const reader = createCollection<NativeRow>({
511 id: `native-scalar-reader`,
512 getKey: (row) => row.id,
513 sync: { sync: ({ markReady }) => markReady() },
514 })
515 const previousTemporal = (
516 globalThis as { Temporal?: Record<string, unknown> }
517 ).Temporal
518 ;(globalThis as { Temporal?: Record<string, unknown> }).Temporal =
519 Object.fromEntries(
520 temporalCases.map(([name]) => [name, temporalStubConstructor(name)]),
521 )
522
523 const values = Object.fromEntries(
524 temporalCases.map(([name, value]) => [name, new TemporalStub(name, value)]),
525 ) as NativeRow[`values`]
526 const mutation = {
527 globalKey: `native-scalar-writer:one`,
528 type: `update`,
529 modified: { id: `one`, values },
530 original: { id: `one`, values },
531 changes: { values },
532 collection: writer,
533 } as unknown as PendingMutation
534 const transaction: OfflineTransaction = {
535 id: `native-scalars`,
536 mutationFnName: `persist`,
537 mutations: [mutation],
538 keys: [mutation.globalKey],
539 idempotencyKey: `once`,
540 createdAt: new Date(0),
541 retryCount: 0,
542 nextAttemptAt: 0,
543 metadata: { nested: { values } },
544 version: 1,
545 }
546
547 try {
548 const encoded = new TransactionSerializer({ rows: writer }).serialize(
549 transaction,
550 )
551 const wire = JSON.parse(encoded)
552 expect(wire.valueEncoding).toBe(3)
553 const encodedLocations = [
554 wire.mutations[0].modified.values,
555 wire.mutations[0].original.values,
556 wire.mutations[0].changes.values,
557 wire.metadata.nested.values,
558 ] as Array<Record<TemporalName, unknown>>
559 for (const location of encodedLocations)
560 for (const [name, value] of temporalCases)
561 expect(location[name]).toEqual({
562 __type: `Temporal`,
563 type: `Temporal.${name}`,
564 value,
565 })
566
567 const restarted = new TransactionSerializer({ rows: reader })
568 const decoded = restarted.deserialize(encoded)
569 const decodedMutation = decoded.mutations[0]!
570 const restored = [
571 (decodedMutation.modified as NativeRow).values,
572 (decodedMutation.original as NativeRow).values,
573 (decodedMutation.changes as { values: NativeRow[`values`] }).values,
574 (
575 decoded.metadata as {
576 nested: { values: NativeRow[`values`] }
577 }
578 ).nested.values,
579 ] as Array<Record<TemporalName, unknown>>
580
581 for (const location of restored) {
582 for (const [name, value] of temporalCases) {
583 expect(location[name]).toBeInstanceOf(TemporalStub)
584 expect(Object.prototype.toString.call(location[name])).toBe(
585 `[object Temporal.${name}]`,
586 )
587 expect(String(location[name])).toBe(value)
588 }
589 }
590 } finally {
591 if (previousTemporal === undefined)
592 delete (globalThis as { Temporal?: Record<string, unknown> }).Temporal
593 else
594 (globalThis as { Temporal?: Record<string, unknown> }).Temporal =
595 previousTemporal
596 await writer.cleanup()
597 await reader.cleanup()
598 }
599})
600
601it(`preserves prior wire meanings when reading native scalar markers`, async () => {
602 const collection = createCollection<{
603 id: string
604 due: unknown
605 createdAt: unknown
606 }>({
607 id: `native-scalar-compatibility`,
608 getKey: (row) => row.id,
609 sync: { sync: ({ markReady }) => markReady() },
610 })
611 const serializer = new TransactionSerializer({ rows: collection })
612 const temporalData = {
613 __type: `Temporal`,
614 type: `Temporal.PlainDate`,
615 value: `2026-09-16`,
616 }
617 const dateMarker = {
618 __type: `Date`,
619 value: `2026-09-16T12:34:56.000Z`,
620 }
621 const baseWire = {
622 id: `compatibility`,
623 mutationFnName: `persist`,
624 mutations: [
625 {
626 globalKey: `rows:one`,
627 type: `insert`,
628 modified: { id: `one`, due: temporalData, createdAt: dateMarker },
629 original: {},
630 changes: {},
631 collectionId: `rows`,
632 },
633 ],
634 keys: [`rows:one`],
635 idempotencyKey: `once`,
636 createdAt: new Date(0).toISOString(),
637 retryCount: 0,
638 nextAttemptAt: 0,
639 metadata: { due: temporalData, createdAt: dateMarker },
640 version: 1,
641 }
642
643 try {
644 const unversioned = serializer.deserialize(JSON.stringify(baseWire))
645 expect(unversioned.mutations[0]!.modified).toEqual({
646 id: `one`,
647 due: temporalData,
648 createdAt: new Date(dateMarker.value),
649 })
650 expect(unversioned.metadata).toEqual(baseWire.metadata)
651
652 const versionTwo = serializer.deserialize(
653 JSON.stringify({
654 ...baseWire,
655 valueEncoding: 2,
656 mutations: [
657 {
658 ...baseWire.mutations[0],
659 modified: {
660 id: `one`,
661 due: { __type: `Object`, value: temporalData },
662 createdAt: dateMarker,
663 },
664 },
665 ],
666 }),
667 )
668 expect(versionTwo.mutations[0]!.modified).toEqual({
669 id: `one`,
670 due: temporalData,
671 createdAt: new Date(dateMarker.value),
672 })
673 expect(versionTwo.metadata).toEqual(baseWire.metadata)
674 } finally {
675 await collection.cleanup()
676 }
677})
678
679it(`keeps legacy pending-work records phase-free across serialization`, () => {
680 const serializer = new TransactionSerializer({})
681 const legacyWire = {
682 id: `legacy-pending`,
683 mutationFnName: `persist`,
684 mutations: [],
685 keys: [],
686 idempotencyKey: `legacy-key`,
687 createdAt: new Date(0).toISOString(),
688 retryCount: 0,
689 nextAttemptAt: 0,
690 version: 1,
691 }
692
693 const decoded = serializer.deserialize(JSON.stringify(legacyWire))
694 expect(decoded.outboxPhase).toBeUndefined()
695 const rewritten = JSON.parse(serializer.serialize(decoded)) as Record<
696 string,
697 unknown
698 >
699 expect(rewritten).not.toHaveProperty(`outboxPhase`)
700 expect(rewritten).toMatchObject(legacyWire)
701 expect(rewritten).toHaveProperty(`valueEncoding`, 3)
702})
703
704it(`round-trips a mutationFn-fulfilled deletion-pending record`, () => {
705 const serializer = new TransactionSerializer({})
706 const transaction: OfflineTransaction = {
707 id: `deletion-pending`,
708 mutationFnName: `persist`,
709 mutations: [],
710 keys: [],
711 idempotencyKey: `stable-key`,
712 createdAt: new Date(0),
713 retryCount: 0,
714 nextAttemptAt: 0,
715 outboxPhase: `deletion-pending`,
716 version: 1,
717 }
718
719 const encoded = serializer.serialize(transaction)
720 expect(JSON.parse(encoded)).toMatchObject({
721 id: transaction.id,
722 idempotencyKey: `stable-key`,
723 outboxPhase: `deletion-pending`,
724 valueEncoding: 3,
725 version: 1,
726 })
727 expect(serializer.deserialize(encoded)).toEqual(transaction)
728})
729
730it.each([null, false, 0, {}, `provider-pending`, `unknown`])(
731 `rejects malformed or unknown outbox phase %j`,
732 (outboxPhase) => {
733 const serializer = new TransactionSerializer({})
734 const wire = {
735 id: `invalid-phase`,
736 mutationFnName: `persist`,
737 mutations: [],
738 keys: [],
739 idempotencyKey: `stable-key`,
740 createdAt: new Date(0).toISOString(),
741 retryCount: 0,
742 nextAttemptAt: 0,
743 outboxPhase,
744 version: 1,
745 }
746 expect(() => serializer.deserialize(JSON.stringify(wire))).toThrow(
747 /Unsupported transaction outbox phase/,
748 )
749 expect(() =>
750 serializer.serialize({
751 ...wire,
752 createdAt: new Date(0),
753 } as unknown as OfflineTransaction),
754 ).toThrow(/Unsupported transaction outbox phase/)
755 },
756)
757
758it(`fails visibly with the retained native scalar transaction id`, async () => {
759 const collection = createCollection<{ id: string; due: unknown }>({
760 id: `native-scalar-missing-runtime`,
761 getKey: (row) => row.id,
762 sync: { sync: ({ markReady }) => markReady() },
763 })
764 const marker = {
765 __type: `Temporal`,
766 type: `Temporal.PlainDate`,
767 value: `2026-09-16`,
768 }
769 const wire = JSON.stringify({
770 valueEncoding: 3,
771 id: `missing-runtime`,
772 mutationFnName: `persist`,
773 mutations: [
774 {
775 globalKey: `rows:one`,
776 type: `insert`,
777 modified: { id: `one`, due: marker },
778 original: {},
779 changes: {},
780 collectionId: `rows`,
781 },
782 ],
783 keys: [`rows:one`],
784 idempotencyKey: `once`,
785 createdAt: new Date(0).toISOString(),
786 retryCount: 0,
787 nextAttemptAt: 0,
788 metadata: { due: marker },
789 version: 1,
790 })
791 const temporalGlobal = globalThis as { Temporal?: Record<string, unknown> }
792 const previousTemporal = temporalGlobal.Temporal
793 temporalGlobal.Temporal = {}
794 const storage = new FakeStorageAdapter()
795 await storage.set(`tx:missing-runtime`, wire)
796 const outbox = new OutboxManager(storage, { rows: collection })
797
798 try {
799 expect(() =>
800 new TransactionSerializer({ rows: collection }).deserialize(wire),
801 ).toThrow(MissingTemporalConstructorError)
802 await expect(outbox.get(`missing-runtime`)).rejects.toThrow(
803 /transaction missing-runtime/,
804 )
805 await expect(outbox.getAll()).rejects.toThrow(/transaction missing-runtime/)
806 expect(storage.snapshot()).toHaveProperty(`tx:missing-runtime`, wire)
807 } finally {
808 if (previousTemporal === undefined) delete temporalGlobal.Temporal
809 else temporalGlobal.Temporal = previousTemporal
810 await collection.cleanup()
811 }
812})
813
814it(`rejects malformed native scalar markers and constructor failures`, async () => {
815 const collection = createCollection<{ id: string; due: unknown }>({
816 id: `native-scalar-invalid`,
817 getKey: (row) => row.id,
818 sync: { sync: ({ markReady }) => markReady() },
819 })
820 const serializer = new TransactionSerializer({ rows: collection })
821 const wire = (marker: unknown) =>
822 JSON.stringify({
823 valueEncoding: 3,
824 id: `invalid-native-scalar`,
825 mutationFnName: `persist`,
826 mutations: [
827 {
828 globalKey: `rows:one`,
829 type: `insert`,
830 modified: { id: `one`, due: marker },
831 original: {},
832 changes: {},
833 collectionId: `rows`,
834 },
835 ],
836 keys: [`rows:one`],
837 idempotencyKey: `once`,
838 createdAt: new Date(0).toISOString(),
839 retryCount: 0,
840 nextAttemptAt: 0,
841 version: 1,
842 })
843
844 try {
845 expect(() =>
846 serializer.deserialize(
847 wire({
848 __type: `Temporal`,
849 type: `Temporal.Calendar`,
850 value: `iso8601`,
851 }),
852 ),
853 ).toThrow(`Corrupted Temporal marker: invalid type field`)
854 expect(() =>
855 serializer.deserialize(
856 wire({ __type: `Temporal`, type: `Temporal.PlainDate` }),
857 ),
858 ).toThrow(`Corrupted Temporal marker: missing value field`)
859
860 const temporalGlobal = globalThis as {
861 Temporal?: Record<string, unknown>
862 }
863 const previousTemporal = temporalGlobal.Temporal
864 const constructorFailure = new Error(`constructor rejected value`)
865 temporalGlobal.Temporal = {
866 PlainDate: {
867 from: () => {
868 throw constructorFailure
869 },
870 },
871 }
872 try {
873 expect(() =>
874 serializer.deserialize(
875 wire({
876 __type: `Temporal`,
877 type: `Temporal.PlainDate`,
878 value: `not-a-date`,
879 }),
880 ),
881 ).toThrow(constructorFailure)
882 } finally {
883 if (previousTemporal === undefined) delete temporalGlobal.Temporal
884 else temporalGlobal.Temporal = previousTemporal
885 }
886 } finally {
887 await collection.cleanup()
888 }
889})