@@ -7,6 +7,10 @@ import type { ExtData } from "./ExtData";
7
7
export const DEFAULT_MAX_DEPTH = 100 ;
8
8
export const DEFAULT_INITIAL_BUFFER_SIZE = 2048 ;
9
9
10
+ const hastoJSON = ( value : unknown ) : value is { toJSON : unknown } => {
11
+ return typeof value === 'object' && value !== null && 'toJSON' in value ;
12
+ } ;
13
+
10
14
export class Encoder < ContextType = undefined > {
11
15
private pos = 0 ;
12
16
private view = new DataView ( new ArrayBuffer ( this . initialBufferSize ) ) ;
@@ -187,14 +191,19 @@ export class Encoder<ContextType = undefined> {
187
191
private encodeObject ( object : unknown , depth : number ) {
188
192
// try to encode objects with custom codec first of non-primitives
189
193
const ext = this . extensionCodec . tryToEncode ( object , this . context ) ;
194
+
190
195
if ( ext != null ) {
191
196
this . encodeExtension ( ext ) ;
192
197
} else if ( Array . isArray ( object ) ) {
193
198
this . encodeArray ( object , depth ) ;
194
199
} else if ( ArrayBuffer . isView ( object ) ) {
195
200
this . encodeBinary ( object ) ;
196
201
} else if ( typeof object === "object" ) {
197
- this . encodeMap ( object as Record < string , unknown > , depth ) ;
202
+ if ( hastoJSON ( object ) && typeof object . toJSON === "function" ) {
203
+ this . doEncode ( object . toJSON ( ) , depth ) ;
204
+ } else {
205
+ this . encodeMap ( object as Record < string , unknown > , depth ) ;
206
+ }
198
207
} else {
199
208
// symbol, function and other special object come here unless extensionCodec handles them.
200
209
throw new Error ( `Unrecognized object: ${ Object . prototype . toString . apply ( object ) } ` ) ;
0 commit comments