avocado-old/packages/net/packet/socket.io-parser.js
2020-06-17 04:35:59 -05:00

78 lines
1.5 KiB
JavaScript

import {compose, deflate, EventEmitter, inflate} from '@avocado/core';
/**
* 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 {fromId} = require('./packets.scwp');
const packetId = packet.data[0];
const {default: Packet} = fromId(packetId);
return deflate(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 {fromId} = require('./packets.scwp');
packet = inflate(Buffer.from(packet));
const view = new Uint8Array(packet);
const packetId = view[0];
const {default: Packet} = fromId(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};