feat: 同步 socket.io 上游代码

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
2023-02-09 13:49:48 +08:00
parent 359aeb9d63
commit 7b85ff5b7c
35 changed files with 7612 additions and 6519 deletions

View File

@@ -1,4 +1,4 @@
import { isBinary } from "./is-binary.js"
import { isBinary } from "./is-binary.js";
/**
* Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
@@ -9,37 +9,37 @@ import { isBinary } from "./is-binary.js"
*/
export function deconstructPacket(packet) {
const buffers = []
const packetData = packet.data
const pack = packet
pack.data = _deconstructPacket(packetData, buffers)
pack.attachments = buffers.length // number of binary 'attachments'
return { packet: pack, buffers: buffers }
const buffers = [];
const packetData = packet.data;
const pack = packet;
pack.data = _deconstructPacket(packetData, buffers);
pack.attachments = buffers.length; // number of binary 'attachments'
return { packet: pack, buffers: buffers };
}
function _deconstructPacket(data, buffers) {
if (!data) return data
if (!data) return data;
if (isBinary(data)) {
const placeholder = { _placeholder: true, num: buffers.length }
buffers.push(data)
return placeholder
} else if (Array.isArray(data)) {
const newData = new Array(data.length)
for (let i = 0; i < data.length; i++) {
newData[i] = _deconstructPacket(data[i], buffers)
}
return newData
} else if (typeof data === "object" && !(data instanceof Date)) {
const newData = {}
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
newData[key] = _deconstructPacket(data[key], buffers)
}
}
return newData
if (isBinary(data)) {
const placeholder = { _placeholder: true, num: buffers.length };
buffers.push(data);
return placeholder;
} else if (Array.isArray(data)) {
const newData = new Array(data.length);
for (let i = 0; i < data.length; i++) {
newData[i] = _deconstructPacket(data[i], buffers);
}
return data
return newData;
} else if (typeof data === "object" && !(data instanceof Date)) {
const newData = {};
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
newData[key] = _deconstructPacket(data[key], buffers);
}
}
return newData;
}
return data;
}
/**
@@ -52,35 +52,35 @@ function _deconstructPacket(data, buffers) {
*/
export function reconstructPacket(packet, buffers) {
packet.data = _reconstructPacket(packet.data, buffers)
packet.attachments = undefined // no longer useful
return packet
packet.data = _reconstructPacket(packet.data, buffers);
delete packet.attachments; // no longer useful
return packet;
}
function _reconstructPacket(data, buffers) {
if (!data) return data
if (!data) return data;
if (data && data._placeholder === true) {
const isIndexValid =
typeof data.num === "number" &&
data.num >= 0 &&
data.num < buffers.length
if (isIndexValid) {
return buffers[data.num] // appropriate buffer (should be natural order anyway)
} else {
throw new Error("illegal attachments")
}
} else if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
data[i] = _reconstructPacket(data[i], buffers)
}
} else if (typeof data === "object") {
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
data[key] = _reconstructPacket(data[key], buffers)
}
}
if (data && data._placeholder === true) {
const isIndexValid =
typeof data.num === "number" &&
data.num >= 0 &&
data.num < buffers.length;
if (isIndexValid) {
return buffers[data.num]; // appropriate buffer (should be natural order anyway)
} else {
throw new Error("illegal attachments");
}
} else if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
data[i] = _reconstructPacket(data[i], buffers);
}
} else if (typeof data === "object") {
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
data[key] = _reconstructPacket(data[key], buffers);
}
}
}
return data
return data;
}

View File

@@ -1,10 +1,9 @@
import { Emitter } from "@socket.io/component-emitter"
import { deconstructPacket, reconstructPacket } from "./binary.js"
import { isBinary, hasBinary } from "./is-binary.js"
import { Emitter } from "@socket.io/component-emitter";
import { deconstructPacket, reconstructPacket } from "./binary.js";
import { isBinary, hasBinary } from "./is-binary.js";
// import debugModule from "debug" // debug()
// const debug = debugModule("socket.io-parser") // debug()
const debug = require("../debug")("socket.io-client")
const debug = require("../debug")("socket.io-parser");
/**
* Protocol version.
@@ -12,24 +11,24 @@ const debug = require("../debug")("socket.io-client")
* @public
*/
export const protocol: number = 5
export const protocol: number = 5;
export enum PacketType {
CONNECT,
DISCONNECT,
EVENT,
ACK,
CONNECT_ERROR,
BINARY_EVENT,
BINARY_ACK,
CONNECT,
DISCONNECT,
EVENT,
ACK,
CONNECT_ERROR,
BINARY_EVENT,
BINARY_ACK,
}
export interface Packet {
type: PacketType
nsp: string
data?: any
id?: number
attachments?: number
type: PacketType;
nsp: string;
data?: any;
id?: number;
attachments?: number;
}
/**
@@ -37,87 +36,91 @@ export interface Packet {
*/
export class Encoder {
/**
* Encoder constructor
*
* @param {function} replacer - custom replacer to pass down to JSON.parse
*/
constructor(private replacer?: (this: any, key: string, value: any) => any) { }
/**
* Encode a packet as a single string if non-binary, or as a
* buffer sequence, depending on packet type.
*
* @param {Object} obj - packet object
*/
public encode(obj: Packet) {
debug("encoding packet %j", obj)
/**
* Encoder constructor
*
* @param {function} replacer - custom replacer to pass down to JSON.parse
*/
constructor(private replacer?: (this: any, key: string, value: any) => any) {}
/**
* Encode a packet as a single string if non-binary, or as a
* buffer sequence, depending on packet type.
*
* @param {Object} obj - packet object
*/
public encode(obj: Packet) {
debug("encoding packet %j", obj);
if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
if (hasBinary(obj)) {
obj.type =
obj.type === PacketType.EVENT
? PacketType.BINARY_EVENT
: PacketType.BINARY_ACK
return this.encodeAsBinary(obj)
}
}
return [this.encodeAsString(obj)]
if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
if (hasBinary(obj)) {
return this.encodeAsBinary({
type:
obj.type === PacketType.EVENT
? PacketType.BINARY_EVENT
: PacketType.BINARY_ACK,
nsp: obj.nsp,
data: obj.data,
id: obj.id,
});
}
}
return [this.encodeAsString(obj)];
}
/**
* Encode packet as string.
*/
private encodeAsString(obj: Packet) {
// first is type
let str = "" + obj.type;
// attachments if we have them
if (
obj.type === PacketType.BINARY_EVENT ||
obj.type === PacketType.BINARY_ACK
) {
str += obj.attachments + "-";
}
/**
* Encode packet as string.
*/
private encodeAsString(obj: Packet) {
// first is type
let str = "" + obj.type
// attachments if we have them
if (
obj.type === PacketType.BINARY_EVENT ||
obj.type === PacketType.BINARY_ACK
) {
str += obj.attachments + "-"
}
// if we have a namespace other than `/`
// we append it followed by a comma `,`
if (obj.nsp && "/" !== obj.nsp) {
str += obj.nsp + ","
}
// immediately followed by the id
if (null != obj.id) {
str += obj.id
}
// json data
if (null != obj.data) {
str += JSON.stringify(obj.data, this.replacer)
}
debug("encoded %j as %s", obj, str)
return str
// if we have a namespace other than `/`
// we append it followed by a comma `,`
if (obj.nsp && "/" !== obj.nsp) {
str += obj.nsp + ",";
}
/**
* Encode packet as 'buffer sequence' by removing blobs, and
* deconstructing packet into object with placeholders and
* a list of buffers.
*/
private encodeAsBinary(obj: Packet) {
const deconstruction = deconstructPacket(obj)
const pack = this.encodeAsString(deconstruction.packet)
const buffers = deconstruction.buffers
buffers.unshift(pack) // add packet info to beginning of data list
return buffers // write all the buffers
// immediately followed by the id
if (null != obj.id) {
str += obj.id;
}
// json data
if (null != obj.data) {
str += JSON.stringify(obj.data, this.replacer);
}
debug("encoded %j as %s", obj, str);
return str;
}
/**
* Encode packet as 'buffer sequence' by removing blobs, and
* deconstructing packet into object with placeholders and
* a list of buffers.
*/
private encodeAsBinary(obj: Packet) {
const deconstruction = deconstructPacket(obj);
const pack = this.encodeAsString(deconstruction.packet);
const buffers = deconstruction.buffers;
buffers.unshift(pack); // add packet info to beginning of data list
return buffers; // write all the buffers
}
}
interface DecoderReservedEvents {
decoded: (packet: Packet) => void
decoded: (packet: Packet) => void;
}
/**
@@ -126,168 +129,168 @@ interface DecoderReservedEvents {
* @return {Object} decoder
*/
export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> {
private reconstructor: BinaryReconstructor
private reconstructor: BinaryReconstructor;
/**
* Decoder constructor
*
* @param {function} reviver - custom reviver to pass down to JSON.stringify
*/
constructor(private reviver?: (this: any, key: string, value: any) => any) {
super()
/**
* Decoder constructor
*
* @param {function} reviver - custom reviver to pass down to JSON.stringify
*/
constructor(private reviver?: (this: any, key: string, value: any) => any) {
super();
}
/**
* Decodes an encoded packet string into packet JSON.
*
* @param {String} obj - encoded packet
*/
public add(obj: any) {
let packet;
if (typeof obj === "string") {
if (this.reconstructor) {
throw new Error("got plaintext data when reconstructing a packet");
}
packet = this.decodeString(obj);
const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
// binary packet's json
this.reconstructor = new BinaryReconstructor(packet);
// no attachments, labeled binary but no binary data to follow
if (packet.attachments === 0) {
super.emitReserved("decoded", packet);
}
} else {
// non-binary full packet
super.emitReserved("decoded", packet);
}
} else if (isBinary(obj) || obj.base64) {
// raw binary data
if (!this.reconstructor) {
throw new Error("got binary data when not reconstructing a packet");
} else {
packet = this.reconstructor.takeBinaryData(obj);
if (packet) {
// received final buffer
this.reconstructor = null;
super.emitReserved("decoded", packet);
}
}
} else {
throw new Error("Unknown type: " + obj);
}
}
/**
* Decode a packet String (JSON data)
*
* @param {String} str
* @return {Object} packet
*/
private decodeString(str): Packet {
let i = 0;
// look up type
const p: any = {
type: Number(str.charAt(0)),
};
if (PacketType[p.type] === undefined) {
throw new Error("unknown packet type " + p.type);
}
/**
* Decodes an encoded packet string into packet JSON.
*
* @param {String} obj - encoded packet
*/
public add(obj: any) {
let packet
if (typeof obj === "string") {
if (this.reconstructor) {
throw new Error("got plaintext data when reconstructing a packet")
}
packet = this.decodeString(obj)
if (
packet.type === PacketType.BINARY_EVENT ||
packet.type === PacketType.BINARY_ACK
) {
// binary packet's json
this.reconstructor = new BinaryReconstructor(packet)
// no attachments, labeled binary but no binary data to follow
if (packet.attachments === 0) {
super.emitReserved("decoded", packet)
}
} else {
// non-binary full packet
super.emitReserved("decoded", packet)
}
} else if (isBinary(obj) || obj.base64) {
// raw binary data
if (!this.reconstructor) {
throw new Error("got binary data when not reconstructing a packet")
} else {
packet = this.reconstructor.takeBinaryData(obj)
if (packet) {
// received final buffer
this.reconstructor = null
super.emitReserved("decoded", packet)
}
}
} else {
throw new Error("Unknown type: " + obj)
}
// look up attachments if type binary
if (
p.type === PacketType.BINARY_EVENT ||
p.type === PacketType.BINARY_ACK
) {
const start = i + 1;
while (str.charAt(++i) !== "-" && i != str.length) {}
const buf = str.substring(start, i);
if (buf != Number(buf) || str.charAt(i) !== "-") {
throw new Error("Illegal attachments");
}
p.attachments = Number(buf);
}
/**
* Decode a packet String (JSON data)
*
* @param {String} str
* @return {Object} packet
*/
private decodeString(str): Packet {
let i = 0
// look up type
const p: any = {
type: Number(str.charAt(0)),
}
if (PacketType[p.type] === undefined) {
throw new Error("unknown packet type " + p.type)
}
// look up attachments if type binary
if (
p.type === PacketType.BINARY_EVENT ||
p.type === PacketType.BINARY_ACK
) {
const start = i + 1
while (str.charAt(++i) !== "-" && i != str.length) { }
const buf = str.substring(start, i)
if (buf != Number(buf) || str.charAt(i) !== "-") {
throw new Error("Illegal attachments")
}
p.attachments = Number(buf)
}
// look up namespace (if any)
if ("/" === str.charAt(i + 1)) {
const start = i + 1
while (++i) {
const c = str.charAt(i)
if ("," === c) break
if (i === str.length) break
}
p.nsp = str.substring(start, i)
} else {
p.nsp = "/"
}
// look up id
const next = str.charAt(i + 1)
if ("" !== next && Number(next) == next) {
const start = i + 1
while (++i) {
const c = str.charAt(i)
if (null == c || Number(c) != c) {
--i
break
}
if (i === str.length) break
}
p.id = Number(str.substring(start, i + 1))
}
// look up json data
if (str.charAt(++i)) {
const payload = this.tryParse(str.substr(i))
if (Decoder.isPayloadValid(p.type, payload)) {
p.data = payload
} else {
throw new Error("invalid payload")
}
}
debug("decoded %s as %j", str, p)
return p
// look up namespace (if any)
if ("/" === str.charAt(i + 1)) {
const start = i + 1;
while (++i) {
const c = str.charAt(i);
if ("," === c) break;
if (i === str.length) break;
}
p.nsp = str.substring(start, i);
} else {
p.nsp = "/";
}
private tryParse(str) {
try {
return JSON.parse(str, this.reviver)
} catch (e) {
return false
// look up id
const next = str.charAt(i + 1);
if ("" !== next && Number(next) == next) {
const start = i + 1;
while (++i) {
const c = str.charAt(i);
if (null == c || Number(c) != c) {
--i;
break;
}
if (i === str.length) break;
}
p.id = Number(str.substring(start, i + 1));
}
private static isPayloadValid(type: PacketType, payload: any): boolean {
switch (type) {
case PacketType.CONNECT:
return typeof payload === "object"
case PacketType.DISCONNECT:
return payload === undefined
case PacketType.CONNECT_ERROR:
return typeof payload === "string" || typeof payload === "object"
case PacketType.EVENT:
case PacketType.BINARY_EVENT:
return Array.isArray(payload) && payload.length > 0
case PacketType.ACK:
case PacketType.BINARY_ACK:
return Array.isArray(payload)
}
// look up json data
if (str.charAt(++i)) {
const payload = this.tryParse(str.substr(i));
if (Decoder.isPayloadValid(p.type, payload)) {
p.data = payload;
} else {
throw new Error("invalid payload");
}
}
/**
* Deallocates a parser's resources
*/
public destroy() {
if (this.reconstructor) {
this.reconstructor.finishedReconstruction()
}
debug("decoded %s as %j", str, p);
return p;
}
private tryParse(str) {
try {
return JSON.parse(str, this.reviver);
} catch (e) {
return false;
}
}
private static isPayloadValid(type: PacketType, payload: any): boolean {
switch (type) {
case PacketType.CONNECT:
return typeof payload === "object";
case PacketType.DISCONNECT:
return payload === undefined;
case PacketType.CONNECT_ERROR:
return typeof payload === "string" || typeof payload === "object";
case PacketType.EVENT:
case PacketType.BINARY_EVENT:
return Array.isArray(payload) && payload.length > 0;
case PacketType.ACK:
case PacketType.BINARY_ACK:
return Array.isArray(payload);
}
}
/**
* Deallocates a parser's resources
*/
public destroy() {
if (this.reconstructor) {
this.reconstructor.finishedReconstruction();
this.reconstructor = null;
}
}
}
/**
@@ -300,37 +303,37 @@ export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> {
*/
class BinaryReconstructor {
private reconPack
private buffers: Array<Buffer | ArrayBuffer> = [];
private reconPack;
private buffers: Array<Buffer | ArrayBuffer> = [];
constructor(readonly packet: Packet) {
this.reconPack = packet
}
constructor(readonly packet: Packet) {
this.reconPack = packet;
}
/**
* Method to be called when binary data received from connection
* after a BINARY_EVENT packet.
*
* @param {Buffer | ArrayBuffer} binData - the raw binary data received
* @return {null | Object} returns null if more binary data is expected or
* a reconstructed packet object if all buffers have been received.
*/
public takeBinaryData(binData) {
this.buffers.push(binData)
if (this.buffers.length === this.reconPack.attachments) {
// done with buffer list
const packet = reconstructPacket(this.reconPack, this.buffers)
this.finishedReconstruction()
return packet
}
return null
/**
* Method to be called when binary data received from connection
* after a BINARY_EVENT packet.
*
* @param {Buffer | ArrayBuffer} binData - the raw binary data received
* @return {null | Object} returns null if more binary data is expected or
* a reconstructed packet object if all buffers have been received.
*/
public takeBinaryData(binData) {
this.buffers.push(binData);
if (this.buffers.length === this.reconPack.attachments) {
// done with buffer list
const packet = reconstructPacket(this.reconPack, this.buffers);
this.finishedReconstruction();
return packet;
}
return null;
}
/**
* Cleans up binary packet reconstruction variables.
*/
public finishedReconstruction() {
this.reconPack = null
this.buffers = []
}
/**
* Cleans up binary packet reconstruction variables.
*/
public finishedReconstruction() {
this.reconPack = null;
this.buffers = [];
}
}

View File

@@ -1,20 +1,20 @@
const withNativeArrayBuffer: boolean = typeof ArrayBuffer === "function"
const withNativeArrayBuffer: boolean = typeof ArrayBuffer === "function";
const isView = (obj: any) => {
return typeof ArrayBuffer.isView === "function"
? ArrayBuffer.isView(obj)
: obj.buffer instanceof ArrayBuffer
}
return typeof ArrayBuffer.isView === "function"
? ArrayBuffer.isView(obj)
: obj.buffer instanceof ArrayBuffer;
};
const toString = Object.prototype.toString
const toString = Object.prototype.toString;
const withNativeBlob =
typeof Blob === "function" ||
(typeof Blob !== "undefined" &&
toString.call(Blob) === "[object BlobConstructor]")
typeof Blob === "function" ||
(typeof Blob !== "undefined" &&
toString.call(Blob) === "[object BlobConstructor]");
const withNativeFile =
typeof File === "function" ||
(typeof File !== "undefined" &&
toString.call(File) === "[object FileConstructor]")
typeof File === "function" ||
(typeof File !== "undefined" &&
toString.call(File) === "[object FileConstructor]");
/**
* Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
@@ -23,44 +23,44 @@ const withNativeFile =
*/
export function isBinary(obj: any) {
return (
(withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||
(withNativeBlob && obj instanceof Blob) ||
(withNativeFile && obj instanceof File)
)
return (
(withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||
(withNativeBlob && obj instanceof Blob) ||
(withNativeFile && obj instanceof File)
);
}
export function hasBinary(obj: any, toJSON?: boolean) {
if (!obj || typeof obj !== "object") {
return false
}
if (!obj || typeof obj !== "object") {
return false;
}
if (Array.isArray(obj)) {
for (let i = 0, l = obj.length; i < l; i++) {
if (hasBinary(obj[i])) {
return true
}
}
return false
if (Array.isArray(obj)) {
for (let i = 0, l = obj.length; i < l; i++) {
if (hasBinary(obj[i])) {
return true;
}
}
return false;
}
if (isBinary(obj)) {
return true
if (isBinary(obj)) {
return true;
}
if (
obj.toJSON &&
typeof obj.toJSON === "function" &&
arguments.length === 1
) {
return hasBinary(obj.toJSON(), true);
}
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
return true;
}
}
if (
obj.toJSON &&
typeof obj.toJSON === "function" &&
arguments.length === 1
) {
return hasBinary(obj.toJSON(), true)
}
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
return true
}
}
return false
return false;
}