@@ -77,16 +77,6 @@ function visit(
7777) : Primitive | ObjOrArray < unknown > {
7878 const [ memoize , unmemoize ] = memo ;
7979
80- // If the value has a `toJSON` method, see if we can bail and let it do the work
81- const valueWithToJSON = value as unknown & { toJSON ?: ( ) => Primitive | ObjOrArray < unknown > } ;
82- if ( valueWithToJSON && typeof valueWithToJSON . toJSON === 'function' ) {
83- try {
84- return valueWithToJSON . toJSON ( ) ;
85- } catch ( err ) {
86- // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)
87- }
88- }
89-
9080 // Get the simple cases out of the way first
9181 if ( value === null || ( [ 'number' , 'boolean' , 'string' ] . includes ( typeof value ) && ! isNaN ( value ) ) ) {
9282 return value as Primitive ;
@@ -120,6 +110,18 @@ function visit(
120110 return '[Circular ~]' ;
121111 }
122112
113+ // If the value has a `toJSON` method, we call it to extract more information
114+ const valueWithToJSON = value as unknown & { toJSON ?: ( ) => unknown } ;
115+ if ( valueWithToJSON && typeof valueWithToJSON . toJSON === 'function' ) {
116+ try {
117+ const jsonValue = valueWithToJSON . toJSON ( ) ;
118+ // We need to normalize the return value of `.toJSON()` in case it has circular references
119+ return visit ( '' , jsonValue , depth - 1 , maxProperties , memo ) ;
120+ } catch ( err ) {
121+ // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)
122+ }
123+ }
124+
123125 // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse
124126 // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each
125127 // property/entry, and keep track of the number of items we add to it.
0 commit comments