@@ -77,16 +77,6 @@ function visit(
77
77
) : Primitive | ObjOrArray < unknown > {
78
78
const [ memoize , unmemoize ] = memo ;
79
79
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
-
90
80
// Get the simple cases out of the way first
91
81
if ( value === null || ( [ 'number' , 'boolean' , 'string' ] . includes ( typeof value ) && ! isNaN ( value ) ) ) {
92
82
return value as Primitive ;
@@ -120,6 +110,18 @@ function visit(
120
110
return '[Circular ~]' ;
121
111
}
122
112
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
+
123
125
// 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
124
126
// because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each
125
127
// property/entry, and keep track of the number of items we add to it.
0 commit comments