const NF_JSON = 0x00 ; const NF_RAW = 0x02 ; const NF_UTF8 = 0x04 ; const NF_MASK = 0xff ; const NF_UNKNOWN = 0x100 ; const CF_NONE = 0x00 << 24 ; const CF_PRIVATE = 0x01 << 24 ; const CF_JSON = 0x02 << 24 ; const CF_RAW = 0x03 << 24 ; const CF_UTF8 = 0x04 << 24 ; const CF_MASK = 0xff << 24 ; category export interface Transcoder { param value encode ( value ) : [ Buffer , number ] ; param bytes param flags decode ( bytes , flags ) : any ; } category export class DefaultTranscoder implements Transcoder { param value encode ( value ) { if ( Buffer . isBuffer ( value ) ) { return [ value , CF_RAW | NF_RAW ] ; } if ( typeof value === 'string' ) { return [ Buffer . from ( value ) , CF_UTF8 | NF_UTF8 ] ; } return [ Buffer . from ( JSON . stringify ( value ) ) , CF_JSON | NF_JSON ] ; } param bytes param flags decode ( bytes , flags ) { let format = flags & NF_MASK ; const cfformat = flags & CF_MASK ; if ( cfformat !== CF_NONE ) { if ( cfformat === CF_JSON ) { format = NF_JSON ; } else if ( cfformat === CF_RAW ) { format = NF_RAW ; } else if ( cfformat === CF_UTF8 ) { format = NF_UTF8 ; } else if ( cfformat !== CF_PRIVATE ) { format = NF_UNKNOWN ; } } if ( format === NF_UTF8 ) { return bytes . toString ( 'utf8' ) ; } else if ( format === NF_RAW ) { return bytes ; } else if ( format === NF_JSON ) { try { return JSON . parse ( bytes . toString ( 'utf8' ) ) ; } catch ( e ) { return bytes ; } } return bytes ; } }