Repository navigation
feat: add opt-in bigint option to parse - #408
Conversation
jordanbtucker
left a comment
There was a problem hiding this comment.
Thanks, this is clean and well tested. I ran the edge cases (±2^53 in decimal and hex, signs, -0/-0x0, exponents, .5, Infinity/NaN, very long literals) and the benchmark, and the default path is unchanged.
On the design question: let's keep unsafe-only. With the option on, {port: 8080} should still give you a number. Making every integer a BigInt would make the option painful for ordinary config, and it's the same trade-off json-bigint made with its opt-in alwaysParseAsBig. People who need predictable types per field will be able to use the reviver source from #386 ((k, v, {source}) => k === 'id' ? BigInt(source) : v), which matches native JSON.parse. Since a non-boolean bigint throws, we can still add something like bigint: 'all' later without a breaking change.
One wording suggestion inline. Also a heads-up that #386 touches the top of parse() and index.d.ts too, so one of the two will need a small rebase.
|
Applied both wording suggestions in 5426cdb: the README and the Agreed on keeping it unsafe-only. The code is unchanged, and On the overlap with #386: happy to rebase this one once #386 lands.
|
|
Thanks! Looks good. I'll merge this first, so no need to wait on #386. |
Closes #292. Follow-up to #370 as discussed there; the
stringifyside was settled in #372.parseaccepts an options object, either as the third argument after the reviver or as the second argument in its place:With
bigint: true, integer literals outside the safe integer range (decimal and hexadecimal, with or without a sign) are returned as BigInts. Safe integers and non-integer literals (fractions, exponents,Infinity,NaN) are still numbers, so existing documents keep parsing to the same values and only the lossy cases change type. Without the option nothing changes.Option handling follows
stringify:null/undefinedmeans the default, a non-boolean value throws aTypeError, and an array in the reviver position is not treated as options.stringifythrows on BigInts since #372, so the README points to a replacer (typeof value === 'bigint' ? String(value) : value) for the way back.Includes types (
ParseOptions, twoparseoverloads), tests for the boundaries at ±2^53, hex, signs, nested values, reviver interplay and option validation, README and CHANGELOG entries.npm testpasses with 100% coverage,npm run test-typesandnpm run lintpass.One design choice worth a look: the type of a parsed value depends on its magnitude (
[1, 9007199254740993]gives[number, bigint]). That keeps the option non-breaking for safe integers, which is what #292 asks for. If you would rather have every integer literal become a BigInt when the option is on, that is a one-line change inintegerLiteral()and I will adjust.