Open History to see the last commit
1import type { SeedDataResult } from '../types'
2
3export type FixtureValue =
4 | ['null']
5 | ['undefined']
6 | ['boolean', boolean]
7 | ['string', string]
8 | ['number' | 'bigint' | 'date', string]
9 | ['array', Array<FixtureValue>]
10 | ['object', Array<[string, FixtureValue]>]
11
12export interface FixtureDiagnostics {
13 registration: string
14 provider: string
15 emit?: (line: string) => void
16}
17
18// A finite fixture format, not a heap serializer. Unsupported extensions must
19// not silently become a supposedly complete replay record or change the getter.
20function encodeFixture(
21 value: unknown,
22 seen = new WeakSet<object>(),
23): FixtureValue {
24 if (value === null) return ['null']
25 switch (typeof value) {
26 case 'undefined':
27 return ['undefined']
28 case 'boolean':
29 return ['boolean', value]
30 case 'string':
31 return ['string', value]
32 case 'number':
33 return ['number', Object.is(value, -0) ? '-0' : String(value)]
34 case 'bigint':
35 return ['bigint', String(value)]
36 case 'object':
37 break
38 default:
39 throw new TypeError('Unsupported fixture value')
40 }
41 if (seen.has(value)) {
42 throw new TypeError('Shared or cyclic fixture reference')
43 }
44 seen.add(value)
45 if (value instanceof Date) return ['date', String(value.getTime())]
46 if (Array.isArray(value)) {
47 if (
48 Reflect.ownKeys(value).length !== value.length + 1 ||
49 Array.from({ length: value.length }, (_, index) => index).some(
50 (index) => !Object.hasOwn(value, index),
51 )
52 ) {
53 throw new TypeError('Sparse or decorated fixture array')
54 }
55 return ['array', value.map((item) => encodeFixture(item, seen))]
56 }
57 if (Object.getPrototypeOf(value) !== Object.prototype) {
58 throw new TypeError('Unsupported fixture object')
59 }
60 const keys = Reflect.ownKeys(value)
61 if (keys.some((key) => typeof key !== 'string')) {
62 throw new TypeError('Symbol fixture property')
63 }
64 return [
65 'object',
66 Object.entries(value).map(([key, item]) => [
67 key,
68 encodeFixture(item, seen),
69 ]),
70 ]
71}
72
73export function reportFixtureCapture(
74 fixture: SeedDataResult,
75 diagnostics: FixtureDiagnostics,
76): void {
77 const capturedAt = Date.now()
78 let payload:
79 | { status: 'complete'; fixture: FixtureValue }
80 | { status: 'unsupported'; reason: string }
81 try {
82 payload = { status: 'complete', fixture: encodeFixture(fixture) }
83 } catch (error) {
84 payload = {
85 status: 'unsupported',
86 reason: error instanceof Error ? error.message : String(error),
87 }
88 }
89 const line =
90 '[db-e2e-fixture] ' +
91 JSON.stringify({
92 version: 1,
93 registration: diagnostics.registration,
94 provider: diagnostics.provider,
95 capturedAt,
96 runtime: null,
97 providerVersion: null,
98 ...payload,
99 })
100 if (diagnostics.emit) diagnostics.emit(line)
101 else console.info(line)
102}