Skip to content

Commit 8f15acd

Browse files
authored
fix(reactotron-core-client): Fixes BigInt() serialization (#1437)
Closes #1436 with tests! Link to community slack: https://infiniteredcommunity.slack.com/archives/C42C5UKHV/p1707258028882889
1 parent 1e56aa2 commit 8f15acd

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

.nxignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
scripts/template
1+
scripts/template
2+
apps/example-app

lib/reactotron-core-client/src/serialize.ts

+15-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,21 @@ const INFINITY = "~~~ Infinity ~~~"
1515
const NEGATIVE_INFINITY = "~~~ -Infinity ~~~"
1616
// const NAN = '~~~ NaN ~~~'
1717

18+
/**
19+
* Fix BigInt serialization
20+
* BigInts are not supported by JSON.stringify. This is a workaround.
21+
* https://github.com/GoogleChromeLabs/jsbi/issues/30#issuecomment-953187833
22+
*/
23+
declare global {
24+
interface BigInt {
25+
toJSON(): string
26+
}
27+
}
28+
// eslint-disable-next-line no-extend-native
29+
BigInt.prototype.toJSON = function () {
30+
return this.toString()
31+
}
32+
1833
/**
1934
* Attempts to give a name to a function.
2035
*
@@ -98,7 +113,6 @@ function serialize(source, proxyHack = false) {
98113
return replacer == null ? value : replacer.call(this, key, value)
99114
}
100115
}
101-
102116
return JSON.stringify(source, serializer(null))
103117
}
104118

lib/reactotron-core-client/test/serialize.test.ts

+14
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,18 @@ test("serializes arrays", () => {
1616
expect(actual).toEqual(expected)
1717
})
1818

19+
test("serializes BigInts", () => {
20+
const mock = {
21+
x: [BigInt(1), BigInt(2), BigInt(3)],
22+
// eslint-disable-next-line @typescript-eslint/no-loss-of-precision, no-loss-of-precision
23+
y: [BigInt(12345678901234567890), BigInt(2345434553442342345235243234)],
24+
}
25+
const actual = serialize(mock)
26+
const expected = `{"x":["1","2","3"],"y":["12345678901234567168","2345434553442342324832043008"]}`
27+
28+
expect(actual).toEqual(expected)
29+
})
30+
1931
test("serializes nested objects", () => {
2032
const mock = { x: { y: 1 } }
2133
const actual = serialize(mock)
@@ -49,6 +61,7 @@ test("medium sized funk", () => {
4961
}
5062
mockPayload.fn = hello
5163
mockPayload.anonymous = () => {}
64+
mockPayload.bigInt = BigInt(1212)
5265

5366
const actual = JSON.parse(serialize(mockPayload))
5467
expect(actual.string).toBe("String")
@@ -62,4 +75,5 @@ test("medium sized funk", () => {
6275
expect(actual.list[4]).toEqual({ foo: { x: 1 }, bar: "~~~ Circular Reference ~~~" })
6376
expect(actual.fn).toBe("~~~ hello() ~~~")
6477
expect(actual.anonymous).toBe("~~~ anonymous function ~~~")
78+
expect(actual.bigInt).toBe("1212")
6579
})

0 commit comments

Comments
 (0)