import { MessageHeader } from './MessageHeader' ; import { toB64 } from '../Helpers' ; /**
 * An ADB Message. Contains a  MessageHeader and an optional  DataView with the
 * data for the message.
  export class Message { constructor ( readonly header , readonly data ? ) { } /**
     * Returns the data content as a  string or  null if data is not available.
     *  returns { string | null } a  string or  null if data is not available.
      dataAsString ( ) { if ( ! this . data ) { return null ; } const textDecoder = new TextDecoder ( ) ; return textDecoder . decode ( this . data ) ; } /**
     * Creates a new Message. See  MessageHeader .
     *  param { string } cmd param { number } arg0 param { number } arg1 param { boolean } useChecksum param { DataView } data returns { Message } static newMessage ( cmd , arg0 , arg1 , useChecksum , data ? ) { let checksum = 0 ; let byteLength = 0 ; if ( data ) { byteLength = data . byteLength ; if ( useChecksum ) { checksum = Message . checksum ( data ) ; } } const header = new MessageHeader ( cmd , arg0 , arg1 , byteLength , checksum ) ; return new Message ( header , data ) ; } param { number } localId param { number } remoteId param { string } service param { boolean } useChecksum returns { Message } static open ( localId , remoteId , service , useChecksum ) { const encoder = new TextEncoder ( ) ; const data = new DataView ( encoder . encode ( '' + service + '\0' ) . buffer ) ; return Message . newMessage ( 'OPEN' , localId , remoteId , useChecksum , data ) ; } param { number } version param { number } maxPayload param { string } banner param { boolean } useChecksum returns { Message } static cnxn ( version , maxPayload , banner , useChecksum ) { const encoder = new TextEncoder ( ) ; const data = new DataView ( encoder . encode ( banner ) . buffer ) ; return Message . newMessage ( 'CNXN' , version , maxPayload , useChecksum , data ) ; } param { DataView } signedToken param { boolean } useChecksum returns { Message } static authSignature ( signedToken , useChecksum ) { return Message . newMessage ( 'AUTH' , 2 , 0 , useChecksum , signedToken ) ; } param { DataView } publicKey param { boolean } useChecksum returns { Message } static authPublicKey ( publicKey , useChecksum ) { const textEncoder = new TextEncoder ( ) ; const data = textEncoder . encode ( toB64 ( publicKey . buffer ) + '\0' ) ; return Message . newMessage ( 'AUTH' , 3 , 0 , useChecksum , new DataView ( data . buffer ) ) ; } private static checksum ( dataView ) { let sum = 0 ; for ( let i = 0 ; i < dataView . byteLength ; i ++ ) { sum += dataView . getUint8 ( i ) ; } return sum & 0xffffffff ; } }