import {compose, EventEmitter} from '@avocado/core'; import {packetFromId} from './registry'; /** * Packet types (see https://github.com/socketio/socket.io-protocol) */ const TYPES = { EVENT: 2, ERROR: 4, BINARY_EVENT: 5, }; class Encoder { encode(packet, callback) { switch (packet.type) { case TYPES.EVENT: case TYPES.BINARY_EVENT: return callback([this.pack(packet)]); default: return callback([JSON.stringify(packet)]); } } pack(packet) { const packetId = packet.data[0]; const Packet = packetFromId(packetId); return Packet.pack(packet); } } const decorateDecoder = compose( EventEmitter, ); class Decoder extends decorateDecoder(class {}) { add(obj) { if (typeof obj === 'string') { this.parseJSON(obj); } else { this.parseBinary(obj); } } destroy() {} parseBinary(packet) { const view = new Uint8Array(packet); const packetId = view[0]; const Packet = packetFromId(packetId); const data = Packet.unpack(packet); this.emit('decoded', { type: TYPES.EVENT, data: [packetId, data], nsp: '/', }); } parseJSON(obj) { let decoded; try { decoded = JSON.parse(obj); } catch (e) { decoded = errorPacket; } this.emit('decoded', decoded); } } export {Decoder, Encoder};