import { Transport } from '../../lib/transport' ; import { Message } from '../../lib/message' ; import * as fs from 'fs' ; export class MockTransport implements Transport { receivedData : DataView [ ] = [ ] ; pendingData : ArrayBuffer = new ArrayBuffer ( 0 ) ; pos = 0 ; reject ? : ( reason : Error ) => void ; async pushFromFile ( fileName ) { const textEncoder = new TextEncoder ( ) ; const messages = JSON . parse ( await fs . promises . readFile ( fileName , { encoding : "utf-8" } ) ) ; for ( const jsonMessage of messages ) { const cmd = jsonMessage . cmd ; const arg0 = jsonMessage . arg0 ; const arg1 = jsonMessage . arg1 ; const data = jsonMessage . data ? new DataView ( textEncoder . encode ( jsonMessage . data ) . buffer ) : jsonMessage . data ; const useChecksum = ! ! jsonMessage . useChecksum ; this . pushMessage ( Message . newMessage ( cmd , arg0 , arg1 , useChecksum , data ) ) ; } } pushData ( data ) { const buffer = data . buffer ; const tmp = new Uint8Array ( this . pendingData . byteLength + buffer . byteLength ) ; tmp . set ( new Uint8Array ( this . pendingData ) , 0 ) ; tmp . set ( new Uint8Array ( buffer ) , this . pendingData . byteLength ) ; this . pendingData = tmp . buffer ; } pushMessage ( msg ) { this . pushData ( msg . header . toDataView ( ) ) ; if ( msg . data ) { this . pushData ( msg . data ) ; } } async read ( len ) { if ( this . pendingData . byteLength - this . pos < len ) { return new Promise ( ( _ , reject ) => { this . reject = reject ; } ) ; } const dataView = new DataView ( this . pendingData , this . pos , len ) ; this . pos += len ; return dataView ; } async write ( data ) { this . receivedData . push ( new DataView ( data ) ) ; return Promise . resolve ( ) ; } close ( ) { if ( this . reject ) { this . reject ( new Error ( 'Transport Closed' ) ) ; } } }