main funcions fixes

This commit is contained in:
2025-09-29 22:06:11 +09:00
parent 40e016e128
commit c8c3274527
7995 changed files with 1517998 additions and 1057 deletions

21
desktop-operator/node_modules/socket.io-client/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-present Guillermo Rauch and Socket.IO contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,29 @@
# socket.io-client
[![Build Status](https://github.com/socketio/socket.io-client/workflows/CI/badge.svg?branch=main)](https://github.com/socketio/socket.io-client/actions)
[![NPM version](https://badge.fury.io/js/socket.io-client.svg)](https://www.npmjs.com/package/socket.io-client)
![Downloads](http://img.shields.io/npm/dm/socket.io-client.svg?style=flat)
[![](http://slack.socket.io/badge.svg?)](http://slack.socket.io)
[![Sauce Test Status](https://saucelabs.com/browser-matrix/socket.svg)](https://saucelabs.com/u/socket)
## Documentation
Please see the documentation [here](https://socket.io/docs/v4/client-initialization/).
The source code of the website can be found [here](https://github.com/socketio/socket.io-website). Contributions are welcome!
## Debug / logging
In order to see all the client debug output, run the following command on the browser console including the desired scope and reload your app page:
```
localStorage.debug = '*';
```
And then, filter by the scopes you're interested in. See also: https://socket.io/docs/v4/logging-and-debugging/
## License
[MIT](/LICENSE)

View File

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

View File

@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const index_js_1 = require("./index.js");
exports.default = index_js_1.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,69 @@
"use strict";
/**
* Initialize backoff timer with `opts`.
*
* - `min` initial timeout in milliseconds [100]
* - `max` max timeout [10000]
* - `jitter` [0]
* - `factor` [2]
*
* @param {Object} opts
* @api public
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Backoff = Backoff;
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";

View File

@@ -0,0 +1,76 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebTransport = exports.WebSocket = exports.NodeWebSocket = exports.XHR = exports.NodeXHR = exports.Fetch = exports.Socket = exports.Manager = exports.protocol = void 0;
exports.io = lookup;
exports.connect = lookup;
exports.default = lookup;
const url_js_1 = require("./url.js");
const manager_js_1 = require("./manager.js");
Object.defineProperty(exports, "Manager", { enumerable: true, get: function () { return manager_js_1.Manager; } });
const socket_js_1 = require("./socket.js");
Object.defineProperty(exports, "Socket", { enumerable: true, get: function () { return socket_js_1.Socket; } });
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("socket.io-client"); // debug()
/**
* Managers cache.
*/
const cache = {};
function lookup(uri, opts) {
if (typeof uri === "object") {
opts = uri;
uri = undefined;
}
opts = opts || {};
const parsed = (0, url_js_1.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_js_1.Manager(source, opts);
}
else {
if (!cache[id]) {
debug("new io instance for %s", source);
cache[id] = new manager_js_1.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: manager_js_1.Manager,
Socket: socket_js_1.Socket,
io: lookup,
connect: lookup,
});
/**
* Protocol version.
*
* @public
*/
var socket_io_parser_1 = require("socket.io-parser");
Object.defineProperty(exports, "protocol", { enumerable: true, get: function () { return socket_io_parser_1.protocol; } });
var engine_io_client_1 = require("engine.io-client");
Object.defineProperty(exports, "Fetch", { enumerable: true, get: function () { return engine_io_client_1.Fetch; } });
Object.defineProperty(exports, "NodeXHR", { enumerable: true, get: function () { return engine_io_client_1.NodeXHR; } });
Object.defineProperty(exports, "XHR", { enumerable: true, get: function () { return engine_io_client_1.XHR; } });
Object.defineProperty(exports, "NodeWebSocket", { enumerable: true, get: function () { return engine_io_client_1.NodeWebSocket; } });
Object.defineProperty(exports, "WebSocket", { enumerable: true, get: function () { return engine_io_client_1.WebSocket; } });
Object.defineProperty(exports, "WebTransport", { enumerable: true, get: function () { return engine_io_client_1.WebTransport; } });
module.exports = lookup;

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,416 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Manager = void 0;
const engine_io_client_1 = require("engine.io-client");
const socket_js_1 = require("./socket.js");
const parser = __importStar(require("socket.io-parser"));
const on_js_1 = require("./on.js");
const backo2_js_1 = require("./contrib/backo2.js");
const component_emitter_1 = require("@socket.io/component-emitter");
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("socket.io-client:manager"); // debug()
class Manager extends component_emitter_1.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;
(0, engine_io_client_1.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 backo2_js_1.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_io_client_1.Socket(this.uri, this.opts);
const socket = this.engine;
const self = this;
this._readyState = "opening";
this.skipReconnect = false;
// emit `open`
const openSubDestroy = (0, on_js_1.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 = (0, on_js_1.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((0, on_js_1.on)(socket, "ping", this.onping.bind(this)), (0, on_js_1.on)(socket, "data", this.ondata.bind(this)), (0, on_js_1.on)(socket, "error", this.onerror.bind(this)), (0, on_js_1.on)(socket, "close", this.onclose.bind(this)),
// @ts-ignore
(0, on_js_1.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"
(0, engine_io_client_1.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_js_1.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);
}
}
exports.Manager = Manager;

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;

View File

@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.on = on;
function on(obj, ev, fn) {
obj.on(ev, fn);
return function subDestroy() {
obj.off(ev, fn);
};
}

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 {};

View File

@@ -0,0 +1,910 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Socket = void 0;
const socket_io_parser_1 = require("socket.io-parser");
const on_js_1 = require("./on.js");
const component_emitter_1 = require("@socket.io/component-emitter");
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("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}`);
* });
*/
class Socket extends component_emitter_1.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 = [
(0, on_js_1.on)(io, "open", this.onopen.bind(this)),
(0, on_js_1.on)(io, "packet", this.onpacket.bind(this)),
(0, on_js_1.on)(io, "error", this.onerror.bind(this)),
(0, on_js_1.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: socket_io_parser_1.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: socket_io_parser_1.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 socket_io_parser_1.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 socket_io_parser_1.PacketType.EVENT:
case socket_io_parser_1.PacketType.BINARY_EVENT:
this.onevent(packet);
break;
case socket_io_parser_1.PacketType.ACK:
case socket_io_parser_1.PacketType.BINARY_ACK:
this.onack(packet);
break;
case socket_io_parser_1.PacketType.DISCONNECT:
this.ondisconnect();
break;
case socket_io_parser_1.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: socket_io_parser_1.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: socket_io_parser_1.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);
}
}
}
}
exports.Socket = Socket;

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 {};

View File

@@ -0,0 +1,69 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.url = url;
const engine_io_client_1 = require("engine.io-client");
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("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
*/
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 = (0, engine_io_client_1.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;
}

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";

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;

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 {};

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);
}
}
}
}

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 {};

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;
}

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";

View File

@@ -0,0 +1,58 @@
import { url } from "./url.js";
import { Manager } from "./manager.js";
import { Socket } from "./socket.js";
/**
* 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) {
io = new Manager(source, opts);
}
else {
if (!cache[id]) {
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,367 @@
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";
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) {
if (~this._readyState.indexOf("open"))
return this;
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) => {
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;
// set timer
const timer = this.setTimeoutFn(() => {
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() {
// 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) {
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) {
return;
}
}
this._close();
}
/**
* Writes a packet.
*
* @param packet
* @private
*/
_packet(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() {
this.subs.forEach((subDestroy) => subDestroy());
this.subs.length = 0;
this.decoder.destroy();
}
/**
* Close the current socket.
*
* @private
*/
_close() {
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;
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) {
this.backoff.reset();
this.emitReserved("reconnect_failed");
this._reconnecting = false;
}
else {
const delay = this.backoff.duration();
this._reconnecting = true;
const timer = this.setTimeoutFn(() => {
if (self.skipReconnect)
return;
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) {
self._reconnecting = false;
self.reconnect();
this.emitReserved("reconnect_error", err);
}
else {
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;

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 {};

View File

@@ -0,0 +1,882 @@
import { PacketType } from "socket.io-parser";
import { on } from "./on.js";
import { Emitter, } from "@socket.io/component-emitter";
/**
* 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++;
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) {
}
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) {
this.sendBuffer.splice(i, 1);
}
}
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) {
this._queue.shift();
if (ack) {
ack(err);
}
}
}
else {
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) {
if (!this.connected || this._queue.length === 0) {
return;
}
const packet = this._queue[0];
if (packet.pending && !force) {
return;
}
packet.pending = true;
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() {
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) {
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 || [];
if (null != packet.id) {
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;
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") {
return;
}
delete this.acks[packet.id];
// @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) {
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() {
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) {
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);
}
}
}
}

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 {};

View File

@@ -0,0 +1,59 @@
import { parse } from "engine.io-client";
/**
* 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)) {
if ("undefined" !== typeof loc) {
uri = loc.protocol + "//" + uri;
}
else {
uri = "https://" + uri;
}
}
// parse
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;
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,20 @@
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca>
Copyright (c) 2018-2021 Josh Junon
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the 'Software'), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,481 @@
# debug
[![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors)
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
A tiny JavaScript debugging utility modelled after Node.js core's debugging
technique. Works in Node.js and web browsers.
## Installation
```bash
$ npm install debug
```
## Usage
`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
Example [_app.js_](./examples/node/app.js):
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %o', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example [_worker.js_](./examples/node/worker.js):
```js
var a = require('debug')('worker:a')
, b = require('debug')('worker:b');
function work() {
a('doing lots of uninteresting work');
setTimeout(work, Math.random() * 1000);
}
work();
function workb() {
b('doing some work');
setTimeout(workb, Math.random() * 2000);
}
workb();
```
The `DEBUG` environment variable is then used to enable these based on space or
comma-delimited names.
Here are some examples:
<img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png">
#### Windows command prompt notes
##### CMD
On Windows the environment variable is set using the `set` command.
```cmd
set DEBUG=*,-not_this
```
Example:
```cmd
set DEBUG=* & node app.js
```
##### PowerShell (VS Code default)
PowerShell uses different syntax to set environment variables.
```cmd
$env:DEBUG = "*,-not_this"
```
Example:
```cmd
$env:DEBUG='app';node app.js
```
Then, run the program to be debugged as usual.
npm script example:
```js
"windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js",
```
## Namespace Colors
Every debug instance has a color generated for it based on its namespace name.
This helps when visually parsing the debug output to identify which debug instance
a debug line belongs to.
#### Node.js
In Node.js, colors are enabled when stderr is a TTY. You also _should_ install
the [`supports-color`](https://npmjs.org/supports-color) module alongside debug,
otherwise debug will only use a small handful of basic colors.
<img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png">
#### Web Browser
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).
<img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png">
## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below:
<img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png">
## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output.
## Wildcards
The `*` character may be used as a wildcard. Suppose for example your library has
debuggers named "connect:bodyParser", "connect:compress", "connect:session",
instead of listing all three with
`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do
`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character.
For example, `DEBUG=*,-connect:*` would include all debuggers except those
starting with "connect:".
## Environment Variables
When running through Node.js, you can set a few environment variables that will
change the behavior of the debug logging:
| Name | Purpose |
|-----------|-------------------------------------------------|
| `DEBUG` | Enables/disables specific debugging namespaces. |
| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). |
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
| `DEBUG_DEPTH` | Object inspection depth. |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
__Note:__ The environment variables beginning with `DEBUG_` end up being
converted into an Options object that gets used with `%o`/`%O` formatters.
See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
for the complete list.
## Formatters
Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting.
Below are the officially supported formatters:
| Formatter | Representation |
|-----------|----------------|
| `%O` | Pretty-print an Object on multiple lines. |
| `%o` | Pretty-print an Object all on a single line. |
| `%s` | String. |
| `%d` | Number (both integer and float). |
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
| `%%` | Single percent sign ('%'). This does not consume an argument. |
### Custom formatters
You can add custom formatters by extending the `debug.formatters` object.
For example, if you wanted to add support for rendering a Buffer as hex with
`%h`, you could do something like:
```js
const createDebug = require('debug')
createDebug.formatters.h = (v) => {
return v.toString('hex')
}
// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
// foo this is hex: 68656c6c6f20776f726c6421 +0ms
```
## Browser Support
You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
if you don't want to build it yourself.
Debug's enable state is currently persisted by `localStorage`.
Consider the situation shown below where you have `worker:a` and `worker:b`,
and wish to debug both. You can enable this using `localStorage.debug`:
```js
localStorage.debug = 'worker:*'
```
And then refresh the page.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
b('doing some work');
}, 1200);
```
In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_.
<img width="647" src="https://user-images.githubusercontent.com/7143133/152083257-29034707-c42c-4959-8add-3cee850e6fcf.png">
## Output streams
By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
Example [_stdout.js_](./examples/node/stdout.js):
```js
var debug = require('debug');
var error = debug('app:error');
// by default stderr is used
error('goes to stderr!');
var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');
// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');
```
## Extend
You can simply extend debugger
```js
const log = require('debug')('auth');
//creates new debug instance with extended namespace
const logSign = log.extend('sign');
const logLogin = log.extend('login');
log('hello'); // auth hello
logSign('hello'); //auth:sign hello
logLogin('hello'); //auth:login hello
```
## Set dynamically
You can also enable debug dynamically by calling the `enable()` method :
```js
let debug = require('debug');
console.log(1, debug.enabled('test'));
debug.enable('test');
console.log(2, debug.enabled('test'));
debug.disable();
console.log(3, debug.enabled('test'));
```
print :
```
1 false
2 true
3 false
```
Usage :
`enable(namespaces)`
`namespaces` can include modes separated by a colon and wildcards.
Note that calling `enable()` completely overrides previously set DEBUG variable :
```
$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))'
=> false
```
`disable()`
Will disable all namespaces. The functions returns the namespaces currently
enabled (and skipped). This can be useful if you want to disable debugging
temporarily without knowing what was enabled to begin with.
For example:
```js
let debug = require('debug');
debug.enable('foo:*,-foo:bar');
let namespaces = debug.disable();
debug.enable(namespaces);
```
Note: There is no guarantee that the string will be identical to the initial
enable string, but semantically they will be identical.
## Checking whether a debug target is enabled
After you've created a debug instance, you can determine whether or not it is
enabled by checking the `enabled` property:
```javascript
const debug = require('debug')('http');
if (debug.enabled) {
// do stuff...
}
```
You can also manually toggle this property to force the debug instance to be
enabled or disabled.
## Usage in child processes
Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process.
For example:
```javascript
worker = fork(WORKER_WRAP_PATH, [workerPath], {
stdio: [
/* stdin: */ 0,
/* stdout: */ 'pipe',
/* stderr: */ 'pipe',
'ipc',
],
env: Object.assign({}, process.env, {
DEBUG_COLORS: 1 // without this settings, colors won't be shown
}),
});
worker.stderr.pipe(process.stderr, { end: false });
```
## Authors
- TJ Holowaychuk
- Nathan Rajlich
- Andrew Rhyne
- Josh Junon
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>
## License
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
Copyright (c) 2018-2021 Josh Junon
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,60 @@
{
"name": "debug",
"version": "4.3.7",
"repository": {
"type": "git",
"url": "git://github.com/debug-js/debug.git"
},
"description": "Lightweight debugging utility for Node.js and the browser",
"keywords": [
"debug",
"log",
"debugger"
],
"files": [
"src",
"LICENSE",
"README.md"
],
"author": "Josh Junon (https://github.com/qix-)",
"contributors": [
"TJ Holowaychuk <tj@vision-media.ca>",
"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io)",
"Andrew Rhyne <rhyneandrew@gmail.com>"
],
"license": "MIT",
"scripts": {
"lint": "xo",
"test": "npm run test:node && npm run test:browser && npm run lint",
"test:node": "istanbul cover _mocha -- test.js test.node.js",
"test:browser": "karma start --single-run",
"test:coverage": "cat ./coverage/lcov.info | coveralls"
},
"dependencies": {
"ms": "^2.1.3"
},
"devDependencies": {
"brfs": "^2.0.1",
"browserify": "^16.2.3",
"coveralls": "^3.0.2",
"istanbul": "^0.4.5",
"karma": "^3.1.4",
"karma-browserify": "^6.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.3.0",
"mocha": "^5.2.0",
"mocha-lcov-reporter": "^1.2.0",
"sinon": "^14.0.0",
"xo": "^0.23.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
},
"main": "./src/index.js",
"browser": "./src/browser.js",
"engines": {
"node": ">=6.0"
}
}

View File

@@ -0,0 +1,271 @@
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
};
})();
/**
* Colors.
*/
exports.colors = [
'#0000CC',
'#0000FF',
'#0033CC',
'#0033FF',
'#0066CC',
'#0066FF',
'#0099CC',
'#0099FF',
'#00CC00',
'#00CC33',
'#00CC66',
'#00CC99',
'#00CCCC',
'#00CCFF',
'#3300CC',
'#3300FF',
'#3333CC',
'#3333FF',
'#3366CC',
'#3366FF',
'#3399CC',
'#3399FF',
'#33CC00',
'#33CC33',
'#33CC66',
'#33CC99',
'#33CCCC',
'#33CCFF',
'#6600CC',
'#6600FF',
'#6633CC',
'#6633FF',
'#66CC00',
'#66CC33',
'#9900CC',
'#9900FF',
'#9933CC',
'#9933FF',
'#99CC00',
'#99CC33',
'#CC0000',
'#CC0033',
'#CC0066',
'#CC0099',
'#CC00CC',
'#CC00FF',
'#CC3300',
'#CC3333',
'#CC3366',
'#CC3399',
'#CC33CC',
'#CC33FF',
'#CC6600',
'#CC6633',
'#CC9900',
'#CC9933',
'#CCCC00',
'#CCCC33',
'#FF0000',
'#FF0033',
'#FF0066',
'#FF0099',
'#FF00CC',
'#FF00FF',
'#FF3300',
'#FF3333',
'#FF3366',
'#FF3399',
'#FF33CC',
'#FF33FF',
'#FF6600',
'#FF6633',
'#FF9900',
'#FF9933',
'#FFCC00',
'#FFCC33'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
}
// Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
let m;
// Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// Is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
// Double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') +
this.namespace +
(this.useColors ? ' %c' : ' ') +
args[0] +
(this.useColors ? '%c ' : ' ') +
'+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, match => {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.debug()` when available.
* No-op when `console.debug` is not a "function".
* If `console.debug` is not available, falls back
* to `console.log`.
*
* @api public
*/
exports.log = console.debug || console.log || (() => {});
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
let r;
try {
r = exports.storage.getItem('debug');
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};

View File

@@ -0,0 +1,274 @@
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
createDebug.destroy = destroy;
Object.keys(env).forEach(key => {
createDebug[key] = env[key];
});
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
// Disabled?
if (!debug.enabled) {
return;
}
const self = debug;
// Set `diff` timestamp
const curr = Number(new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
}
// Apply any `formatters` transformations
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return '%';
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
const val = args[index];
match = formatter.call(self, val);
// Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
Object.defineProperty(debug, 'enabled', {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: v => {
enableOverride = v;
}
});
// Env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
let i;
const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
].join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
let i;
let len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Convert regexp to namespace
*
* @param {RegExp} regxep
* @return {String} namespace
* @api private
*/
function toNamespace(regexp) {
return regexp.toString()
.substring(2, regexp.toString().length - 2)
.replace(/\.\*\?$/, '*');
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
/**
* XXX DO NOT USE. This is a temporary stub function.
* XXX It WILL be removed in the next major release.
*/
function destroy() {
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;

View File

@@ -0,0 +1,10 @@
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}

View File

@@ -0,0 +1,263 @@
/**
* Module dependencies.
*/
const tty = require('tty');
const util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*/
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.destroy = util.deprecate(
() => {},
'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
);
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
try {
// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
// eslint-disable-next-line import/no-extraneous-dependencies
const supportsColor = require('supports-color');
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error) {
// Swallow - we only care if `supports-color` is available; it doesn't have to be.
}
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(key => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
// Camel-case
const prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
// Coerce string value into JS value
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === 'null') {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts ?
Boolean(exports.inspectOpts.colors) :
tty.isatty(process.stderr.fd);
}
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
const {namespace: name, useColors} = this;
if (useColors) {
const c = this.color;
const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
} else {
args[0] = getDate() + name + ' ' + args[0];
}
}
function getDate() {
if (exports.inspectOpts.hideDate) {
return '';
}
return new Date().toISOString() + ' ';
}
/**
* Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.
*/
function log(...args) {
return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %o to `util.inspect()`, all on a single line.
*/
formatters.o = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.split('\n')
.map(str => str.trim())
.join(' ');
};
/**
* Map %O to `util.inspect()`, allowing multiple lines if needed.
*/
formatters.O = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};

View File

@@ -0,0 +1,101 @@
{
"name": "socket.io-client",
"version": "4.8.1",
"description": "Realtime application framework client",
"keywords": [
"realtime",
"framework",
"websocket",
"tcp",
"events",
"client"
],
"files": [
"dist/",
"build/"
],
"type": "commonjs",
"main": "./build/cjs/index.js",
"module": "./build/esm/index.js",
"exports": {
"./package.json": "./package.json",
"./dist/socket.io.js": "./dist/socket.io.js",
"./dist/socket.io.js.map": "./dist/socket.io.js.map",
".": {
"import": {
"types": "./build/esm/index.d.ts",
"node": "./build/esm-debug/index.js",
"default": "./build/esm/index.js"
},
"require": {
"types": "./build/cjs/index.d.ts",
"default": "./build/cjs/index.js"
}
},
"./debug": {
"import": {
"types": "./build/esm/index.d.ts",
"default": "./build/esm-debug/index.js"
},
"require": {
"types": "./build/cjs/index.d.ts",
"default": "./build/cjs/index.js"
}
}
},
"types": "./build/esm/index.d.ts",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.2",
"engine.io-client": "~6.6.1",
"socket.io-parser": "~4.2.4"
},
"scripts": {
"compile": "rimraf ./build && tsc && tsc -p tsconfig.esm.json && ./postcompile.sh",
"test": "npm run format:check && npm run compile && if test \"$BROWSERS\" = \"1\" ; then npm run test:browser; else npm run test:node; fi",
"test:node": "mocha --require ts-node/register --require test/support/hooks.ts --exit test/index.ts",
"test:browser": "ts-node test/browser-runner.ts",
"test:types": "tsd",
"build": "rollup -c support/rollup.config.umd.js && rollup -c support/rollup.config.esm.js && rollup -c support/rollup.config.umd.msgpack.js",
"bundle-size": "node support/bundle-size.js",
"format:check": "prettier --check \"*.js\" \"lib/**/*.ts\" \"test/**/*.ts\" \"support/**/*.js\"",
"format:fix": "prettier --write \"*.js\" \"lib/**/*.ts\" \"test/**/*.ts\" \"support/**/*.js\"",
"prepack": "npm run compile"
},
"contributors": [
{
"name": "Guillermo Rauch",
"email": "rauchg@gmail.com"
},
{
"name": "Arnout Kazemier",
"email": "info@3rd-eden.com"
},
{
"name": "Vladimir Dronnikov",
"email": "dronnikov@gmail.com"
},
{
"name": "Einar Otto Stangvik",
"email": "einaros@gmail.com"
}
],
"homepage": "https://github.com/socketio/socket.io/tree/main/packages/socket.io-client#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/socketio/socket.io.git"
},
"bugs": {
"url": "https://github.com/socketio/socket.io/issues"
},
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"tsd": {
"directory": "test"
},
"browser": {
"./test/node.ts": false
}
}