Updated script that can be controled by Nodejs web app

This commit is contained in:
mac OS
2024-11-25 12:24:18 +07:00
parent c440eda1f4
commit 8b0ab2bd3a
8662 changed files with 1803808 additions and 34 deletions

View File

@ -0,0 +1,2 @@
import { io } from "./index.js";
export default io;

View File

@ -0,0 +1,2 @@
import { io } from "./index.js";
export default io;

View File

@ -0,0 +1,12 @@
/**
* Initialize backoff timer with `opts`.
*
* - `min` initial timeout in milliseconds [100]
* - `max` max timeout [10000]
* - `jitter` [0]
* - `factor` [2]
*
* @param {Object} opts
* @api public
*/
export declare function Backoff(opts: any): void;

View File

@ -0,0 +1,66 @@
/**
* Initialize backoff timer with `opts`.
*
* - `min` initial timeout in milliseconds [100]
* - `max` max timeout [10000]
* - `jitter` [0]
* - `factor` [2]
*
* @param {Object} opts
* @api public
*/
export function Backoff(opts) {
opts = opts || {};
this.ms = opts.min || 100;
this.max = opts.max || 10000;
this.factor = opts.factor || 2;
this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
this.attempts = 0;
}
/**
* Return the backoff duration.
*
* @return {Number}
* @api public
*/
Backoff.prototype.duration = function () {
var ms = this.ms * Math.pow(this.factor, this.attempts++);
if (this.jitter) {
var rand = Math.random();
var deviation = Math.floor(rand * this.jitter * ms);
ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
}
return Math.min(ms, this.max) | 0;
};
/**
* Reset the number of attempts.
*
* @api public
*/
Backoff.prototype.reset = function () {
this.attempts = 0;
};
/**
* Set the minimum duration
*
* @api public
*/
Backoff.prototype.setMin = function (min) {
this.ms = min;
};
/**
* Set the maximum duration
*
* @api public
*/
Backoff.prototype.setMax = function (max) {
this.max = max;
};
/**
* Set the jitter
*
* @api public
*/
Backoff.prototype.setJitter = function (jitter) {
this.jitter = jitter;
};

View File

@ -0,0 +1,29 @@
import { Manager, ManagerOptions } from "./manager.js";
import { Socket, SocketOptions } from "./socket.js";
/**
* Looks up an existing `Manager` for multiplexing.
* If the user summons:
*
* `io('http://localhost/a');`
* `io('http://localhost/b');`
*
* We reuse the existing instance based on same scheme/port/host,
* and we initialize sockets for each namespace.
*
* @public
*/
declare function lookup(opts?: Partial<ManagerOptions & SocketOptions>): Socket;
declare function lookup(uri?: string, opts?: Partial<ManagerOptions & SocketOptions>): Socket;
/**
* Protocol version.
*
* @public
*/
export { protocol } from "socket.io-parser";
/**
* Expose constructors for standalone build.
*
* @public
*/
export { Manager, ManagerOptions, Socket, SocketOptions, lookup as io, lookup as connect, lookup as default, };
export { Fetch, NodeXHR, XHR, NodeWebSocket, WebSocket, WebTransport, } from "engine.io-client";

62
node_modules/socket.io-client/build/esm-debug/index.js generated vendored Normal file
View File

@ -0,0 +1,62 @@
import { url } from "./url.js";
import { Manager } from "./manager.js";
import { Socket } from "./socket.js";
import debugModule from "debug"; // debug()
const debug = debugModule("socket.io-client"); // debug()
/**
* Managers cache.
*/
const cache = {};
function lookup(uri, opts) {
if (typeof uri === "object") {
opts = uri;
uri = undefined;
}
opts = opts || {};
const parsed = url(uri, opts.path || "/socket.io");
const source = parsed.source;
const id = parsed.id;
const path = parsed.path;
const sameNamespace = cache[id] && path in cache[id]["nsps"];
const newConnection = opts.forceNew ||
opts["force new connection"] ||
false === opts.multiplex ||
sameNamespace;
let io;
if (newConnection) {
debug("ignoring socket cache for %s", source);
io = new Manager(source, opts);
}
else {
if (!cache[id]) {
debug("new io instance for %s", source);
cache[id] = new Manager(source, opts);
}
io = cache[id];
}
if (parsed.query && !opts.query) {
opts.query = parsed.queryKey;
}
return io.socket(parsed.path, opts);
}
// so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
// namespace (e.g. `io.connect(...)`), for backward compatibility
Object.assign(lookup, {
Manager,
Socket,
io: lookup,
connect: lookup,
});
/**
* Protocol version.
*
* @public
*/
export { protocol } from "socket.io-parser";
/**
* Expose constructors for standalone build.
*
* @public
*/
export { Manager, Socket, lookup as io, lookup as connect, lookup as default, };
export { Fetch, NodeXHR, XHR, NodeWebSocket, WebSocket, WebTransport, } from "engine.io-client";

View File

@ -0,0 +1,295 @@
import { Socket as Engine, SocketOptions as EngineOptions } from "engine.io-client";
import { Socket, SocketOptions, DisconnectDescription } from "./socket.js";
import { Packet } from "socket.io-parser";
import { DefaultEventsMap, EventsMap, Emitter } from "@socket.io/component-emitter";
export interface ManagerOptions extends EngineOptions {
/**
* Should we force a new Manager for this connection?
* @default false
*/
forceNew: boolean;
/**
* Should we multiplex our connection (reuse existing Manager) ?
* @default true
*/
multiplex: boolean;
/**
* The path to get our client file from, in the case of the server
* serving it
* @default '/socket.io'
*/
path: string;
/**
* Should we allow reconnections?
* @default true
*/
reconnection: boolean;
/**
* How many reconnection attempts should we try?
* @default Infinity
*/
reconnectionAttempts: number;
/**
* The time delay in milliseconds between reconnection attempts
* @default 1000
*/
reconnectionDelay: number;
/**
* The max time delay in milliseconds between reconnection attempts
* @default 5000
*/
reconnectionDelayMax: number;
/**
* Used in the exponential backoff jitter when reconnecting
* @default 0.5
*/
randomizationFactor: number;
/**
* The timeout in milliseconds for our connection attempt
* @default 20000
*/
timeout: number;
/**
* Should we automatically connect?
* @default true
*/
autoConnect: boolean;
/**
* the parser to use. Defaults to an instance of the Parser that ships with socket.io.
*/
parser: any;
}
interface ManagerReservedEvents {
open: () => void;
error: (err: Error) => void;
ping: () => void;
packet: (packet: Packet) => void;
close: (reason: string, description?: DisconnectDescription) => void;
reconnect_failed: () => void;
reconnect_attempt: (attempt: number) => void;
reconnect_error: (err: Error) => void;
reconnect: (attempt: number) => void;
}
export declare class Manager<ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents> extends Emitter<{}, {}, ManagerReservedEvents> {
/**
* The Engine.IO client instance
*
* @public
*/
engine: Engine;
/**
* @private
*/
_autoConnect: boolean;
/**
* @private
*/
_readyState: "opening" | "open" | "closed";
/**
* @private
*/
_reconnecting: boolean;
private readonly uri;
opts: Partial<ManagerOptions>;
private nsps;
private subs;
private backoff;
private setTimeoutFn;
private clearTimeoutFn;
private _reconnection;
private _reconnectionAttempts;
private _reconnectionDelay;
private _randomizationFactor;
private _reconnectionDelayMax;
private _timeout;
private encoder;
private decoder;
private skipReconnect;
/**
* `Manager` constructor.
*
* @param uri - engine instance or engine uri/opts
* @param opts - options
* @public
*/
constructor(opts: Partial<ManagerOptions>);
constructor(uri?: string, opts?: Partial<ManagerOptions>);
constructor(uri?: string | Partial<ManagerOptions>, opts?: Partial<ManagerOptions>);
/**
* Sets the `reconnection` config.
*
* @param {Boolean} v - true/false if it should automatically reconnect
* @return {Manager} self or value
* @public
*/
reconnection(v: boolean): this;
reconnection(): boolean;
reconnection(v?: boolean): this | boolean;
/**
* Sets the reconnection attempts config.
*
* @param {Number} v - max reconnection attempts before giving up
* @return {Manager} self or value
* @public
*/
reconnectionAttempts(v: number): this;
reconnectionAttempts(): number;
reconnectionAttempts(v?: number): this | number;
/**
* Sets the delay between reconnections.
*
* @param {Number} v - delay
* @return {Manager} self or value
* @public
*/
reconnectionDelay(v: number): this;
reconnectionDelay(): number;
reconnectionDelay(v?: number): this | number;
/**
* Sets the randomization factor
*
* @param v - the randomization factor
* @return self or value
* @public
*/
randomizationFactor(v: number): this;
randomizationFactor(): number;
randomizationFactor(v?: number): this | number;
/**
* Sets the maximum delay between reconnections.
*
* @param v - delay
* @return self or value
* @public
*/
reconnectionDelayMax(v: number): this;
reconnectionDelayMax(): number;
reconnectionDelayMax(v?: number): this | number;
/**
* Sets the connection timeout. `false` to disable
*
* @param v - connection timeout
* @return self or value
* @public
*/
timeout(v: number | boolean): this;
timeout(): number | boolean;
timeout(v?: number | boolean): this | number | boolean;
/**
* Starts trying to reconnect if reconnection is enabled and we have not
* started reconnecting yet
*
* @private
*/
private maybeReconnectOnOpen;
/**
* Sets the current transport `socket`.
*
* @param {Function} fn - optional, callback
* @return self
* @public
*/
open(fn?: (err?: Error) => void): this;
/**
* Alias for open()
*
* @return self
* @public
*/
connect(fn?: (err?: Error) => void): this;
/**
* Called upon transport open.
*
* @private
*/
private onopen;
/**
* Called upon a ping.
*
* @private
*/
private onping;
/**
* Called with data.
*
* @private
*/
private ondata;
/**
* Called when parser fully decodes a packet.
*
* @private
*/
private ondecoded;
/**
* Called upon socket error.
*
* @private
*/
private onerror;
/**
* Creates a new socket for the given `nsp`.
*
* @return {Socket}
* @public
*/
socket(nsp: string, opts?: Partial<SocketOptions>): Socket;
/**
* Called upon a socket close.
*
* @param socket
* @private
*/
_destroy(socket: Socket): void;
/**
* Writes a packet.
*
* @param packet
* @private
*/
_packet(packet: Partial<Packet & {
query: string;
options: any;
}>): void;
/**
* Clean up transport subscriptions and packet buffer.
*
* @private
*/
private cleanup;
/**
* Close the current socket.
*
* @private
*/
_close(): void;
/**
* Alias for close()
*
* @private
*/
private disconnect;
/**
* Called when:
*
* - the low-level engine is closed
* - the parser encountered a badly formatted packet
* - all sockets are disconnected
*
* @private
*/
private onclose;
/**
* Attempt a reconnection.
*
* @private
*/
private reconnect;
/**
* Called upon successful reconnect.
*
* @private
*/
private onreconnect;
}
export {};

View File

@ -0,0 +1,386 @@
import { Socket as Engine, installTimerFunctions, nextTick, } from "engine.io-client";
import { Socket } from "./socket.js";
import * as parser from "socket.io-parser";
import { on } from "./on.js";
import { Backoff } from "./contrib/backo2.js";
import { Emitter, } from "@socket.io/component-emitter";
import debugModule from "debug"; // debug()
const debug = debugModule("socket.io-client:manager"); // debug()
export class Manager extends Emitter {
constructor(uri, opts) {
var _a;
super();
this.nsps = {};
this.subs = [];
if (uri && "object" === typeof uri) {
opts = uri;
uri = undefined;
}
opts = opts || {};
opts.path = opts.path || "/socket.io";
this.opts = opts;
installTimerFunctions(this, opts);
this.reconnection(opts.reconnection !== false);
this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
this.reconnectionDelay(opts.reconnectionDelay || 1000);
this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
this.backoff = new Backoff({
min: this.reconnectionDelay(),
max: this.reconnectionDelayMax(),
jitter: this.randomizationFactor(),
});
this.timeout(null == opts.timeout ? 20000 : opts.timeout);
this._readyState = "closed";
this.uri = uri;
const _parser = opts.parser || parser;
this.encoder = new _parser.Encoder();
this.decoder = new _parser.Decoder();
this._autoConnect = opts.autoConnect !== false;
if (this._autoConnect)
this.open();
}
reconnection(v) {
if (!arguments.length)
return this._reconnection;
this._reconnection = !!v;
if (!v) {
this.skipReconnect = true;
}
return this;
}
reconnectionAttempts(v) {
if (v === undefined)
return this._reconnectionAttempts;
this._reconnectionAttempts = v;
return this;
}
reconnectionDelay(v) {
var _a;
if (v === undefined)
return this._reconnectionDelay;
this._reconnectionDelay = v;
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
return this;
}
randomizationFactor(v) {
var _a;
if (v === undefined)
return this._randomizationFactor;
this._randomizationFactor = v;
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
return this;
}
reconnectionDelayMax(v) {
var _a;
if (v === undefined)
return this._reconnectionDelayMax;
this._reconnectionDelayMax = v;
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
return this;
}
timeout(v) {
if (!arguments.length)
return this._timeout;
this._timeout = v;
return this;
}
/**
* Starts trying to reconnect if reconnection is enabled and we have not
* started reconnecting yet
*
* @private
*/
maybeReconnectOnOpen() {
// Only try to reconnect if it's the first time we're connecting
if (!this._reconnecting &&
this._reconnection &&
this.backoff.attempts === 0) {
// keeps reconnection from firing twice for the same reconnection loop
this.reconnect();
}
}
/**
* Sets the current transport `socket`.
*
* @param {Function} fn - optional, callback
* @return self
* @public
*/
open(fn) {
debug("readyState %s", this._readyState);
if (~this._readyState.indexOf("open"))
return this;
debug("opening %s", this.uri);
this.engine = new Engine(this.uri, this.opts);
const socket = this.engine;
const self = this;
this._readyState = "opening";
this.skipReconnect = false;
// emit `open`
const openSubDestroy = on(socket, "open", function () {
self.onopen();
fn && fn();
});
const onError = (err) => {
debug("error");
this.cleanup();
this._readyState = "closed";
this.emitReserved("error", err);
if (fn) {
fn(err);
}
else {
// Only do this if there is no fn to handle the error
this.maybeReconnectOnOpen();
}
};
// emit `error`
const errorSub = on(socket, "error", onError);
if (false !== this._timeout) {
const timeout = this._timeout;
debug("connect attempt will timeout after %d", timeout);
// set timer
const timer = this.setTimeoutFn(() => {
debug("connect attempt timed out after %d", timeout);
openSubDestroy();
onError(new Error("timeout"));
socket.close();
}, timeout);
if (this.opts.autoUnref) {
timer.unref();
}
this.subs.push(() => {
this.clearTimeoutFn(timer);
});
}
this.subs.push(openSubDestroy);
this.subs.push(errorSub);
return this;
}
/**
* Alias for open()
*
* @return self
* @public
*/
connect(fn) {
return this.open(fn);
}
/**
* Called upon transport open.
*
* @private
*/
onopen() {
debug("open");
// clear old subs
this.cleanup();
// mark as open
this._readyState = "open";
this.emitReserved("open");
// add new subs
const socket = this.engine;
this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)),
// @ts-ignore
on(this.decoder, "decoded", this.ondecoded.bind(this)));
}
/**
* Called upon a ping.
*
* @private
*/
onping() {
this.emitReserved("ping");
}
/**
* Called with data.
*
* @private
*/
ondata(data) {
try {
this.decoder.add(data);
}
catch (e) {
this.onclose("parse error", e);
}
}
/**
* Called when parser fully decodes a packet.
*
* @private
*/
ondecoded(packet) {
// the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
nextTick(() => {
this.emitReserved("packet", packet);
}, this.setTimeoutFn);
}
/**
* Called upon socket error.
*
* @private
*/
onerror(err) {
debug("error", err);
this.emitReserved("error", err);
}
/**
* Creates a new socket for the given `nsp`.
*
* @return {Socket}
* @public
*/
socket(nsp, opts) {
let socket = this.nsps[nsp];
if (!socket) {
socket = new Socket(this, nsp, opts);
this.nsps[nsp] = socket;
}
else if (this._autoConnect && !socket.active) {
socket.connect();
}
return socket;
}
/**
* Called upon a socket close.
*
* @param socket
* @private
*/
_destroy(socket) {
const nsps = Object.keys(this.nsps);
for (const nsp of nsps) {
const socket = this.nsps[nsp];
if (socket.active) {
debug("socket %s is still active, skipping close", nsp);
return;
}
}
this._close();
}
/**
* Writes a packet.
*
* @param packet
* @private
*/
_packet(packet) {
debug("writing packet %j", packet);
const encodedPackets = this.encoder.encode(packet);
for (let i = 0; i < encodedPackets.length; i++) {
this.engine.write(encodedPackets[i], packet.options);
}
}
/**
* Clean up transport subscriptions and packet buffer.
*
* @private
*/
cleanup() {
debug("cleanup");
this.subs.forEach((subDestroy) => subDestroy());
this.subs.length = 0;
this.decoder.destroy();
}
/**
* Close the current socket.
*
* @private
*/
_close() {
debug("disconnect");
this.skipReconnect = true;
this._reconnecting = false;
this.onclose("forced close");
}
/**
* Alias for close()
*
* @private
*/
disconnect() {
return this._close();
}
/**
* Called when:
*
* - the low-level engine is closed
* - the parser encountered a badly formatted packet
* - all sockets are disconnected
*
* @private
*/
onclose(reason, description) {
var _a;
debug("closed due to %s", reason);
this.cleanup();
(_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
this.backoff.reset();
this._readyState = "closed";
this.emitReserved("close", reason, description);
if (this._reconnection && !this.skipReconnect) {
this.reconnect();
}
}
/**
* Attempt a reconnection.
*
* @private
*/
reconnect() {
if (this._reconnecting || this.skipReconnect)
return this;
const self = this;
if (this.backoff.attempts >= this._reconnectionAttempts) {
debug("reconnect failed");
this.backoff.reset();
this.emitReserved("reconnect_failed");
this._reconnecting = false;
}
else {
const delay = this.backoff.duration();
debug("will wait %dms before reconnect attempt", delay);
this._reconnecting = true;
const timer = this.setTimeoutFn(() => {
if (self.skipReconnect)
return;
debug("attempting reconnect");
this.emitReserved("reconnect_attempt", self.backoff.attempts);
// check again for the case socket closed in above events
if (self.skipReconnect)
return;
self.open((err) => {
if (err) {
debug("reconnect attempt error");
self._reconnecting = false;
self.reconnect();
this.emitReserved("reconnect_error", err);
}
else {
debug("reconnect success");
self.onreconnect();
}
});
}, delay);
if (this.opts.autoUnref) {
timer.unref();
}
this.subs.push(() => {
this.clearTimeoutFn(timer);
});
}
}
/**
* Called upon successful reconnect.
*
* @private
*/
onreconnect() {
const attempt = this.backoff.attempts;
this._reconnecting = false;
this.backoff.reset();
this.emitReserved("reconnect", attempt);
}
}

View File

@ -0,0 +1,2 @@
import { Emitter } from "@socket.io/component-emitter";
export declare function on(obj: Emitter<any, any>, ev: string, fn: (err?: any) => any): VoidFunction;

6
node_modules/socket.io-client/build/esm-debug/on.js generated vendored Normal file
View File

@ -0,0 +1,6 @@
export function on(obj, ev, fn) {
obj.on(ev, fn);
return function subDestroy() {
obj.off(ev, fn);
};
}

View File

@ -0,0 +1,5 @@
{
"name": "socket.io-client",
"version": "4.7.5",
"type": "module"
}

View File

@ -0,0 +1,593 @@
import { Packet } from "socket.io-parser";
import { Manager } from "./manager.js";
import { DefaultEventsMap, EventNames, EventParams, EventsMap, Emitter } from "@socket.io/component-emitter";
type PrependTimeoutError<T extends any[]> = {
[K in keyof T]: T[K] extends (...args: infer Params) => infer Result ? (err: Error, ...args: Params) => Result : T[K];
};
/**
* Utility type to decorate the acknowledgement callbacks with a timeout error.
*
* This is needed because the timeout() flag breaks the symmetry between the sender and the receiver:
*
* @example
* interface Events {
* "my-event": (val: string) => void;
* }
*
* socket.on("my-event", (cb) => {
* cb("123"); // one single argument here
* });
*
* socket.timeout(1000).emit("my-event", (err, val) => {
* // two arguments there (the "err" argument is not properly typed)
* });
*
*/
export type DecorateAcknowledgements<E> = {
[K in keyof E]: E[K] extends (...args: infer Params) => infer Result ? (...args: PrependTimeoutError<Params>) => Result : E[K];
};
export type Last<T extends any[]> = T extends [...infer H, infer L] ? L : any;
export type AllButLast<T extends any[]> = T extends [...infer H, infer L] ? H : any[];
export type FirstArg<T> = T extends (arg: infer Param) => infer Result ? Param : any;
export interface SocketOptions {
/**
* the authentication payload sent when connecting to the Namespace
*/
auth?: {
[key: string]: any;
} | ((cb: (data: object) => void) => void);
/**
* The maximum number of retries. Above the limit, the packet will be discarded.
*
* Using `Infinity` means the delivery guarantee is "at-least-once" (instead of "at-most-once" by default), but a
* smaller value like 10 should be sufficient in practice.
*/
retries?: number;
/**
* The default timeout in milliseconds used when waiting for an acknowledgement.
*/
ackTimeout?: number;
}
export type DisconnectDescription = Error | {
description: string;
context?: unknown;
};
interface SocketReservedEvents {
connect: () => void;
connect_error: (err: Error) => void;
disconnect: (reason: Socket.DisconnectReason, description?: DisconnectDescription) => void;
}
/**
* A Socket is the fundamental class for interacting with the server.
*
* A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
*
* @example
* const socket = io();
*
* socket.on("connect", () => {
* console.log("connected");
* });
*
* // send an event to the server
* socket.emit("foo", "bar");
*
* socket.on("foobar", () => {
* // an event was received from the server
* });
*
* // upon disconnection
* socket.on("disconnect", (reason) => {
* console.log(`disconnected due to ${reason}`);
* });
*/
export declare class Socket<ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents> extends Emitter<ListenEvents, EmitEvents, SocketReservedEvents> {
readonly io: Manager<ListenEvents, EmitEvents>;
/**
* A unique identifier for the session. `undefined` when the socket is not connected.
*
* @example
* const socket = io();
*
* console.log(socket.id); // undefined
*
* socket.on("connect", () => {
* console.log(socket.id); // "G5p5..."
* });
*/
id: string | undefined;
/**
* The session ID used for connection state recovery, which must not be shared (unlike {@link id}).
*
* @private
*/
private _pid;
/**
* The offset of the last received packet, which will be sent upon reconnection to allow for the recovery of the connection state.
*
* @private
*/
private _lastOffset;
/**
* Whether the socket is currently connected to the server.
*
* @example
* const socket = io();
*
* socket.on("connect", () => {
* console.log(socket.connected); // true
* });
*
* socket.on("disconnect", () => {
* console.log(socket.connected); // false
* });
*/
connected: boolean;
/**
* Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
* be transmitted by the server.
*/
recovered: boolean;
/**
* Credentials that are sent when accessing a namespace.
*
* @example
* const socket = io({
* auth: {
* token: "abcd"
* }
* });
*
* // or with a function
* const socket = io({
* auth: (cb) => {
* cb({ token: localStorage.token })
* }
* });
*/
auth: {
[key: string]: any;
} | ((cb: (data: object) => void) => void);
/**
* Buffer for packets received before the CONNECT packet
*/
receiveBuffer: Array<ReadonlyArray<any>>;
/**
* Buffer for packets that will be sent once the socket is connected
*/
sendBuffer: Array<Packet>;
/**
* The queue of packets to be sent with retry in case of failure.
*
* Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
* @private
*/
private _queue;
/**
* A sequence to generate the ID of the {@link QueuedPacket}.
* @private
*/
private _queueSeq;
private readonly nsp;
private readonly _opts;
private ids;
/**
* A map containing acknowledgement handlers.
*
* The `withError` attribute is used to differentiate handlers that accept an error as first argument:
*
* - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
* - `socket.timeout(5000).emit("test", (err, value) => { ... })`
* - `const value = await socket.emitWithAck("test")`
*
* From those that don't:
*
* - `socket.emit("test", (value) => { ... });`
*
* In the first case, the handlers will be called with an error when:
*
* - the timeout is reached
* - the socket gets disconnected
*
* In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
* an acknowledgement from the server.
*
* @private
*/
private acks;
private flags;
private subs?;
private _anyListeners;
private _anyOutgoingListeners;
/**
* `Socket` constructor.
*/
constructor(io: Manager, nsp: string, opts?: Partial<SocketOptions>);
/**
* Whether the socket is currently disconnected
*
* @example
* const socket = io();
*
* socket.on("connect", () => {
* console.log(socket.disconnected); // false
* });
*
* socket.on("disconnect", () => {
* console.log(socket.disconnected); // true
* });
*/
get disconnected(): boolean;
/**
* Subscribe to open, close and packet events
*
* @private
*/
private subEvents;
/**
* Whether the Socket will try to reconnect when its Manager connects or reconnects.
*
* @example
* const socket = io();
*
* console.log(socket.active); // true
*
* socket.on("disconnect", (reason) => {
* if (reason === "io server disconnect") {
* // the disconnection was initiated by the server, you need to manually reconnect
* console.log(socket.active); // false
* }
* // else the socket will automatically try to reconnect
* console.log(socket.active); // true
* });
*/
get active(): boolean;
/**
* "Opens" the socket.
*
* @example
* const socket = io({
* autoConnect: false
* });
*
* socket.connect();
*/
connect(): this;
/**
* Alias for {@link connect()}.
*/
open(): this;
/**
* Sends a `message` event.
*
* This method mimics the WebSocket.send() method.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
*
* @example
* socket.send("hello");
*
* // this is equivalent to
* socket.emit("message", "hello");
*
* @return self
*/
send(...args: any[]): this;
/**
* Override `emit`.
* If the event is in `events`, it's emitted normally.
*
* @example
* socket.emit("hello", "world");
*
* // all serializable datastructures are supported (no need to call JSON.stringify)
* socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
*
* // with an acknowledgement from the server
* socket.emit("hello", "world", (val) => {
* // ...
* });
*
* @return self
*/
emit<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: EventParams<EmitEvents, Ev>): this;
/**
* @private
*/
private _registerAckCallback;
/**
* Emits an event and waits for an acknowledgement
*
* @example
* // without timeout
* const response = await socket.emitWithAck("hello", "world");
*
* // with a specific timeout
* try {
* const response = await socket.timeout(1000).emitWithAck("hello", "world");
* } catch (err) {
* // the server did not acknowledge the event in the given delay
* }
*
* @return a Promise that will be fulfilled when the server acknowledges the event
*/
emitWithAck<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: AllButLast<EventParams<EmitEvents, Ev>>): Promise<FirstArg<Last<EventParams<EmitEvents, Ev>>>>;
/**
* Add the packet to the queue.
* @param args
* @private
*/
private _addToQueue;
/**
* Send the first packet of the queue, and wait for an acknowledgement from the server.
* @param force - whether to resend a packet that has not been acknowledged yet
*
* @private
*/
private _drainQueue;
/**
* Sends a packet.
*
* @param packet
* @private
*/
private packet;
/**
* Called upon engine `open`.
*
* @private
*/
private onopen;
/**
* Sends a CONNECT packet to initiate the Socket.IO session.
*
* @param data
* @private
*/
private _sendConnectPacket;
/**
* Called upon engine or manager `error`.
*
* @param err
* @private
*/
private onerror;
/**
* Called upon engine `close`.
*
* @param reason
* @param description
* @private
*/
private onclose;
/**
* Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
* the server.
*
* @private
*/
private _clearAcks;
/**
* Called with socket packet.
*
* @param packet
* @private
*/
private onpacket;
/**
* Called upon a server event.
*
* @param packet
* @private
*/
private onevent;
private emitEvent;
/**
* Produces an ack callback to emit with an event.
*
* @private
*/
private ack;
/**
* Called upon a server acknowledgement.
*
* @param packet
* @private
*/
private onack;
/**
* Called upon server connect.
*
* @private
*/
private onconnect;
/**
* Emit buffered events (received and emitted).
*
* @private
*/
private emitBuffered;
/**
* Called upon server disconnect.
*
* @private
*/
private ondisconnect;
/**
* Called upon forced client/server side disconnections,
* this method ensures the manager stops tracking us and
* that reconnections don't get triggered for this.
*
* @private
*/
private destroy;
/**
* Disconnects the socket manually. In that case, the socket will not try to reconnect.
*
* If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
*
* @example
* const socket = io();
*
* socket.on("disconnect", (reason) => {
* // console.log(reason); prints "io client disconnect"
* });
*
* socket.disconnect();
*
* @return self
*/
disconnect(): this;
/**
* Alias for {@link disconnect()}.
*
* @return self
*/
close(): this;
/**
* Sets the compress flag.
*
* @example
* socket.compress(false).emit("hello");
*
* @param compress - if `true`, compresses the sending data
* @return self
*/
compress(compress: boolean): this;
/**
* Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
* ready to send messages.
*
* @example
* socket.volatile.emit("hello"); // the server may or may not receive it
*
* @returns self
*/
get volatile(): this;
/**
* Sets a modifier for a subsequent event emission that the callback will be called with an error when the
* given number of milliseconds have elapsed without an acknowledgement from the server:
*
* @example
* socket.timeout(5000).emit("my-event", (err) => {
* if (err) {
* // the server did not acknowledge the event in the given delay
* }
* });
*
* @returns self
*/
timeout(timeout: number): Socket<ListenEvents, DecorateAcknowledgements<EmitEvents>>;
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback.
*
* @example
* socket.onAny((event, ...args) => {
* console.log(`got ${event}`);
* });
*
* @param listener
*/
onAny(listener: (...args: any[]) => void): this;
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback. The listener is added to the beginning of the listeners array.
*
* @example
* socket.prependAny((event, ...args) => {
* console.log(`got event ${event}`);
* });
*
* @param listener
*/
prependAny(listener: (...args: any[]) => void): this;
/**
* Removes the listener that will be fired when any event is emitted.
*
* @example
* const catchAllListener = (event, ...args) => {
* console.log(`got event ${event}`);
* }
*
* socket.onAny(catchAllListener);
*
* // remove a specific listener
* socket.offAny(catchAllListener);
*
* // or remove all listeners
* socket.offAny();
*
* @param listener
*/
offAny(listener?: (...args: any[]) => void): this;
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*/
listenersAny(): ((...args: any[]) => void)[];
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback.
*
* Note: acknowledgements sent to the server are not included.
*
* @example
* socket.onAnyOutgoing((event, ...args) => {
* console.log(`sent event ${event}`);
* });
*
* @param listener
*/
onAnyOutgoing(listener: (...args: any[]) => void): this;
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback. The listener is added to the beginning of the listeners array.
*
* Note: acknowledgements sent to the server are not included.
*
* @example
* socket.prependAnyOutgoing((event, ...args) => {
* console.log(`sent event ${event}`);
* });
*
* @param listener
*/
prependAnyOutgoing(listener: (...args: any[]) => void): this;
/**
* Removes the listener that will be fired when any event is emitted.
*
* @example
* const catchAllListener = (event, ...args) => {
* console.log(`sent event ${event}`);
* }
*
* socket.onAnyOutgoing(catchAllListener);
*
* // remove a specific listener
* socket.offAnyOutgoing(catchAllListener);
*
* // or remove all listeners
* socket.offAnyOutgoing();
*
* @param [listener] - the catch-all listener (optional)
*/
offAnyOutgoing(listener?: (...args: any[]) => void): this;
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*/
listenersAnyOutgoing(): ((...args: any[]) => void)[];
/**
* Notify the listeners for each packet sent
*
* @param packet
*
* @private
*/
private notifyOutgoingListeners;
}
export declare namespace Socket {
type DisconnectReason = "io server disconnect" | "io client disconnect" | "ping timeout" | "transport close" | "transport error" | "parse error";
}
export {};

903
node_modules/socket.io-client/build/esm-debug/socket.js generated vendored Normal file
View File

@ -0,0 +1,903 @@
import { PacketType } from "socket.io-parser";
import { on } from "./on.js";
import { Emitter, } from "@socket.io/component-emitter";
import debugModule from "debug"; // debug()
const debug = debugModule("socket.io-client:socket"); // debug()
/**
* Internal events.
* These events can't be emitted by the user.
*/
const RESERVED_EVENTS = Object.freeze({
connect: 1,
connect_error: 1,
disconnect: 1,
disconnecting: 1,
// EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
newListener: 1,
removeListener: 1,
});
/**
* A Socket is the fundamental class for interacting with the server.
*
* A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
*
* @example
* const socket = io();
*
* socket.on("connect", () => {
* console.log("connected");
* });
*
* // send an event to the server
* socket.emit("foo", "bar");
*
* socket.on("foobar", () => {
* // an event was received from the server
* });
*
* // upon disconnection
* socket.on("disconnect", (reason) => {
* console.log(`disconnected due to ${reason}`);
* });
*/
export class Socket extends Emitter {
/**
* `Socket` constructor.
*/
constructor(io, nsp, opts) {
super();
/**
* Whether the socket is currently connected to the server.
*
* @example
* const socket = io();
*
* socket.on("connect", () => {
* console.log(socket.connected); // true
* });
*
* socket.on("disconnect", () => {
* console.log(socket.connected); // false
* });
*/
this.connected = false;
/**
* Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
* be transmitted by the server.
*/
this.recovered = false;
/**
* Buffer for packets received before the CONNECT packet
*/
this.receiveBuffer = [];
/**
* Buffer for packets that will be sent once the socket is connected
*/
this.sendBuffer = [];
/**
* The queue of packets to be sent with retry in case of failure.
*
* Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
* @private
*/
this._queue = [];
/**
* A sequence to generate the ID of the {@link QueuedPacket}.
* @private
*/
this._queueSeq = 0;
this.ids = 0;
/**
* A map containing acknowledgement handlers.
*
* The `withError` attribute is used to differentiate handlers that accept an error as first argument:
*
* - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
* - `socket.timeout(5000).emit("test", (err, value) => { ... })`
* - `const value = await socket.emitWithAck("test")`
*
* From those that don't:
*
* - `socket.emit("test", (value) => { ... });`
*
* In the first case, the handlers will be called with an error when:
*
* - the timeout is reached
* - the socket gets disconnected
*
* In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
* an acknowledgement from the server.
*
* @private
*/
this.acks = {};
this.flags = {};
this.io = io;
this.nsp = nsp;
if (opts && opts.auth) {
this.auth = opts.auth;
}
this._opts = Object.assign({}, opts);
if (this.io._autoConnect)
this.open();
}
/**
* Whether the socket is currently disconnected
*
* @example
* const socket = io();
*
* socket.on("connect", () => {
* console.log(socket.disconnected); // false
* });
*
* socket.on("disconnect", () => {
* console.log(socket.disconnected); // true
* });
*/
get disconnected() {
return !this.connected;
}
/**
* Subscribe to open, close and packet events
*
* @private
*/
subEvents() {
if (this.subs)
return;
const io = this.io;
this.subs = [
on(io, "open", this.onopen.bind(this)),
on(io, "packet", this.onpacket.bind(this)),
on(io, "error", this.onerror.bind(this)),
on(io, "close", this.onclose.bind(this)),
];
}
/**
* Whether the Socket will try to reconnect when its Manager connects or reconnects.
*
* @example
* const socket = io();
*
* console.log(socket.active); // true
*
* socket.on("disconnect", (reason) => {
* if (reason === "io server disconnect") {
* // the disconnection was initiated by the server, you need to manually reconnect
* console.log(socket.active); // false
* }
* // else the socket will automatically try to reconnect
* console.log(socket.active); // true
* });
*/
get active() {
return !!this.subs;
}
/**
* "Opens" the socket.
*
* @example
* const socket = io({
* autoConnect: false
* });
*
* socket.connect();
*/
connect() {
if (this.connected)
return this;
this.subEvents();
if (!this.io["_reconnecting"])
this.io.open(); // ensure open
if ("open" === this.io._readyState)
this.onopen();
return this;
}
/**
* Alias for {@link connect()}.
*/
open() {
return this.connect();
}
/**
* Sends a `message` event.
*
* This method mimics the WebSocket.send() method.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
*
* @example
* socket.send("hello");
*
* // this is equivalent to
* socket.emit("message", "hello");
*
* @return self
*/
send(...args) {
args.unshift("message");
this.emit.apply(this, args);
return this;
}
/**
* Override `emit`.
* If the event is in `events`, it's emitted normally.
*
* @example
* socket.emit("hello", "world");
*
* // all serializable datastructures are supported (no need to call JSON.stringify)
* socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
*
* // with an acknowledgement from the server
* socket.emit("hello", "world", (val) => {
* // ...
* });
*
* @return self
*/
emit(ev, ...args) {
var _a, _b, _c;
if (RESERVED_EVENTS.hasOwnProperty(ev)) {
throw new Error('"' + ev.toString() + '" is a reserved event name');
}
args.unshift(ev);
if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
this._addToQueue(args);
return this;
}
const packet = {
type: PacketType.EVENT,
data: args,
};
packet.options = {};
packet.options.compress = this.flags.compress !== false;
// event ack callback
if ("function" === typeof args[args.length - 1]) {
const id = this.ids++;
debug("emitting packet with ack id %d", id);
const ack = args.pop();
this._registerAckCallback(id, ack);
packet.id = id;
}
const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
const discardPacket = this.flags.volatile && !isTransportWritable;
if (discardPacket) {
debug("discard packet as the transport is not currently writable");
}
else if (isConnected) {
this.notifyOutgoingListeners(packet);
this.packet(packet);
}
else {
this.sendBuffer.push(packet);
}
this.flags = {};
return this;
}
/**
* @private
*/
_registerAckCallback(id, ack) {
var _a;
const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
if (timeout === undefined) {
this.acks[id] = ack;
return;
}
// @ts-ignore
const timer = this.io.setTimeoutFn(() => {
delete this.acks[id];
for (let i = 0; i < this.sendBuffer.length; i++) {
if (this.sendBuffer[i].id === id) {
debug("removing packet with ack id %d from the buffer", id);
this.sendBuffer.splice(i, 1);
}
}
debug("event with ack id %d has timed out after %d ms", id, timeout);
ack.call(this, new Error("operation has timed out"));
}, timeout);
const fn = (...args) => {
// @ts-ignore
this.io.clearTimeoutFn(timer);
ack.apply(this, args);
};
fn.withError = true;
this.acks[id] = fn;
}
/**
* Emits an event and waits for an acknowledgement
*
* @example
* // without timeout
* const response = await socket.emitWithAck("hello", "world");
*
* // with a specific timeout
* try {
* const response = await socket.timeout(1000).emitWithAck("hello", "world");
* } catch (err) {
* // the server did not acknowledge the event in the given delay
* }
*
* @return a Promise that will be fulfilled when the server acknowledges the event
*/
emitWithAck(ev, ...args) {
return new Promise((resolve, reject) => {
const fn = (arg1, arg2) => {
return arg1 ? reject(arg1) : resolve(arg2);
};
fn.withError = true;
args.push(fn);
this.emit(ev, ...args);
});
}
/**
* Add the packet to the queue.
* @param args
* @private
*/
_addToQueue(args) {
let ack;
if (typeof args[args.length - 1] === "function") {
ack = args.pop();
}
const packet = {
id: this._queueSeq++,
tryCount: 0,
pending: false,
args,
flags: Object.assign({ fromQueue: true }, this.flags),
};
args.push((err, ...responseArgs) => {
if (packet !== this._queue[0]) {
// the packet has already been acknowledged
return;
}
const hasError = err !== null;
if (hasError) {
if (packet.tryCount > this._opts.retries) {
debug("packet [%d] is discarded after %d tries", packet.id, packet.tryCount);
this._queue.shift();
if (ack) {
ack(err);
}
}
}
else {
debug("packet [%d] was successfully sent", packet.id);
this._queue.shift();
if (ack) {
ack(null, ...responseArgs);
}
}
packet.pending = false;
return this._drainQueue();
});
this._queue.push(packet);
this._drainQueue();
}
/**
* Send the first packet of the queue, and wait for an acknowledgement from the server.
* @param force - whether to resend a packet that has not been acknowledged yet
*
* @private
*/
_drainQueue(force = false) {
debug("draining queue");
if (!this.connected || this._queue.length === 0) {
return;
}
const packet = this._queue[0];
if (packet.pending && !force) {
debug("packet [%d] has already been sent and is waiting for an ack", packet.id);
return;
}
packet.pending = true;
packet.tryCount++;
debug("sending packet [%d] (try n°%d)", packet.id, packet.tryCount);
this.flags = packet.flags;
this.emit.apply(this, packet.args);
}
/**
* Sends a packet.
*
* @param packet
* @private
*/
packet(packet) {
packet.nsp = this.nsp;
this.io._packet(packet);
}
/**
* Called upon engine `open`.
*
* @private
*/
onopen() {
debug("transport is open - connecting");
if (typeof this.auth == "function") {
this.auth((data) => {
this._sendConnectPacket(data);
});
}
else {
this._sendConnectPacket(this.auth);
}
}
/**
* Sends a CONNECT packet to initiate the Socket.IO session.
*
* @param data
* @private
*/
_sendConnectPacket(data) {
this.packet({
type: PacketType.CONNECT,
data: this._pid
? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)
: data,
});
}
/**
* Called upon engine or manager `error`.
*
* @param err
* @private
*/
onerror(err) {
if (!this.connected) {
this.emitReserved("connect_error", err);
}
}
/**
* Called upon engine `close`.
*
* @param reason
* @param description
* @private
*/
onclose(reason, description) {
debug("close (%s)", reason);
this.connected = false;
delete this.id;
this.emitReserved("disconnect", reason, description);
this._clearAcks();
}
/**
* Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
* the server.
*
* @private
*/
_clearAcks() {
Object.keys(this.acks).forEach((id) => {
const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
if (!isBuffered) {
// note: handlers that do not accept an error as first argument are ignored here
const ack = this.acks[id];
delete this.acks[id];
if (ack.withError) {
ack.call(this, new Error("socket has been disconnected"));
}
}
});
}
/**
* Called with socket packet.
*
* @param packet
* @private
*/
onpacket(packet) {
const sameNamespace = packet.nsp === this.nsp;
if (!sameNamespace)
return;
switch (packet.type) {
case PacketType.CONNECT:
if (packet.data && packet.data.sid) {
this.onconnect(packet.data.sid, packet.data.pid);
}
else {
this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
}
break;
case PacketType.EVENT:
case PacketType.BINARY_EVENT:
this.onevent(packet);
break;
case PacketType.ACK:
case PacketType.BINARY_ACK:
this.onack(packet);
break;
case PacketType.DISCONNECT:
this.ondisconnect();
break;
case PacketType.CONNECT_ERROR:
this.destroy();
const err = new Error(packet.data.message);
// @ts-ignore
err.data = packet.data.data;
this.emitReserved("connect_error", err);
break;
}
}
/**
* Called upon a server event.
*
* @param packet
* @private
*/
onevent(packet) {
const args = packet.data || [];
debug("emitting event %j", args);
if (null != packet.id) {
debug("attaching ack callback to event");
args.push(this.ack(packet.id));
}
if (this.connected) {
this.emitEvent(args);
}
else {
this.receiveBuffer.push(Object.freeze(args));
}
}
emitEvent(args) {
if (this._anyListeners && this._anyListeners.length) {
const listeners = this._anyListeners.slice();
for (const listener of listeners) {
listener.apply(this, args);
}
}
super.emit.apply(this, args);
if (this._pid && args.length && typeof args[args.length - 1] === "string") {
this._lastOffset = args[args.length - 1];
}
}
/**
* Produces an ack callback to emit with an event.
*
* @private
*/
ack(id) {
const self = this;
let sent = false;
return function (...args) {
// prevent double callbacks
if (sent)
return;
sent = true;
debug("sending ack %j", args);
self.packet({
type: PacketType.ACK,
id: id,
data: args,
});
};
}
/**
* Called upon a server acknowledgement.
*
* @param packet
* @private
*/
onack(packet) {
const ack = this.acks[packet.id];
if (typeof ack !== "function") {
debug("bad ack %s", packet.id);
return;
}
delete this.acks[packet.id];
debug("calling ack %s with %j", packet.id, packet.data);
// @ts-ignore FIXME ack is incorrectly inferred as 'never'
if (ack.withError) {
packet.data.unshift(null);
}
// @ts-ignore
ack.apply(this, packet.data);
}
/**
* Called upon server connect.
*
* @private
*/
onconnect(id, pid) {
debug("socket connected with id %s", id);
this.id = id;
this.recovered = pid && this._pid === pid;
this._pid = pid; // defined only if connection state recovery is enabled
this.connected = true;
this.emitBuffered();
this.emitReserved("connect");
this._drainQueue(true);
}
/**
* Emit buffered events (received and emitted).
*
* @private
*/
emitBuffered() {
this.receiveBuffer.forEach((args) => this.emitEvent(args));
this.receiveBuffer = [];
this.sendBuffer.forEach((packet) => {
this.notifyOutgoingListeners(packet);
this.packet(packet);
});
this.sendBuffer = [];
}
/**
* Called upon server disconnect.
*
* @private
*/
ondisconnect() {
debug("server disconnect (%s)", this.nsp);
this.destroy();
this.onclose("io server disconnect");
}
/**
* Called upon forced client/server side disconnections,
* this method ensures the manager stops tracking us and
* that reconnections don't get triggered for this.
*
* @private
*/
destroy() {
if (this.subs) {
// clean subscriptions to avoid reconnections
this.subs.forEach((subDestroy) => subDestroy());
this.subs = undefined;
}
this.io["_destroy"](this);
}
/**
* Disconnects the socket manually. In that case, the socket will not try to reconnect.
*
* If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
*
* @example
* const socket = io();
*
* socket.on("disconnect", (reason) => {
* // console.log(reason); prints "io client disconnect"
* });
*
* socket.disconnect();
*
* @return self
*/
disconnect() {
if (this.connected) {
debug("performing disconnect (%s)", this.nsp);
this.packet({ type: PacketType.DISCONNECT });
}
// remove socket from pool
this.destroy();
if (this.connected) {
// fire events
this.onclose("io client disconnect");
}
return this;
}
/**
* Alias for {@link disconnect()}.
*
* @return self
*/
close() {
return this.disconnect();
}
/**
* Sets the compress flag.
*
* @example
* socket.compress(false).emit("hello");
*
* @param compress - if `true`, compresses the sending data
* @return self
*/
compress(compress) {
this.flags.compress = compress;
return this;
}
/**
* Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
* ready to send messages.
*
* @example
* socket.volatile.emit("hello"); // the server may or may not receive it
*
* @returns self
*/
get volatile() {
this.flags.volatile = true;
return this;
}
/**
* Sets a modifier for a subsequent event emission that the callback will be called with an error when the
* given number of milliseconds have elapsed without an acknowledgement from the server:
*
* @example
* socket.timeout(5000).emit("my-event", (err) => {
* if (err) {
* // the server did not acknowledge the event in the given delay
* }
* });
*
* @returns self
*/
timeout(timeout) {
this.flags.timeout = timeout;
return this;
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback.
*
* @example
* socket.onAny((event, ...args) => {
* console.log(`got ${event}`);
* });
*
* @param listener
*/
onAny(listener) {
this._anyListeners = this._anyListeners || [];
this._anyListeners.push(listener);
return this;
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback. The listener is added to the beginning of the listeners array.
*
* @example
* socket.prependAny((event, ...args) => {
* console.log(`got event ${event}`);
* });
*
* @param listener
*/
prependAny(listener) {
this._anyListeners = this._anyListeners || [];
this._anyListeners.unshift(listener);
return this;
}
/**
* Removes the listener that will be fired when any event is emitted.
*
* @example
* const catchAllListener = (event, ...args) => {
* console.log(`got event ${event}`);
* }
*
* socket.onAny(catchAllListener);
*
* // remove a specific listener
* socket.offAny(catchAllListener);
*
* // or remove all listeners
* socket.offAny();
*
* @param listener
*/
offAny(listener) {
if (!this._anyListeners) {
return this;
}
if (listener) {
const listeners = this._anyListeners;
for (let i = 0; i < listeners.length; i++) {
if (listener === listeners[i]) {
listeners.splice(i, 1);
return this;
}
}
}
else {
this._anyListeners = [];
}
return this;
}
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*/
listenersAny() {
return this._anyListeners || [];
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback.
*
* Note: acknowledgements sent to the server are not included.
*
* @example
* socket.onAnyOutgoing((event, ...args) => {
* console.log(`sent event ${event}`);
* });
*
* @param listener
*/
onAnyOutgoing(listener) {
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
this._anyOutgoingListeners.push(listener);
return this;
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback. The listener is added to the beginning of the listeners array.
*
* Note: acknowledgements sent to the server are not included.
*
* @example
* socket.prependAnyOutgoing((event, ...args) => {
* console.log(`sent event ${event}`);
* });
*
* @param listener
*/
prependAnyOutgoing(listener) {
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
this._anyOutgoingListeners.unshift(listener);
return this;
}
/**
* Removes the listener that will be fired when any event is emitted.
*
* @example
* const catchAllListener = (event, ...args) => {
* console.log(`sent event ${event}`);
* }
*
* socket.onAnyOutgoing(catchAllListener);
*
* // remove a specific listener
* socket.offAnyOutgoing(catchAllListener);
*
* // or remove all listeners
* socket.offAnyOutgoing();
*
* @param [listener] - the catch-all listener (optional)
*/
offAnyOutgoing(listener) {
if (!this._anyOutgoingListeners) {
return this;
}
if (listener) {
const listeners = this._anyOutgoingListeners;
for (let i = 0; i < listeners.length; i++) {
if (listener === listeners[i]) {
listeners.splice(i, 1);
return this;
}
}
}
else {
this._anyOutgoingListeners = [];
}
return this;
}
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*/
listenersAnyOutgoing() {
return this._anyOutgoingListeners || [];
}
/**
* Notify the listeners for each packet sent
*
* @param packet
*
* @private
*/
notifyOutgoingListeners(packet) {
if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
const listeners = this._anyOutgoingListeners.slice();
for (const listener of listeners) {
listener.apply(this, packet.data);
}
}
}
}

33
node_modules/socket.io-client/build/esm-debug/url.d.ts generated vendored Normal file
View File

@ -0,0 +1,33 @@
type ParsedUrl = {
source: string;
protocol: string;
authority: string;
userInfo: string;
user: string;
password: string;
host: string;
port: string;
relative: string;
path: string;
directory: string;
file: string;
query: string;
anchor: string;
pathNames: Array<string>;
queryKey: {
[key: string]: string;
};
id: string;
href: string;
};
/**
* URL parser.
*
* @param uri - url
* @param path - the request path of the connection
* @param loc - An object meant to mimic window.location.
* Defaults to window.location.
* @public
*/
export declare function url(uri: string | ParsedUrl, path?: string, loc?: Location): ParsedUrl;
export {};

63
node_modules/socket.io-client/build/esm-debug/url.js generated vendored Normal file
View File

@ -0,0 +1,63 @@
import { parse } from "engine.io-client";
import debugModule from "debug"; // debug()
const debug = debugModule("socket.io-client:url"); // debug()
/**
* URL parser.
*
* @param uri - url
* @param path - the request path of the connection
* @param loc - An object meant to mimic window.location.
* Defaults to window.location.
* @public
*/
export function url(uri, path = "", loc) {
let obj = uri;
// default to window.location
loc = loc || (typeof location !== "undefined" && location);
if (null == uri)
uri = loc.protocol + "//" + loc.host;
// relative path support
if (typeof uri === "string") {
if ("/" === uri.charAt(0)) {
if ("/" === uri.charAt(1)) {
uri = loc.protocol + uri;
}
else {
uri = loc.host + uri;
}
}
if (!/^(https?|wss?):\/\//.test(uri)) {
debug("protocol-less url %s", uri);
if ("undefined" !== typeof loc) {
uri = loc.protocol + "//" + uri;
}
else {
uri = "https://" + uri;
}
}
// parse
debug("parse %s", uri);
obj = parse(uri);
}
// make sure we treat `localhost:80` and `localhost` equally
if (!obj.port) {
if (/^(http|ws)$/.test(obj.protocol)) {
obj.port = "80";
}
else if (/^(http|ws)s$/.test(obj.protocol)) {
obj.port = "443";
}
}
obj.path = obj.path || "/";
const ipv6 = obj.host.indexOf(":") !== -1;
const host = ipv6 ? "[" + obj.host + "]" : obj.host;
// define unique id
obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
// define href
obj.href =
obj.protocol +
"://" +
host +
(loc && loc.port === obj.port ? "" : ":" + obj.port);
return obj;
}