robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
0abc9ccc19
master
1if ( typeof msgpackr === 'undefined' ) { 2throw new Error ( 3'msgpackr library not loaded. ' + 4'Check that the script tag for msgpackr is present and loads correctly.' 5); 6} 7 8// Buffer/Window/Tabpage handles come back as msgpack EXT values. 9// - Type code: not fixed across builds, so read it from 10// nvim_get_api_info()'s types metadata at runtime instead of 11// hardcoding it. 12// - Payload: itself a variable length msgpack integer, 13// so it needs a real unpack call, not a fixed width DataView read. 14function registerNvimHandleTypes ( types ) { 15for ( const [ name , info ] of Object . entries ( types )) { 16msgpackr . addExtension ({ 17type :info . id , 18unpack ( payload ) { 19return { __nvimType :name , id :msgpackr . unpack ( payload ) }; 20}, 21pack ( value ) { 22return msgpackr . pack ( value . id ); 23}, 24}); 25console . log ( `[msgpack] registered Nvim EXT type ${ info . id } -> ${ name } ` ); 26} 27} 28 29const MsgpackCodec = { 30encode ( value ) { 31const encoded = msgpackr . pack ( value ); 32const prefix = Array . from ( encoded . slice ( 0 , Math . min ( encoded . length , 8 ))) 33. map ( b => b . toString ( 16 ). padStart ( 2 , '0' )) 34. join ( ' ' ); 35console . log ( `[MsgpackCodec.encode] ${ encoded . length } bytes, prefix: ${ prefix } ` ); 36return encoded ; 37}, 38 39decodeMultiple ( bytes ) { 40const messages = []; 41let consumed = 0 ; 42 43try { 44msgpackr . unpackMultiple ( bytes , ( value , start , end ) => { 45messages . push ( value ); 46consumed = end ; 47}); 48consumed = bytes . length ; 49} catch ( e ) { 50if ( ! isIncompleteDataError ( e )) { 51console . error ( '[MsgpackCodec.decodeMultiple] fatal decode error' , e , 'consumed so far:' , consumed ); 52throw e ; 53} 54} 55 56return { messages, consumed}; 57}, 58}; 59 60function isIncompleteDataError ( e ) { 61return / unexpected end | incomplete | out of bounds | out of range / i . test ( e ?. message || '' ); 62}