import * as ByteBuffer from 'bytebuffer' ; import { Type , Message , Field } from 'protobufjs/light' ; import { isPrimitiveField } from '../../utils/protobuf' ; const transform = ( field , value ) => { if ( field . optional && typeof value === 'undefined' ) { return null ; } if ( field . type === 'bytes' ) { return ByteBuffer . wrap ( value ) . toString ( 'hex' ) ; } if ( field . long ) { if ( Number . isSafeInteger ( value . toNumber ( ) ) ) { return value . toNumber ( ) ; } return value . toString ( ) ; } return value ; } ; function messageToJSON ( Message , fields ) { const { ... message } = Message ; const res = { } ; Object . keys ( fields ) . forEach ( key => { const field = fields [ key ] ; const value = message [ key ] ; if ( field . repeated ) { if ( isPrimitiveField ( field . type ) ) { res [ key ] = value . map ( ( v ) => transform ( field , v ) ) ; } else if ( 'valuesById' in field . resolvedType ! ) { res [ key ] = value ; } else if ( 'fields' in field . resolvedType ! ) { res [ key ] = value . map ( ( v ) => messageToJSON ( v , ( field . resolvedType as Type ) . fields ) ) ; } else { throw new Error ( `case not handled for repeated key: ${ key }` ) ; } } else if ( isPrimitiveField ( field . type ) ) { res [ key ] = transform ( field , value ) ; } else if ( 'valuesById' in field . resolvedType ! ) { res [ key ] = field . resolvedType . valuesById [ value ] ; } else if ( field . resolvedType ! . fields ) { res [ key ] = messageToJSON ( value , field . resolvedType ! . fields ) ; } else { throw new Error ( `case not handled: ${ key }` ) ; } } ) ; return res ; } export const decode = ( Message , data ) => { const buff = data . toBuffer ( ) ; const a = new Uint8Array ( buff ) ; const decoded = Message . decode ( a ) ; return messageToJSON ( decoded , decoded . $type . fields ) ; } ;