@zaplier/sdk 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -6251,15 +6251,22 @@ class ElysiaWebSocketTransport {
6251
6251
  }
6252
6252
  };
6253
6253
  this.ws?.addEventListener('message', messageHandler);
6254
- // Send the tracking data
6254
+ // Send the complete tracking data payload (includes fingerprintHash, stableCoreHash, etc.)
6255
6255
  this.ws?.send(JSON.stringify({
6256
+ // Include all data from the SDK payload
6257
+ ...data,
6258
+ // Override/ensure essential fields for WebSocket transport
6256
6259
  eventId: data.eventId || crypto.randomUUID(),
6257
6260
  sessionId: data.sessionId || data.s,
6258
6261
  eventType: data.eventType || data.type || 'websocket_event',
6259
6262
  eventName: data.eventName || data.name,
6260
6263
  url: data.url,
6261
6264
  userAgent: data.userAgent || navigator.userAgent,
6262
- timestamp: new Date().toISOString()
6265
+ timestamp: new Date().toISOString(),
6266
+ // Ensure these critical fields are included for identity resolution
6267
+ fingerprintHash: data.fingerprintHash,
6268
+ stableCoreHash: data.stableCoreHash,
6269
+ stableCoreVector: data.stableCoreVector
6263
6270
  }));
6264
6271
  // Timeout after 5 seconds
6265
6272
  setTimeout(() => {
@@ -6319,100 +6326,6 @@ class ElysiaWebSocketTransport {
6319
6326
  }
6320
6327
  }
6321
6328
  }
6322
- /**
6323
- * Socket.io Transport (Real-time bidirectional communication for anti-adblock)
6324
- */
6325
- class SocketIOTransport {
6326
- constructor(baseUrl) {
6327
- this.name = 'socketio';
6328
- this.available = typeof WebSocket !== 'undefined';
6329
- this.connected = false;
6330
- this.baseUrl = baseUrl;
6331
- }
6332
- async send(data, _endpoint) {
6333
- const start = Date.now();
6334
- if (!this.available) {
6335
- return { success: false, method: this.name, error: 'WebRTC not available' };
6336
- }
6337
- try {
6338
- if (!this.connected) {
6339
- await this.connect();
6340
- }
6341
- return new Promise((resolve) => {
6342
- // Emit tracking data via enhanced WebSocket
6343
- this.socket.emit('track', data);
6344
- // Listen for success response
6345
- this.socket.once('track_success', () => {
6346
- resolve({
6347
- success: true,
6348
- method: this.name,
6349
- latency: Date.now() - start
6350
- });
6351
- });
6352
- // Listen for error response
6353
- this.socket.once('track_error', (error) => {
6354
- resolve({
6355
- success: false,
6356
- method: this.name,
6357
- error: error.error || 'WebSocket send failed'
6358
- });
6359
- });
6360
- // Timeout after 5 seconds
6361
- setTimeout(() => {
6362
- resolve({
6363
- success: false,
6364
- method: this.name,
6365
- error: 'WebSocket timeout'
6366
- });
6367
- }, 5000);
6368
- });
6369
- }
6370
- catch (error) {
6371
- return {
6372
- success: false,
6373
- method: this.name,
6374
- error: error instanceof Error ? error.message : String(error)
6375
- };
6376
- }
6377
- }
6378
- async connect() {
6379
- return new Promise((resolve, reject) => {
6380
- try {
6381
- // Use dynamic import to load socket.io-client only when needed
6382
- Promise.resolve().then(function () { return index; }).then(({ io }) => {
6383
- // Extract domain from baseUrl - preserve protocol (HTTP/HTTPS)
6384
- const url = new URL(this.baseUrl);
6385
- const socketUrl = `${url.protocol}//${url.host}`;
6386
- this.socket = io(socketUrl, {
6387
- transports: ['polling', 'websocket'], // Try polling first for better proxy compatibility
6388
- timeout: 5000,
6389
- upgrade: true,
6390
- rememberUpgrade: false
6391
- });
6392
- this.socket.on('connect', () => {
6393
- this.connected = true;
6394
- resolve();
6395
- });
6396
- this.socket.on('connect_error', (error) => {
6397
- reject(error);
6398
- });
6399
- this.socket.on('disconnect', () => {
6400
- this.connected = false;
6401
- });
6402
- }).catch(reject);
6403
- }
6404
- catch (error) {
6405
- reject(error);
6406
- }
6407
- });
6408
- }
6409
- destroy() {
6410
- if (this.socket) {
6411
- this.socket.disconnect();
6412
- this.connected = false;
6413
- }
6414
- }
6415
- }
6416
6329
  /**
6417
6330
  * WebRTC DataChannel Transport (experimental - legacy)
6418
6331
  */
@@ -6517,7 +6430,6 @@ class AntiAdblockManager {
6517
6430
  initializeTransports() {
6518
6431
  const transportMap = {
6519
6432
  'elysia-websocket': () => new ElysiaWebSocketTransport(this.baseUrl, this.token),
6520
- socketio: () => new SocketIOTransport(this.baseUrl),
6521
6433
  fetch: () => new FetchTransport(),
6522
6434
  resource: () => new ResourceSpoofTransport(this.baseUrl),
6523
6435
  webrtc: () => new WebRTCTransport()
@@ -12822,4045 +12734,6 @@ var deviceSignals = /*#__PURE__*/Object.freeze({
12822
12734
  collectDeviceSignals: collectDeviceSignals
12823
12735
  });
12824
12736
 
12825
- const PACKET_TYPES = Object.create(null); // no Map = no polyfill
12826
- PACKET_TYPES["open"] = "0";
12827
- PACKET_TYPES["close"] = "1";
12828
- PACKET_TYPES["ping"] = "2";
12829
- PACKET_TYPES["pong"] = "3";
12830
- PACKET_TYPES["message"] = "4";
12831
- PACKET_TYPES["upgrade"] = "5";
12832
- PACKET_TYPES["noop"] = "6";
12833
- const PACKET_TYPES_REVERSE = Object.create(null);
12834
- Object.keys(PACKET_TYPES).forEach((key) => {
12835
- PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
12836
- });
12837
- const ERROR_PACKET = { type: "error", data: "parser error" };
12838
-
12839
- const withNativeBlob$1 = typeof Blob === "function" ||
12840
- (typeof Blob !== "undefined" &&
12841
- Object.prototype.toString.call(Blob) === "[object BlobConstructor]");
12842
- const withNativeArrayBuffer$2 = typeof ArrayBuffer === "function";
12843
- // ArrayBuffer.isView method is not defined in IE10
12844
- const isView$1 = (obj) => {
12845
- return typeof ArrayBuffer.isView === "function"
12846
- ? ArrayBuffer.isView(obj)
12847
- : obj && obj.buffer instanceof ArrayBuffer;
12848
- };
12849
- const encodePacket = ({ type, data }, supportsBinary, callback) => {
12850
- if (withNativeBlob$1 && data instanceof Blob) {
12851
- if (supportsBinary) {
12852
- return callback(data);
12853
- }
12854
- else {
12855
- return encodeBlobAsBase64(data, callback);
12856
- }
12857
- }
12858
- else if (withNativeArrayBuffer$2 &&
12859
- (data instanceof ArrayBuffer || isView$1(data))) {
12860
- if (supportsBinary) {
12861
- return callback(data);
12862
- }
12863
- else {
12864
- return encodeBlobAsBase64(new Blob([data]), callback);
12865
- }
12866
- }
12867
- // plain string
12868
- return callback(PACKET_TYPES[type] + (data || ""));
12869
- };
12870
- const encodeBlobAsBase64 = (data, callback) => {
12871
- const fileReader = new FileReader();
12872
- fileReader.onload = function () {
12873
- const content = fileReader.result.split(",")[1];
12874
- callback("b" + (content || ""));
12875
- };
12876
- return fileReader.readAsDataURL(data);
12877
- };
12878
- function toArray(data) {
12879
- if (data instanceof Uint8Array) {
12880
- return data;
12881
- }
12882
- else if (data instanceof ArrayBuffer) {
12883
- return new Uint8Array(data);
12884
- }
12885
- else {
12886
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
12887
- }
12888
- }
12889
- let TEXT_ENCODER;
12890
- function encodePacketToBinary(packet, callback) {
12891
- if (withNativeBlob$1 && packet.data instanceof Blob) {
12892
- return packet.data.arrayBuffer().then(toArray).then(callback);
12893
- }
12894
- else if (withNativeArrayBuffer$2 &&
12895
- (packet.data instanceof ArrayBuffer || isView$1(packet.data))) {
12896
- return callback(toArray(packet.data));
12897
- }
12898
- encodePacket(packet, false, (encoded) => {
12899
- if (!TEXT_ENCODER) {
12900
- TEXT_ENCODER = new TextEncoder();
12901
- }
12902
- callback(TEXT_ENCODER.encode(encoded));
12903
- });
12904
- }
12905
-
12906
- // imported from https://github.com/socketio/base64-arraybuffer
12907
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
12908
- // Use a lookup table to find the index.
12909
- const lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
12910
- for (let i = 0; i < chars.length; i++) {
12911
- lookup$1[chars.charCodeAt(i)] = i;
12912
- }
12913
- const decode$1 = (base64) => {
12914
- let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
12915
- if (base64[base64.length - 1] === '=') {
12916
- bufferLength--;
12917
- if (base64[base64.length - 2] === '=') {
12918
- bufferLength--;
12919
- }
12920
- }
12921
- const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
12922
- for (i = 0; i < len; i += 4) {
12923
- encoded1 = lookup$1[base64.charCodeAt(i)];
12924
- encoded2 = lookup$1[base64.charCodeAt(i + 1)];
12925
- encoded3 = lookup$1[base64.charCodeAt(i + 2)];
12926
- encoded4 = lookup$1[base64.charCodeAt(i + 3)];
12927
- bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
12928
- bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
12929
- bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
12930
- }
12931
- return arraybuffer;
12932
- };
12933
-
12934
- const withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
12935
- const decodePacket = (encodedPacket, binaryType) => {
12936
- if (typeof encodedPacket !== "string") {
12937
- return {
12938
- type: "message",
12939
- data: mapBinary(encodedPacket, binaryType),
12940
- };
12941
- }
12942
- const type = encodedPacket.charAt(0);
12943
- if (type === "b") {
12944
- return {
12945
- type: "message",
12946
- data: decodeBase64Packet(encodedPacket.substring(1), binaryType),
12947
- };
12948
- }
12949
- const packetType = PACKET_TYPES_REVERSE[type];
12950
- if (!packetType) {
12951
- return ERROR_PACKET;
12952
- }
12953
- return encodedPacket.length > 1
12954
- ? {
12955
- type: PACKET_TYPES_REVERSE[type],
12956
- data: encodedPacket.substring(1),
12957
- }
12958
- : {
12959
- type: PACKET_TYPES_REVERSE[type],
12960
- };
12961
- };
12962
- const decodeBase64Packet = (data, binaryType) => {
12963
- if (withNativeArrayBuffer$1) {
12964
- const decoded = decode$1(data);
12965
- return mapBinary(decoded, binaryType);
12966
- }
12967
- else {
12968
- return { base64: true, data }; // fallback for old browsers
12969
- }
12970
- };
12971
- const mapBinary = (data, binaryType) => {
12972
- switch (binaryType) {
12973
- case "blob":
12974
- if (data instanceof Blob) {
12975
- // from WebSocket + binaryType "blob"
12976
- return data;
12977
- }
12978
- else {
12979
- // from HTTP long-polling or WebTransport
12980
- return new Blob([data]);
12981
- }
12982
- case "arraybuffer":
12983
- default:
12984
- if (data instanceof ArrayBuffer) {
12985
- // from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer"
12986
- return data;
12987
- }
12988
- else {
12989
- // from WebTransport (Uint8Array)
12990
- return data.buffer;
12991
- }
12992
- }
12993
- };
12994
-
12995
- const SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
12996
- const encodePayload = (packets, callback) => {
12997
- // some packets may be added to the array while encoding, so the initial length must be saved
12998
- const length = packets.length;
12999
- const encodedPackets = new Array(length);
13000
- let count = 0;
13001
- packets.forEach((packet, i) => {
13002
- // force base64 encoding for binary packets
13003
- encodePacket(packet, false, (encodedPacket) => {
13004
- encodedPackets[i] = encodedPacket;
13005
- if (++count === length) {
13006
- callback(encodedPackets.join(SEPARATOR));
13007
- }
13008
- });
13009
- });
13010
- };
13011
- const decodePayload = (encodedPayload, binaryType) => {
13012
- const encodedPackets = encodedPayload.split(SEPARATOR);
13013
- const packets = [];
13014
- for (let i = 0; i < encodedPackets.length; i++) {
13015
- const decodedPacket = decodePacket(encodedPackets[i], binaryType);
13016
- packets.push(decodedPacket);
13017
- if (decodedPacket.type === "error") {
13018
- break;
13019
- }
13020
- }
13021
- return packets;
13022
- };
13023
- function createPacketEncoderStream() {
13024
- return new TransformStream({
13025
- transform(packet, controller) {
13026
- encodePacketToBinary(packet, (encodedPacket) => {
13027
- const payloadLength = encodedPacket.length;
13028
- let header;
13029
- // inspired by the WebSocket format: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#decoding_payload_length
13030
- if (payloadLength < 126) {
13031
- header = new Uint8Array(1);
13032
- new DataView(header.buffer).setUint8(0, payloadLength);
13033
- }
13034
- else if (payloadLength < 65536) {
13035
- header = new Uint8Array(3);
13036
- const view = new DataView(header.buffer);
13037
- view.setUint8(0, 126);
13038
- view.setUint16(1, payloadLength);
13039
- }
13040
- else {
13041
- header = new Uint8Array(9);
13042
- const view = new DataView(header.buffer);
13043
- view.setUint8(0, 127);
13044
- view.setBigUint64(1, BigInt(payloadLength));
13045
- }
13046
- // first bit indicates whether the payload is plain text (0) or binary (1)
13047
- if (packet.data && typeof packet.data !== "string") {
13048
- header[0] |= 0x80;
13049
- }
13050
- controller.enqueue(header);
13051
- controller.enqueue(encodedPacket);
13052
- });
13053
- },
13054
- });
13055
- }
13056
- let TEXT_DECODER;
13057
- function totalLength(chunks) {
13058
- return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
13059
- }
13060
- function concatChunks(chunks, size) {
13061
- if (chunks[0].length === size) {
13062
- return chunks.shift();
13063
- }
13064
- const buffer = new Uint8Array(size);
13065
- let j = 0;
13066
- for (let i = 0; i < size; i++) {
13067
- buffer[i] = chunks[0][j++];
13068
- if (j === chunks[0].length) {
13069
- chunks.shift();
13070
- j = 0;
13071
- }
13072
- }
13073
- if (chunks.length && j < chunks[0].length) {
13074
- chunks[0] = chunks[0].slice(j);
13075
- }
13076
- return buffer;
13077
- }
13078
- function createPacketDecoderStream(maxPayload, binaryType) {
13079
- if (!TEXT_DECODER) {
13080
- TEXT_DECODER = new TextDecoder();
13081
- }
13082
- const chunks = [];
13083
- let state = 0 /* State.READ_HEADER */;
13084
- let expectedLength = -1;
13085
- let isBinary = false;
13086
- return new TransformStream({
13087
- transform(chunk, controller) {
13088
- chunks.push(chunk);
13089
- while (true) {
13090
- if (state === 0 /* State.READ_HEADER */) {
13091
- if (totalLength(chunks) < 1) {
13092
- break;
13093
- }
13094
- const header = concatChunks(chunks, 1);
13095
- isBinary = (header[0] & 0x80) === 0x80;
13096
- expectedLength = header[0] & 0x7f;
13097
- if (expectedLength < 126) {
13098
- state = 3 /* State.READ_PAYLOAD */;
13099
- }
13100
- else if (expectedLength === 126) {
13101
- state = 1 /* State.READ_EXTENDED_LENGTH_16 */;
13102
- }
13103
- else {
13104
- state = 2 /* State.READ_EXTENDED_LENGTH_64 */;
13105
- }
13106
- }
13107
- else if (state === 1 /* State.READ_EXTENDED_LENGTH_16 */) {
13108
- if (totalLength(chunks) < 2) {
13109
- break;
13110
- }
13111
- const headerArray = concatChunks(chunks, 2);
13112
- expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
13113
- state = 3 /* State.READ_PAYLOAD */;
13114
- }
13115
- else if (state === 2 /* State.READ_EXTENDED_LENGTH_64 */) {
13116
- if (totalLength(chunks) < 8) {
13117
- break;
13118
- }
13119
- const headerArray = concatChunks(chunks, 8);
13120
- const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
13121
- const n = view.getUint32(0);
13122
- if (n > Math.pow(2, 53 - 32) - 1) {
13123
- // the maximum safe integer in JavaScript is 2^53 - 1
13124
- controller.enqueue(ERROR_PACKET);
13125
- break;
13126
- }
13127
- expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
13128
- state = 3 /* State.READ_PAYLOAD */;
13129
- }
13130
- else {
13131
- if (totalLength(chunks) < expectedLength) {
13132
- break;
13133
- }
13134
- const data = concatChunks(chunks, expectedLength);
13135
- controller.enqueue(decodePacket(isBinary ? data : TEXT_DECODER.decode(data), binaryType));
13136
- state = 0 /* State.READ_HEADER */;
13137
- }
13138
- if (expectedLength === 0 || expectedLength > maxPayload) {
13139
- controller.enqueue(ERROR_PACKET);
13140
- break;
13141
- }
13142
- }
13143
- },
13144
- });
13145
- }
13146
- const protocol$1 = 4;
13147
-
13148
- /**
13149
- * Initialize a new `Emitter`.
13150
- *
13151
- * @api public
13152
- */
13153
-
13154
- function Emitter(obj) {
13155
- if (obj) return mixin(obj);
13156
- }
13157
-
13158
- /**
13159
- * Mixin the emitter properties.
13160
- *
13161
- * @param {Object} obj
13162
- * @return {Object}
13163
- * @api private
13164
- */
13165
-
13166
- function mixin(obj) {
13167
- for (var key in Emitter.prototype) {
13168
- obj[key] = Emitter.prototype[key];
13169
- }
13170
- return obj;
13171
- }
13172
-
13173
- /**
13174
- * Listen on the given `event` with `fn`.
13175
- *
13176
- * @param {String} event
13177
- * @param {Function} fn
13178
- * @return {Emitter}
13179
- * @api public
13180
- */
13181
-
13182
- Emitter.prototype.on =
13183
- Emitter.prototype.addEventListener = function(event, fn){
13184
- this._callbacks = this._callbacks || {};
13185
- (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
13186
- .push(fn);
13187
- return this;
13188
- };
13189
-
13190
- /**
13191
- * Adds an `event` listener that will be invoked a single
13192
- * time then automatically removed.
13193
- *
13194
- * @param {String} event
13195
- * @param {Function} fn
13196
- * @return {Emitter}
13197
- * @api public
13198
- */
13199
-
13200
- Emitter.prototype.once = function(event, fn){
13201
- function on() {
13202
- this.off(event, on);
13203
- fn.apply(this, arguments);
13204
- }
13205
-
13206
- on.fn = fn;
13207
- this.on(event, on);
13208
- return this;
13209
- };
13210
-
13211
- /**
13212
- * Remove the given callback for `event` or all
13213
- * registered callbacks.
13214
- *
13215
- * @param {String} event
13216
- * @param {Function} fn
13217
- * @return {Emitter}
13218
- * @api public
13219
- */
13220
-
13221
- Emitter.prototype.off =
13222
- Emitter.prototype.removeListener =
13223
- Emitter.prototype.removeAllListeners =
13224
- Emitter.prototype.removeEventListener = function(event, fn){
13225
- this._callbacks = this._callbacks || {};
13226
-
13227
- // all
13228
- if (0 == arguments.length) {
13229
- this._callbacks = {};
13230
- return this;
13231
- }
13232
-
13233
- // specific event
13234
- var callbacks = this._callbacks['$' + event];
13235
- if (!callbacks) return this;
13236
-
13237
- // remove all handlers
13238
- if (1 == arguments.length) {
13239
- delete this._callbacks['$' + event];
13240
- return this;
13241
- }
13242
-
13243
- // remove specific handler
13244
- var cb;
13245
- for (var i = 0; i < callbacks.length; i++) {
13246
- cb = callbacks[i];
13247
- if (cb === fn || cb.fn === fn) {
13248
- callbacks.splice(i, 1);
13249
- break;
13250
- }
13251
- }
13252
-
13253
- // Remove event specific arrays for event types that no
13254
- // one is subscribed for to avoid memory leak.
13255
- if (callbacks.length === 0) {
13256
- delete this._callbacks['$' + event];
13257
- }
13258
-
13259
- return this;
13260
- };
13261
-
13262
- /**
13263
- * Emit `event` with the given args.
13264
- *
13265
- * @param {String} event
13266
- * @param {Mixed} ...
13267
- * @return {Emitter}
13268
- */
13269
-
13270
- Emitter.prototype.emit = function(event){
13271
- this._callbacks = this._callbacks || {};
13272
-
13273
- var args = new Array(arguments.length - 1)
13274
- , callbacks = this._callbacks['$' + event];
13275
-
13276
- for (var i = 1; i < arguments.length; i++) {
13277
- args[i - 1] = arguments[i];
13278
- }
13279
-
13280
- if (callbacks) {
13281
- callbacks = callbacks.slice(0);
13282
- for (var i = 0, len = callbacks.length; i < len; ++i) {
13283
- callbacks[i].apply(this, args);
13284
- }
13285
- }
13286
-
13287
- return this;
13288
- };
13289
-
13290
- // alias used for reserved events (protected method)
13291
- Emitter.prototype.emitReserved = Emitter.prototype.emit;
13292
-
13293
- /**
13294
- * Return array of callbacks for `event`.
13295
- *
13296
- * @param {String} event
13297
- * @return {Array}
13298
- * @api public
13299
- */
13300
-
13301
- Emitter.prototype.listeners = function(event){
13302
- this._callbacks = this._callbacks || {};
13303
- return this._callbacks['$' + event] || [];
13304
- };
13305
-
13306
- /**
13307
- * Check if this emitter has `event` handlers.
13308
- *
13309
- * @param {String} event
13310
- * @return {Boolean}
13311
- * @api public
13312
- */
13313
-
13314
- Emitter.prototype.hasListeners = function(event){
13315
- return !! this.listeners(event).length;
13316
- };
13317
-
13318
- const nextTick = (() => {
13319
- const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
13320
- if (isPromiseAvailable) {
13321
- return (cb) => Promise.resolve().then(cb);
13322
- }
13323
- else {
13324
- return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
13325
- }
13326
- })();
13327
- const globalThisShim = (() => {
13328
- if (typeof self !== "undefined") {
13329
- return self;
13330
- }
13331
- else if (typeof window !== "undefined") {
13332
- return window;
13333
- }
13334
- else {
13335
- return Function("return this")();
13336
- }
13337
- })();
13338
- const defaultBinaryType = "arraybuffer";
13339
- function createCookieJar() { }
13340
-
13341
- function pick(obj, ...attr) {
13342
- return attr.reduce((acc, k) => {
13343
- if (obj.hasOwnProperty(k)) {
13344
- acc[k] = obj[k];
13345
- }
13346
- return acc;
13347
- }, {});
13348
- }
13349
- // Keep a reference to the real timeout functions so they can be used when overridden
13350
- const NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
13351
- const NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
13352
- function installTimerFunctions(obj, opts) {
13353
- if (opts.useNativeTimers) {
13354
- obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
13355
- obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
13356
- }
13357
- else {
13358
- obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
13359
- obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
13360
- }
13361
- }
13362
- // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
13363
- const BASE64_OVERHEAD = 1.33;
13364
- // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
13365
- function byteLength(obj) {
13366
- if (typeof obj === "string") {
13367
- return utf8Length(obj);
13368
- }
13369
- // arraybuffer or blob
13370
- return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
13371
- }
13372
- function utf8Length(str) {
13373
- let c = 0, length = 0;
13374
- for (let i = 0, l = str.length; i < l; i++) {
13375
- c = str.charCodeAt(i);
13376
- if (c < 0x80) {
13377
- length += 1;
13378
- }
13379
- else if (c < 0x800) {
13380
- length += 2;
13381
- }
13382
- else if (c < 0xd800 || c >= 0xe000) {
13383
- length += 3;
13384
- }
13385
- else {
13386
- i++;
13387
- length += 4;
13388
- }
13389
- }
13390
- return length;
13391
- }
13392
- /**
13393
- * Generates a random 8-characters string.
13394
- */
13395
- function randomString() {
13396
- return (Date.now().toString(36).substring(3) +
13397
- Math.random().toString(36).substring(2, 5));
13398
- }
13399
-
13400
- // imported from https://github.com/galkn/querystring
13401
- /**
13402
- * Compiles a querystring
13403
- * Returns string representation of the object
13404
- *
13405
- * @param {Object}
13406
- * @api private
13407
- */
13408
- function encode(obj) {
13409
- let str = '';
13410
- for (let i in obj) {
13411
- if (obj.hasOwnProperty(i)) {
13412
- if (str.length)
13413
- str += '&';
13414
- str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
13415
- }
13416
- }
13417
- return str;
13418
- }
13419
- /**
13420
- * Parses a simple querystring into an object
13421
- *
13422
- * @param {String} qs
13423
- * @api private
13424
- */
13425
- function decode(qs) {
13426
- let qry = {};
13427
- let pairs = qs.split('&');
13428
- for (let i = 0, l = pairs.length; i < l; i++) {
13429
- let pair = pairs[i].split('=');
13430
- qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
13431
- }
13432
- return qry;
13433
- }
13434
-
13435
- class TransportError extends Error {
13436
- constructor(reason, description, context) {
13437
- super(reason);
13438
- this.description = description;
13439
- this.context = context;
13440
- this.type = "TransportError";
13441
- }
13442
- }
13443
- class Transport extends Emitter {
13444
- /**
13445
- * Transport abstract constructor.
13446
- *
13447
- * @param {Object} opts - options
13448
- * @protected
13449
- */
13450
- constructor(opts) {
13451
- super();
13452
- this.writable = false;
13453
- installTimerFunctions(this, opts);
13454
- this.opts = opts;
13455
- this.query = opts.query;
13456
- this.socket = opts.socket;
13457
- this.supportsBinary = !opts.forceBase64;
13458
- }
13459
- /**
13460
- * Emits an error.
13461
- *
13462
- * @param {String} reason
13463
- * @param description
13464
- * @param context - the error context
13465
- * @return {Transport} for chaining
13466
- * @protected
13467
- */
13468
- onError(reason, description, context) {
13469
- super.emitReserved("error", new TransportError(reason, description, context));
13470
- return this;
13471
- }
13472
- /**
13473
- * Opens the transport.
13474
- */
13475
- open() {
13476
- this.readyState = "opening";
13477
- this.doOpen();
13478
- return this;
13479
- }
13480
- /**
13481
- * Closes the transport.
13482
- */
13483
- close() {
13484
- if (this.readyState === "opening" || this.readyState === "open") {
13485
- this.doClose();
13486
- this.onClose();
13487
- }
13488
- return this;
13489
- }
13490
- /**
13491
- * Sends multiple packets.
13492
- *
13493
- * @param {Array} packets
13494
- */
13495
- send(packets) {
13496
- if (this.readyState === "open") {
13497
- this.write(packets);
13498
- }
13499
- }
13500
- /**
13501
- * Called upon open
13502
- *
13503
- * @protected
13504
- */
13505
- onOpen() {
13506
- this.readyState = "open";
13507
- this.writable = true;
13508
- super.emitReserved("open");
13509
- }
13510
- /**
13511
- * Called with data.
13512
- *
13513
- * @param {String} data
13514
- * @protected
13515
- */
13516
- onData(data) {
13517
- const packet = decodePacket(data, this.socket.binaryType);
13518
- this.onPacket(packet);
13519
- }
13520
- /**
13521
- * Called with a decoded packet.
13522
- *
13523
- * @protected
13524
- */
13525
- onPacket(packet) {
13526
- super.emitReserved("packet", packet);
13527
- }
13528
- /**
13529
- * Called upon close.
13530
- *
13531
- * @protected
13532
- */
13533
- onClose(details) {
13534
- this.readyState = "closed";
13535
- super.emitReserved("close", details);
13536
- }
13537
- /**
13538
- * Pauses the transport, in order not to lose packets during an upgrade.
13539
- *
13540
- * @param onPause
13541
- */
13542
- pause(onPause) { }
13543
- createUri(schema, query = {}) {
13544
- return (schema +
13545
- "://" +
13546
- this._hostname() +
13547
- this._port() +
13548
- this.opts.path +
13549
- this._query(query));
13550
- }
13551
- _hostname() {
13552
- const hostname = this.opts.hostname;
13553
- return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
13554
- }
13555
- _port() {
13556
- if (this.opts.port &&
13557
- ((this.opts.secure && Number(this.opts.port !== 443)) ||
13558
- (!this.opts.secure && Number(this.opts.port) !== 80))) {
13559
- return ":" + this.opts.port;
13560
- }
13561
- else {
13562
- return "";
13563
- }
13564
- }
13565
- _query(query) {
13566
- const encodedQuery = encode(query);
13567
- return encodedQuery.length ? "?" + encodedQuery : "";
13568
- }
13569
- }
13570
-
13571
- class Polling extends Transport {
13572
- constructor() {
13573
- super(...arguments);
13574
- this._polling = false;
13575
- }
13576
- get name() {
13577
- return "polling";
13578
- }
13579
- /**
13580
- * Opens the socket (triggers polling). We write a PING message to determine
13581
- * when the transport is open.
13582
- *
13583
- * @protected
13584
- */
13585
- doOpen() {
13586
- this._poll();
13587
- }
13588
- /**
13589
- * Pauses polling.
13590
- *
13591
- * @param {Function} onPause - callback upon buffers are flushed and transport is paused
13592
- * @package
13593
- */
13594
- pause(onPause) {
13595
- this.readyState = "pausing";
13596
- const pause = () => {
13597
- this.readyState = "paused";
13598
- onPause();
13599
- };
13600
- if (this._polling || !this.writable) {
13601
- let total = 0;
13602
- if (this._polling) {
13603
- total++;
13604
- this.once("pollComplete", function () {
13605
- --total || pause();
13606
- });
13607
- }
13608
- if (!this.writable) {
13609
- total++;
13610
- this.once("drain", function () {
13611
- --total || pause();
13612
- });
13613
- }
13614
- }
13615
- else {
13616
- pause();
13617
- }
13618
- }
13619
- /**
13620
- * Starts polling cycle.
13621
- *
13622
- * @private
13623
- */
13624
- _poll() {
13625
- this._polling = true;
13626
- this.doPoll();
13627
- this.emitReserved("poll");
13628
- }
13629
- /**
13630
- * Overloads onData to detect payloads.
13631
- *
13632
- * @protected
13633
- */
13634
- onData(data) {
13635
- const callback = (packet) => {
13636
- // if its the first message we consider the transport open
13637
- if ("opening" === this.readyState && packet.type === "open") {
13638
- this.onOpen();
13639
- }
13640
- // if its a close packet, we close the ongoing requests
13641
- if ("close" === packet.type) {
13642
- this.onClose({ description: "transport closed by the server" });
13643
- return false;
13644
- }
13645
- // otherwise bypass onData and handle the message
13646
- this.onPacket(packet);
13647
- };
13648
- // decode payload
13649
- decodePayload(data, this.socket.binaryType).forEach(callback);
13650
- // if an event did not trigger closing
13651
- if ("closed" !== this.readyState) {
13652
- // if we got data we're not polling
13653
- this._polling = false;
13654
- this.emitReserved("pollComplete");
13655
- if ("open" === this.readyState) {
13656
- this._poll();
13657
- }
13658
- }
13659
- }
13660
- /**
13661
- * For polling, send a close packet.
13662
- *
13663
- * @protected
13664
- */
13665
- doClose() {
13666
- const close = () => {
13667
- this.write([{ type: "close" }]);
13668
- };
13669
- if ("open" === this.readyState) {
13670
- close();
13671
- }
13672
- else {
13673
- // in case we're trying to close while
13674
- // handshaking is in progress (GH-164)
13675
- this.once("open", close);
13676
- }
13677
- }
13678
- /**
13679
- * Writes a packets payload.
13680
- *
13681
- * @param {Array} packets - data packets
13682
- * @protected
13683
- */
13684
- write(packets) {
13685
- this.writable = false;
13686
- encodePayload(packets, (data) => {
13687
- this.doWrite(data, () => {
13688
- this.writable = true;
13689
- this.emitReserved("drain");
13690
- });
13691
- });
13692
- }
13693
- /**
13694
- * Generates uri for connection.
13695
- *
13696
- * @private
13697
- */
13698
- uri() {
13699
- const schema = this.opts.secure ? "https" : "http";
13700
- const query = this.query || {};
13701
- // cache busting is forced
13702
- if (false !== this.opts.timestampRequests) {
13703
- query[this.opts.timestampParam] = randomString();
13704
- }
13705
- if (!this.supportsBinary && !query.sid) {
13706
- query.b64 = 1;
13707
- }
13708
- return this.createUri(schema, query);
13709
- }
13710
- }
13711
-
13712
- // imported from https://github.com/component/has-cors
13713
- let value = false;
13714
- try {
13715
- value = typeof XMLHttpRequest !== 'undefined' &&
13716
- 'withCredentials' in new XMLHttpRequest();
13717
- }
13718
- catch (err) {
13719
- // if XMLHttp support is disabled in IE then it will throw
13720
- // when trying to create
13721
- }
13722
- const hasCORS = value;
13723
-
13724
- function empty() { }
13725
- class BaseXHR extends Polling {
13726
- /**
13727
- * XHR Polling constructor.
13728
- *
13729
- * @param {Object} opts
13730
- * @package
13731
- */
13732
- constructor(opts) {
13733
- super(opts);
13734
- if (typeof location !== "undefined") {
13735
- const isSSL = "https:" === location.protocol;
13736
- let port = location.port;
13737
- // some user agents have empty `location.port`
13738
- if (!port) {
13739
- port = isSSL ? "443" : "80";
13740
- }
13741
- this.xd =
13742
- (typeof location !== "undefined" &&
13743
- opts.hostname !== location.hostname) ||
13744
- port !== opts.port;
13745
- }
13746
- }
13747
- /**
13748
- * Sends data.
13749
- *
13750
- * @param {String} data to send.
13751
- * @param {Function} called upon flush.
13752
- * @private
13753
- */
13754
- doWrite(data, fn) {
13755
- const req = this.request({
13756
- method: "POST",
13757
- data: data,
13758
- });
13759
- req.on("success", fn);
13760
- req.on("error", (xhrStatus, context) => {
13761
- this.onError("xhr post error", xhrStatus, context);
13762
- });
13763
- }
13764
- /**
13765
- * Starts a poll cycle.
13766
- *
13767
- * @private
13768
- */
13769
- doPoll() {
13770
- const req = this.request();
13771
- req.on("data", this.onData.bind(this));
13772
- req.on("error", (xhrStatus, context) => {
13773
- this.onError("xhr poll error", xhrStatus, context);
13774
- });
13775
- this.pollXhr = req;
13776
- }
13777
- }
13778
- class Request extends Emitter {
13779
- /**
13780
- * Request constructor
13781
- *
13782
- * @param {Object} options
13783
- * @package
13784
- */
13785
- constructor(createRequest, uri, opts) {
13786
- super();
13787
- this.createRequest = createRequest;
13788
- installTimerFunctions(this, opts);
13789
- this._opts = opts;
13790
- this._method = opts.method || "GET";
13791
- this._uri = uri;
13792
- this._data = undefined !== opts.data ? opts.data : null;
13793
- this._create();
13794
- }
13795
- /**
13796
- * Creates the XHR object and sends the request.
13797
- *
13798
- * @private
13799
- */
13800
- _create() {
13801
- var _a;
13802
- const opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
13803
- opts.xdomain = !!this._opts.xd;
13804
- const xhr = (this._xhr = this.createRequest(opts));
13805
- try {
13806
- xhr.open(this._method, this._uri, true);
13807
- try {
13808
- if (this._opts.extraHeaders) {
13809
- // @ts-ignore
13810
- xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
13811
- for (let i in this._opts.extraHeaders) {
13812
- if (this._opts.extraHeaders.hasOwnProperty(i)) {
13813
- xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
13814
- }
13815
- }
13816
- }
13817
- }
13818
- catch (e) { }
13819
- if ("POST" === this._method) {
13820
- try {
13821
- xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
13822
- }
13823
- catch (e) { }
13824
- }
13825
- try {
13826
- xhr.setRequestHeader("Accept", "*/*");
13827
- }
13828
- catch (e) { }
13829
- (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
13830
- // ie6 check
13831
- if ("withCredentials" in xhr) {
13832
- xhr.withCredentials = this._opts.withCredentials;
13833
- }
13834
- if (this._opts.requestTimeout) {
13835
- xhr.timeout = this._opts.requestTimeout;
13836
- }
13837
- xhr.onreadystatechange = () => {
13838
- var _a;
13839
- if (xhr.readyState === 3) {
13840
- (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(
13841
- // @ts-ignore
13842
- xhr.getResponseHeader("set-cookie"));
13843
- }
13844
- if (4 !== xhr.readyState)
13845
- return;
13846
- if (200 === xhr.status || 1223 === xhr.status) {
13847
- this._onLoad();
13848
- }
13849
- else {
13850
- // make sure the `error` event handler that's user-set
13851
- // does not throw in the same tick and gets caught here
13852
- this.setTimeoutFn(() => {
13853
- this._onError(typeof xhr.status === "number" ? xhr.status : 0);
13854
- }, 0);
13855
- }
13856
- };
13857
- xhr.send(this._data);
13858
- }
13859
- catch (e) {
13860
- // Need to defer since .create() is called directly from the constructor
13861
- // and thus the 'error' event can only be only bound *after* this exception
13862
- // occurs. Therefore, also, we cannot throw here at all.
13863
- this.setTimeoutFn(() => {
13864
- this._onError(e);
13865
- }, 0);
13866
- return;
13867
- }
13868
- if (typeof document !== "undefined") {
13869
- this._index = Request.requestsCount++;
13870
- Request.requests[this._index] = this;
13871
- }
13872
- }
13873
- /**
13874
- * Called upon error.
13875
- *
13876
- * @private
13877
- */
13878
- _onError(err) {
13879
- this.emitReserved("error", err, this._xhr);
13880
- this._cleanup(true);
13881
- }
13882
- /**
13883
- * Cleans up house.
13884
- *
13885
- * @private
13886
- */
13887
- _cleanup(fromError) {
13888
- if ("undefined" === typeof this._xhr || null === this._xhr) {
13889
- return;
13890
- }
13891
- this._xhr.onreadystatechange = empty;
13892
- if (fromError) {
13893
- try {
13894
- this._xhr.abort();
13895
- }
13896
- catch (e) { }
13897
- }
13898
- if (typeof document !== "undefined") {
13899
- delete Request.requests[this._index];
13900
- }
13901
- this._xhr = null;
13902
- }
13903
- /**
13904
- * Called upon load.
13905
- *
13906
- * @private
13907
- */
13908
- _onLoad() {
13909
- const data = this._xhr.responseText;
13910
- if (data !== null) {
13911
- this.emitReserved("data", data);
13912
- this.emitReserved("success");
13913
- this._cleanup();
13914
- }
13915
- }
13916
- /**
13917
- * Aborts the request.
13918
- *
13919
- * @package
13920
- */
13921
- abort() {
13922
- this._cleanup();
13923
- }
13924
- }
13925
- Request.requestsCount = 0;
13926
- Request.requests = {};
13927
- /**
13928
- * Aborts pending requests when unloading the window. This is needed to prevent
13929
- * memory leaks (e.g. when using IE) and to ensure that no spurious error is
13930
- * emitted.
13931
- */
13932
- if (typeof document !== "undefined") {
13933
- // @ts-ignore
13934
- if (typeof attachEvent === "function") {
13935
- // @ts-ignore
13936
- attachEvent("onunload", unloadHandler);
13937
- }
13938
- else if (typeof addEventListener === "function") {
13939
- const terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
13940
- addEventListener(terminationEvent, unloadHandler, false);
13941
- }
13942
- }
13943
- function unloadHandler() {
13944
- for (let i in Request.requests) {
13945
- if (Request.requests.hasOwnProperty(i)) {
13946
- Request.requests[i].abort();
13947
- }
13948
- }
13949
- }
13950
- const hasXHR2 = (function () {
13951
- const xhr = newRequest({
13952
- xdomain: false,
13953
- });
13954
- return xhr && xhr.responseType !== null;
13955
- })();
13956
- /**
13957
- * HTTP long-polling based on the built-in `XMLHttpRequest` object.
13958
- *
13959
- * Usage: browser
13960
- *
13961
- * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
13962
- */
13963
- class XHR extends BaseXHR {
13964
- constructor(opts) {
13965
- super(opts);
13966
- const forceBase64 = opts && opts.forceBase64;
13967
- this.supportsBinary = hasXHR2 && !forceBase64;
13968
- }
13969
- request(opts = {}) {
13970
- Object.assign(opts, { xd: this.xd }, this.opts);
13971
- return new Request(newRequest, this.uri(), opts);
13972
- }
13973
- }
13974
- function newRequest(opts) {
13975
- const xdomain = opts.xdomain;
13976
- // XMLHttpRequest can be disabled on IE
13977
- try {
13978
- if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
13979
- return new XMLHttpRequest();
13980
- }
13981
- }
13982
- catch (e) { }
13983
- if (!xdomain) {
13984
- try {
13985
- return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
13986
- }
13987
- catch (e) { }
13988
- }
13989
- }
13990
-
13991
- // detect ReactNative environment
13992
- const isReactNative = typeof navigator !== "undefined" &&
13993
- typeof navigator.product === "string" &&
13994
- navigator.product.toLowerCase() === "reactnative";
13995
- class BaseWS extends Transport {
13996
- get name() {
13997
- return "websocket";
13998
- }
13999
- doOpen() {
14000
- const uri = this.uri();
14001
- const protocols = this.opts.protocols;
14002
- // React Native only supports the 'headers' option, and will print a warning if anything else is passed
14003
- const opts = isReactNative
14004
- ? {}
14005
- : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
14006
- if (this.opts.extraHeaders) {
14007
- opts.headers = this.opts.extraHeaders;
14008
- }
14009
- try {
14010
- this.ws = this.createSocket(uri, protocols, opts);
14011
- }
14012
- catch (err) {
14013
- return this.emitReserved("error", err);
14014
- }
14015
- this.ws.binaryType = this.socket.binaryType;
14016
- this.addEventListeners();
14017
- }
14018
- /**
14019
- * Adds event listeners to the socket
14020
- *
14021
- * @private
14022
- */
14023
- addEventListeners() {
14024
- this.ws.onopen = () => {
14025
- if (this.opts.autoUnref) {
14026
- this.ws._socket.unref();
14027
- }
14028
- this.onOpen();
14029
- };
14030
- this.ws.onclose = (closeEvent) => this.onClose({
14031
- description: "websocket connection closed",
14032
- context: closeEvent,
14033
- });
14034
- this.ws.onmessage = (ev) => this.onData(ev.data);
14035
- this.ws.onerror = (e) => this.onError("websocket error", e);
14036
- }
14037
- write(packets) {
14038
- this.writable = false;
14039
- // encodePacket efficient as it uses WS framing
14040
- // no need for encodePayload
14041
- for (let i = 0; i < packets.length; i++) {
14042
- const packet = packets[i];
14043
- const lastPacket = i === packets.length - 1;
14044
- encodePacket(packet, this.supportsBinary, (data) => {
14045
- // Sometimes the websocket has already been closed but the browser didn't
14046
- // have a chance of informing us about it yet, in that case send will
14047
- // throw an error
14048
- try {
14049
- this.doWrite(packet, data);
14050
- }
14051
- catch (e) {
14052
- }
14053
- if (lastPacket) {
14054
- // fake drain
14055
- // defer to next tick to allow Socket to clear writeBuffer
14056
- nextTick(() => {
14057
- this.writable = true;
14058
- this.emitReserved("drain");
14059
- }, this.setTimeoutFn);
14060
- }
14061
- });
14062
- }
14063
- }
14064
- doClose() {
14065
- if (typeof this.ws !== "undefined") {
14066
- this.ws.onerror = () => { };
14067
- this.ws.close();
14068
- this.ws = null;
14069
- }
14070
- }
14071
- /**
14072
- * Generates uri for connection.
14073
- *
14074
- * @private
14075
- */
14076
- uri() {
14077
- const schema = this.opts.secure ? "wss" : "ws";
14078
- const query = this.query || {};
14079
- // append timestamp to URI
14080
- if (this.opts.timestampRequests) {
14081
- query[this.opts.timestampParam] = randomString();
14082
- }
14083
- // communicate binary support capabilities
14084
- if (!this.supportsBinary) {
14085
- query.b64 = 1;
14086
- }
14087
- return this.createUri(schema, query);
14088
- }
14089
- }
14090
- const WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
14091
- /**
14092
- * WebSocket transport based on the built-in `WebSocket` object.
14093
- *
14094
- * Usage: browser, Node.js (since v21), Deno, Bun
14095
- *
14096
- * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
14097
- * @see https://caniuse.com/mdn-api_websocket
14098
- * @see https://nodejs.org/api/globals.html#websocket
14099
- */
14100
- class WS extends BaseWS {
14101
- createSocket(uri, protocols, opts) {
14102
- return !isReactNative
14103
- ? protocols
14104
- ? new WebSocketCtor(uri, protocols)
14105
- : new WebSocketCtor(uri)
14106
- : new WebSocketCtor(uri, protocols, opts);
14107
- }
14108
- doWrite(_packet, data) {
14109
- this.ws.send(data);
14110
- }
14111
- }
14112
-
14113
- /**
14114
- * WebTransport transport based on the built-in `WebTransport` object.
14115
- *
14116
- * Usage: browser, Node.js (with the `@fails-components/webtransport` package)
14117
- *
14118
- * @see https://developer.mozilla.org/en-US/docs/Web/API/WebTransport
14119
- * @see https://caniuse.com/webtransport
14120
- */
14121
- class WT extends Transport {
14122
- get name() {
14123
- return "webtransport";
14124
- }
14125
- doOpen() {
14126
- try {
14127
- // @ts-ignore
14128
- this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
14129
- }
14130
- catch (err) {
14131
- return this.emitReserved("error", err);
14132
- }
14133
- this._transport.closed
14134
- .then(() => {
14135
- this.onClose();
14136
- })
14137
- .catch((err) => {
14138
- this.onError("webtransport error", err);
14139
- });
14140
- // note: we could have used async/await, but that would require some additional polyfills
14141
- this._transport.ready.then(() => {
14142
- this._transport.createBidirectionalStream().then((stream) => {
14143
- const decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
14144
- const reader = stream.readable.pipeThrough(decoderStream).getReader();
14145
- const encoderStream = createPacketEncoderStream();
14146
- encoderStream.readable.pipeTo(stream.writable);
14147
- this._writer = encoderStream.writable.getWriter();
14148
- const read = () => {
14149
- reader
14150
- .read()
14151
- .then(({ done, value }) => {
14152
- if (done) {
14153
- return;
14154
- }
14155
- this.onPacket(value);
14156
- read();
14157
- })
14158
- .catch((err) => {
14159
- });
14160
- };
14161
- read();
14162
- const packet = { type: "open" };
14163
- if (this.query.sid) {
14164
- packet.data = `{"sid":"${this.query.sid}"}`;
14165
- }
14166
- this._writer.write(packet).then(() => this.onOpen());
14167
- });
14168
- });
14169
- }
14170
- write(packets) {
14171
- this.writable = false;
14172
- for (let i = 0; i < packets.length; i++) {
14173
- const packet = packets[i];
14174
- const lastPacket = i === packets.length - 1;
14175
- this._writer.write(packet).then(() => {
14176
- if (lastPacket) {
14177
- nextTick(() => {
14178
- this.writable = true;
14179
- this.emitReserved("drain");
14180
- }, this.setTimeoutFn);
14181
- }
14182
- });
14183
- }
14184
- }
14185
- doClose() {
14186
- var _a;
14187
- (_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
14188
- }
14189
- }
14190
-
14191
- const transports = {
14192
- websocket: WS,
14193
- webtransport: WT,
14194
- polling: XHR,
14195
- };
14196
-
14197
- // imported from https://github.com/galkn/parseuri
14198
- /**
14199
- * Parses a URI
14200
- *
14201
- * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.
14202
- *
14203
- * See:
14204
- * - https://developer.mozilla.org/en-US/docs/Web/API/URL
14205
- * - https://caniuse.com/url
14206
- * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B
14207
- *
14208
- * History of the parse() method:
14209
- * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c
14210
- * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3
14211
- * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242
14212
- *
14213
- * @author Steven Levithan <stevenlevithan.com> (MIT license)
14214
- * @api private
14215
- */
14216
- const re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
14217
- const parts = [
14218
- 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
14219
- ];
14220
- function parse(str) {
14221
- if (str.length > 8000) {
14222
- throw "URI too long";
14223
- }
14224
- const src = str, b = str.indexOf('['), e = str.indexOf(']');
14225
- if (b != -1 && e != -1) {
14226
- str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
14227
- }
14228
- let m = re.exec(str || ''), uri = {}, i = 14;
14229
- while (i--) {
14230
- uri[parts[i]] = m[i] || '';
14231
- }
14232
- if (b != -1 && e != -1) {
14233
- uri.source = src;
14234
- uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
14235
- uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
14236
- uri.ipv6uri = true;
14237
- }
14238
- uri.pathNames = pathNames(uri, uri['path']);
14239
- uri.queryKey = queryKey(uri, uri['query']);
14240
- return uri;
14241
- }
14242
- function pathNames(obj, path) {
14243
- const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
14244
- if (path.slice(0, 1) == '/' || path.length === 0) {
14245
- names.splice(0, 1);
14246
- }
14247
- if (path.slice(-1) == '/') {
14248
- names.splice(names.length - 1, 1);
14249
- }
14250
- return names;
14251
- }
14252
- function queryKey(uri, query) {
14253
- const data = {};
14254
- query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
14255
- if ($1) {
14256
- data[$1] = $2;
14257
- }
14258
- });
14259
- return data;
14260
- }
14261
-
14262
- const withEventListeners = typeof addEventListener === "function" &&
14263
- typeof removeEventListener === "function";
14264
- const OFFLINE_EVENT_LISTENERS = [];
14265
- if (withEventListeners) {
14266
- // within a ServiceWorker, any event handler for the 'offline' event must be added on the initial evaluation of the
14267
- // script, so we create one single event listener here which will forward the event to the socket instances
14268
- addEventListener("offline", () => {
14269
- OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());
14270
- }, false);
14271
- }
14272
- /**
14273
- * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
14274
- * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
14275
- *
14276
- * This class comes without upgrade mechanism, which means that it will keep the first low-level transport that
14277
- * successfully establishes the connection.
14278
- *
14279
- * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
14280
- *
14281
- * @example
14282
- * import { SocketWithoutUpgrade, WebSocket } from "engine.io-client";
14283
- *
14284
- * const socket = new SocketWithoutUpgrade({
14285
- * transports: [WebSocket]
14286
- * });
14287
- *
14288
- * socket.on("open", () => {
14289
- * socket.send("hello");
14290
- * });
14291
- *
14292
- * @see SocketWithUpgrade
14293
- * @see Socket
14294
- */
14295
- class SocketWithoutUpgrade extends Emitter {
14296
- /**
14297
- * Socket constructor.
14298
- *
14299
- * @param {String|Object} uri - uri or options
14300
- * @param {Object} opts - options
14301
- */
14302
- constructor(uri, opts) {
14303
- super();
14304
- this.binaryType = defaultBinaryType;
14305
- this.writeBuffer = [];
14306
- this._prevBufferLen = 0;
14307
- this._pingInterval = -1;
14308
- this._pingTimeout = -1;
14309
- this._maxPayload = -1;
14310
- /**
14311
- * The expiration timestamp of the {@link _pingTimeoutTimer} object is tracked, in case the timer is throttled and the
14312
- * callback is not fired on time. This can happen for example when a laptop is suspended or when a phone is locked.
14313
- */
14314
- this._pingTimeoutTime = Infinity;
14315
- if (uri && "object" === typeof uri) {
14316
- opts = uri;
14317
- uri = null;
14318
- }
14319
- if (uri) {
14320
- const parsedUri = parse(uri);
14321
- opts.hostname = parsedUri.host;
14322
- opts.secure =
14323
- parsedUri.protocol === "https" || parsedUri.protocol === "wss";
14324
- opts.port = parsedUri.port;
14325
- if (parsedUri.query)
14326
- opts.query = parsedUri.query;
14327
- }
14328
- else if (opts.host) {
14329
- opts.hostname = parse(opts.host).host;
14330
- }
14331
- installTimerFunctions(this, opts);
14332
- this.secure =
14333
- null != opts.secure
14334
- ? opts.secure
14335
- : typeof location !== "undefined" && "https:" === location.protocol;
14336
- if (opts.hostname && !opts.port) {
14337
- // if no port is specified manually, use the protocol default
14338
- opts.port = this.secure ? "443" : "80";
14339
- }
14340
- this.hostname =
14341
- opts.hostname ||
14342
- (typeof location !== "undefined" ? location.hostname : "localhost");
14343
- this.port =
14344
- opts.port ||
14345
- (typeof location !== "undefined" && location.port
14346
- ? location.port
14347
- : this.secure
14348
- ? "443"
14349
- : "80");
14350
- this.transports = [];
14351
- this._transportsByName = {};
14352
- opts.transports.forEach((t) => {
14353
- const transportName = t.prototype.name;
14354
- this.transports.push(transportName);
14355
- this._transportsByName[transportName] = t;
14356
- });
14357
- this.opts = Object.assign({
14358
- path: "/engine.io",
14359
- agent: false,
14360
- withCredentials: false,
14361
- upgrade: true,
14362
- timestampParam: "t",
14363
- rememberUpgrade: false,
14364
- addTrailingSlash: true,
14365
- rejectUnauthorized: true,
14366
- perMessageDeflate: {
14367
- threshold: 1024,
14368
- },
14369
- transportOptions: {},
14370
- closeOnBeforeunload: false,
14371
- }, opts);
14372
- this.opts.path =
14373
- this.opts.path.replace(/\/$/, "") +
14374
- (this.opts.addTrailingSlash ? "/" : "");
14375
- if (typeof this.opts.query === "string") {
14376
- this.opts.query = decode(this.opts.query);
14377
- }
14378
- if (withEventListeners) {
14379
- if (this.opts.closeOnBeforeunload) {
14380
- // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
14381
- // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
14382
- // closed/reloaded)
14383
- this._beforeunloadEventListener = () => {
14384
- if (this.transport) {
14385
- // silently close the transport
14386
- this.transport.removeAllListeners();
14387
- this.transport.close();
14388
- }
14389
- };
14390
- addEventListener("beforeunload", this._beforeunloadEventListener, false);
14391
- }
14392
- if (this.hostname !== "localhost") {
14393
- this._offlineEventListener = () => {
14394
- this._onClose("transport close", {
14395
- description: "network connection lost",
14396
- });
14397
- };
14398
- OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);
14399
- }
14400
- }
14401
- if (this.opts.withCredentials) {
14402
- this._cookieJar = createCookieJar();
14403
- }
14404
- this._open();
14405
- }
14406
- /**
14407
- * Creates transport of the given type.
14408
- *
14409
- * @param {String} name - transport name
14410
- * @return {Transport}
14411
- * @private
14412
- */
14413
- createTransport(name) {
14414
- const query = Object.assign({}, this.opts.query);
14415
- // append engine.io protocol identifier
14416
- query.EIO = protocol$1;
14417
- // transport name
14418
- query.transport = name;
14419
- // session id if we already have one
14420
- if (this.id)
14421
- query.sid = this.id;
14422
- const opts = Object.assign({}, this.opts, {
14423
- query,
14424
- socket: this,
14425
- hostname: this.hostname,
14426
- secure: this.secure,
14427
- port: this.port,
14428
- }, this.opts.transportOptions[name]);
14429
- return new this._transportsByName[name](opts);
14430
- }
14431
- /**
14432
- * Initializes transport to use and starts probe.
14433
- *
14434
- * @private
14435
- */
14436
- _open() {
14437
- if (this.transports.length === 0) {
14438
- // Emit error on next tick so it can be listened to
14439
- this.setTimeoutFn(() => {
14440
- this.emitReserved("error", "No transports available");
14441
- }, 0);
14442
- return;
14443
- }
14444
- const transportName = this.opts.rememberUpgrade &&
14445
- SocketWithoutUpgrade.priorWebsocketSuccess &&
14446
- this.transports.indexOf("websocket") !== -1
14447
- ? "websocket"
14448
- : this.transports[0];
14449
- this.readyState = "opening";
14450
- const transport = this.createTransport(transportName);
14451
- transport.open();
14452
- this.setTransport(transport);
14453
- }
14454
- /**
14455
- * Sets the current transport. Disables the existing one (if any).
14456
- *
14457
- * @private
14458
- */
14459
- setTransport(transport) {
14460
- if (this.transport) {
14461
- this.transport.removeAllListeners();
14462
- }
14463
- // set up transport
14464
- this.transport = transport;
14465
- // set up transport listeners
14466
- transport
14467
- .on("drain", this._onDrain.bind(this))
14468
- .on("packet", this._onPacket.bind(this))
14469
- .on("error", this._onError.bind(this))
14470
- .on("close", (reason) => this._onClose("transport close", reason));
14471
- }
14472
- /**
14473
- * Called when connection is deemed open.
14474
- *
14475
- * @private
14476
- */
14477
- onOpen() {
14478
- this.readyState = "open";
14479
- SocketWithoutUpgrade.priorWebsocketSuccess =
14480
- "websocket" === this.transport.name;
14481
- this.emitReserved("open");
14482
- this.flush();
14483
- }
14484
- /**
14485
- * Handles a packet.
14486
- *
14487
- * @private
14488
- */
14489
- _onPacket(packet) {
14490
- if ("opening" === this.readyState ||
14491
- "open" === this.readyState ||
14492
- "closing" === this.readyState) {
14493
- this.emitReserved("packet", packet);
14494
- // Socket is live - any packet counts
14495
- this.emitReserved("heartbeat");
14496
- switch (packet.type) {
14497
- case "open":
14498
- this.onHandshake(JSON.parse(packet.data));
14499
- break;
14500
- case "ping":
14501
- this._sendPacket("pong");
14502
- this.emitReserved("ping");
14503
- this.emitReserved("pong");
14504
- this._resetPingTimeout();
14505
- break;
14506
- case "error":
14507
- const err = new Error("server error");
14508
- // @ts-ignore
14509
- err.code = packet.data;
14510
- this._onError(err);
14511
- break;
14512
- case "message":
14513
- this.emitReserved("data", packet.data);
14514
- this.emitReserved("message", packet.data);
14515
- break;
14516
- }
14517
- }
14518
- }
14519
- /**
14520
- * Called upon handshake completion.
14521
- *
14522
- * @param {Object} data - handshake obj
14523
- * @private
14524
- */
14525
- onHandshake(data) {
14526
- this.emitReserved("handshake", data);
14527
- this.id = data.sid;
14528
- this.transport.query.sid = data.sid;
14529
- this._pingInterval = data.pingInterval;
14530
- this._pingTimeout = data.pingTimeout;
14531
- this._maxPayload = data.maxPayload;
14532
- this.onOpen();
14533
- // In case open handler closes socket
14534
- if ("closed" === this.readyState)
14535
- return;
14536
- this._resetPingTimeout();
14537
- }
14538
- /**
14539
- * Sets and resets ping timeout timer based on server pings.
14540
- *
14541
- * @private
14542
- */
14543
- _resetPingTimeout() {
14544
- this.clearTimeoutFn(this._pingTimeoutTimer);
14545
- const delay = this._pingInterval + this._pingTimeout;
14546
- this._pingTimeoutTime = Date.now() + delay;
14547
- this._pingTimeoutTimer = this.setTimeoutFn(() => {
14548
- this._onClose("ping timeout");
14549
- }, delay);
14550
- if (this.opts.autoUnref) {
14551
- this._pingTimeoutTimer.unref();
14552
- }
14553
- }
14554
- /**
14555
- * Called on `drain` event
14556
- *
14557
- * @private
14558
- */
14559
- _onDrain() {
14560
- this.writeBuffer.splice(0, this._prevBufferLen);
14561
- // setting prevBufferLen = 0 is very important
14562
- // for example, when upgrading, upgrade packet is sent over,
14563
- // and a nonzero prevBufferLen could cause problems on `drain`
14564
- this._prevBufferLen = 0;
14565
- if (0 === this.writeBuffer.length) {
14566
- this.emitReserved("drain");
14567
- }
14568
- else {
14569
- this.flush();
14570
- }
14571
- }
14572
- /**
14573
- * Flush write buffers.
14574
- *
14575
- * @private
14576
- */
14577
- flush() {
14578
- if ("closed" !== this.readyState &&
14579
- this.transport.writable &&
14580
- !this.upgrading &&
14581
- this.writeBuffer.length) {
14582
- const packets = this._getWritablePackets();
14583
- this.transport.send(packets);
14584
- // keep track of current length of writeBuffer
14585
- // splice writeBuffer and callbackBuffer on `drain`
14586
- this._prevBufferLen = packets.length;
14587
- this.emitReserved("flush");
14588
- }
14589
- }
14590
- /**
14591
- * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
14592
- * long-polling)
14593
- *
14594
- * @private
14595
- */
14596
- _getWritablePackets() {
14597
- const shouldCheckPayloadSize = this._maxPayload &&
14598
- this.transport.name === "polling" &&
14599
- this.writeBuffer.length > 1;
14600
- if (!shouldCheckPayloadSize) {
14601
- return this.writeBuffer;
14602
- }
14603
- let payloadSize = 1; // first packet type
14604
- for (let i = 0; i < this.writeBuffer.length; i++) {
14605
- const data = this.writeBuffer[i].data;
14606
- if (data) {
14607
- payloadSize += byteLength(data);
14608
- }
14609
- if (i > 0 && payloadSize > this._maxPayload) {
14610
- return this.writeBuffer.slice(0, i);
14611
- }
14612
- payloadSize += 2; // separator + packet type
14613
- }
14614
- return this.writeBuffer;
14615
- }
14616
- /**
14617
- * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
14618
- *
14619
- * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
14620
- * `write()` method then the message would not be buffered by the Socket.IO client.
14621
- *
14622
- * @return {boolean}
14623
- * @private
14624
- */
14625
- /* private */ _hasPingExpired() {
14626
- if (!this._pingTimeoutTime)
14627
- return true;
14628
- const hasExpired = Date.now() > this._pingTimeoutTime;
14629
- if (hasExpired) {
14630
- this._pingTimeoutTime = 0;
14631
- nextTick(() => {
14632
- this._onClose("ping timeout");
14633
- }, this.setTimeoutFn);
14634
- }
14635
- return hasExpired;
14636
- }
14637
- /**
14638
- * Sends a message.
14639
- *
14640
- * @param {String} msg - message.
14641
- * @param {Object} options.
14642
- * @param {Function} fn - callback function.
14643
- * @return {Socket} for chaining.
14644
- */
14645
- write(msg, options, fn) {
14646
- this._sendPacket("message", msg, options, fn);
14647
- return this;
14648
- }
14649
- /**
14650
- * Sends a message. Alias of {@link Socket#write}.
14651
- *
14652
- * @param {String} msg - message.
14653
- * @param {Object} options.
14654
- * @param {Function} fn - callback function.
14655
- * @return {Socket} for chaining.
14656
- */
14657
- send(msg, options, fn) {
14658
- this._sendPacket("message", msg, options, fn);
14659
- return this;
14660
- }
14661
- /**
14662
- * Sends a packet.
14663
- *
14664
- * @param {String} type: packet type.
14665
- * @param {String} data.
14666
- * @param {Object} options.
14667
- * @param {Function} fn - callback function.
14668
- * @private
14669
- */
14670
- _sendPacket(type, data, options, fn) {
14671
- if ("function" === typeof data) {
14672
- fn = data;
14673
- data = undefined;
14674
- }
14675
- if ("function" === typeof options) {
14676
- fn = options;
14677
- options = null;
14678
- }
14679
- if ("closing" === this.readyState || "closed" === this.readyState) {
14680
- return;
14681
- }
14682
- options = options || {};
14683
- options.compress = false !== options.compress;
14684
- const packet = {
14685
- type: type,
14686
- data: data,
14687
- options: options,
14688
- };
14689
- this.emitReserved("packetCreate", packet);
14690
- this.writeBuffer.push(packet);
14691
- if (fn)
14692
- this.once("flush", fn);
14693
- this.flush();
14694
- }
14695
- /**
14696
- * Closes the connection.
14697
- */
14698
- close() {
14699
- const close = () => {
14700
- this._onClose("forced close");
14701
- this.transport.close();
14702
- };
14703
- const cleanupAndClose = () => {
14704
- this.off("upgrade", cleanupAndClose);
14705
- this.off("upgradeError", cleanupAndClose);
14706
- close();
14707
- };
14708
- const waitForUpgrade = () => {
14709
- // wait for upgrade to finish since we can't send packets while pausing a transport
14710
- this.once("upgrade", cleanupAndClose);
14711
- this.once("upgradeError", cleanupAndClose);
14712
- };
14713
- if ("opening" === this.readyState || "open" === this.readyState) {
14714
- this.readyState = "closing";
14715
- if (this.writeBuffer.length) {
14716
- this.once("drain", () => {
14717
- if (this.upgrading) {
14718
- waitForUpgrade();
14719
- }
14720
- else {
14721
- close();
14722
- }
14723
- });
14724
- }
14725
- else if (this.upgrading) {
14726
- waitForUpgrade();
14727
- }
14728
- else {
14729
- close();
14730
- }
14731
- }
14732
- return this;
14733
- }
14734
- /**
14735
- * Called upon transport error
14736
- *
14737
- * @private
14738
- */
14739
- _onError(err) {
14740
- SocketWithoutUpgrade.priorWebsocketSuccess = false;
14741
- if (this.opts.tryAllTransports &&
14742
- this.transports.length > 1 &&
14743
- this.readyState === "opening") {
14744
- this.transports.shift();
14745
- return this._open();
14746
- }
14747
- this.emitReserved("error", err);
14748
- this._onClose("transport error", err);
14749
- }
14750
- /**
14751
- * Called upon transport close.
14752
- *
14753
- * @private
14754
- */
14755
- _onClose(reason, description) {
14756
- if ("opening" === this.readyState ||
14757
- "open" === this.readyState ||
14758
- "closing" === this.readyState) {
14759
- // clear timers
14760
- this.clearTimeoutFn(this._pingTimeoutTimer);
14761
- // stop event from firing again for transport
14762
- this.transport.removeAllListeners("close");
14763
- // ensure transport won't stay open
14764
- this.transport.close();
14765
- // ignore further transport communication
14766
- this.transport.removeAllListeners();
14767
- if (withEventListeners) {
14768
- if (this._beforeunloadEventListener) {
14769
- removeEventListener("beforeunload", this._beforeunloadEventListener, false);
14770
- }
14771
- if (this._offlineEventListener) {
14772
- const i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
14773
- if (i !== -1) {
14774
- OFFLINE_EVENT_LISTENERS.splice(i, 1);
14775
- }
14776
- }
14777
- }
14778
- // set ready state
14779
- this.readyState = "closed";
14780
- // clear session id
14781
- this.id = null;
14782
- // emit close event
14783
- this.emitReserved("close", reason, description);
14784
- // clean buffers after, so users can still
14785
- // grab the buffers on `close` event
14786
- this.writeBuffer = [];
14787
- this._prevBufferLen = 0;
14788
- }
14789
- }
14790
- }
14791
- SocketWithoutUpgrade.protocol = protocol$1;
14792
- /**
14793
- * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
14794
- * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
14795
- *
14796
- * This class comes with an upgrade mechanism, which means that once the connection is established with the first
14797
- * low-level transport, it will try to upgrade to a better transport.
14798
- *
14799
- * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
14800
- *
14801
- * @example
14802
- * import { SocketWithUpgrade, WebSocket } from "engine.io-client";
14803
- *
14804
- * const socket = new SocketWithUpgrade({
14805
- * transports: [WebSocket]
14806
- * });
14807
- *
14808
- * socket.on("open", () => {
14809
- * socket.send("hello");
14810
- * });
14811
- *
14812
- * @see SocketWithoutUpgrade
14813
- * @see Socket
14814
- */
14815
- class SocketWithUpgrade extends SocketWithoutUpgrade {
14816
- constructor() {
14817
- super(...arguments);
14818
- this._upgrades = [];
14819
- }
14820
- onOpen() {
14821
- super.onOpen();
14822
- if ("open" === this.readyState && this.opts.upgrade) {
14823
- for (let i = 0; i < this._upgrades.length; i++) {
14824
- this._probe(this._upgrades[i]);
14825
- }
14826
- }
14827
- }
14828
- /**
14829
- * Probes a transport.
14830
- *
14831
- * @param {String} name - transport name
14832
- * @private
14833
- */
14834
- _probe(name) {
14835
- let transport = this.createTransport(name);
14836
- let failed = false;
14837
- SocketWithoutUpgrade.priorWebsocketSuccess = false;
14838
- const onTransportOpen = () => {
14839
- if (failed)
14840
- return;
14841
- transport.send([{ type: "ping", data: "probe" }]);
14842
- transport.once("packet", (msg) => {
14843
- if (failed)
14844
- return;
14845
- if ("pong" === msg.type && "probe" === msg.data) {
14846
- this.upgrading = true;
14847
- this.emitReserved("upgrading", transport);
14848
- if (!transport)
14849
- return;
14850
- SocketWithoutUpgrade.priorWebsocketSuccess =
14851
- "websocket" === transport.name;
14852
- this.transport.pause(() => {
14853
- if (failed)
14854
- return;
14855
- if ("closed" === this.readyState)
14856
- return;
14857
- cleanup();
14858
- this.setTransport(transport);
14859
- transport.send([{ type: "upgrade" }]);
14860
- this.emitReserved("upgrade", transport);
14861
- transport = null;
14862
- this.upgrading = false;
14863
- this.flush();
14864
- });
14865
- }
14866
- else {
14867
- const err = new Error("probe error");
14868
- // @ts-ignore
14869
- err.transport = transport.name;
14870
- this.emitReserved("upgradeError", err);
14871
- }
14872
- });
14873
- };
14874
- function freezeTransport() {
14875
- if (failed)
14876
- return;
14877
- // Any callback called by transport should be ignored since now
14878
- failed = true;
14879
- cleanup();
14880
- transport.close();
14881
- transport = null;
14882
- }
14883
- // Handle any error that happens while probing
14884
- const onerror = (err) => {
14885
- const error = new Error("probe error: " + err);
14886
- // @ts-ignore
14887
- error.transport = transport.name;
14888
- freezeTransport();
14889
- this.emitReserved("upgradeError", error);
14890
- };
14891
- function onTransportClose() {
14892
- onerror("transport closed");
14893
- }
14894
- // When the socket is closed while we're probing
14895
- function onclose() {
14896
- onerror("socket closed");
14897
- }
14898
- // When the socket is upgraded while we're probing
14899
- function onupgrade(to) {
14900
- if (transport && to.name !== transport.name) {
14901
- freezeTransport();
14902
- }
14903
- }
14904
- // Remove all listeners on the transport and on self
14905
- const cleanup = () => {
14906
- transport.removeListener("open", onTransportOpen);
14907
- transport.removeListener("error", onerror);
14908
- transport.removeListener("close", onTransportClose);
14909
- this.off("close", onclose);
14910
- this.off("upgrading", onupgrade);
14911
- };
14912
- transport.once("open", onTransportOpen);
14913
- transport.once("error", onerror);
14914
- transport.once("close", onTransportClose);
14915
- this.once("close", onclose);
14916
- this.once("upgrading", onupgrade);
14917
- if (this._upgrades.indexOf("webtransport") !== -1 &&
14918
- name !== "webtransport") {
14919
- // favor WebTransport
14920
- this.setTimeoutFn(() => {
14921
- if (!failed) {
14922
- transport.open();
14923
- }
14924
- }, 200);
14925
- }
14926
- else {
14927
- transport.open();
14928
- }
14929
- }
14930
- onHandshake(data) {
14931
- this._upgrades = this._filterUpgrades(data.upgrades);
14932
- super.onHandshake(data);
14933
- }
14934
- /**
14935
- * Filters upgrades, returning only those matching client transports.
14936
- *
14937
- * @param {Array} upgrades - server upgrades
14938
- * @private
14939
- */
14940
- _filterUpgrades(upgrades) {
14941
- const filteredUpgrades = [];
14942
- for (let i = 0; i < upgrades.length; i++) {
14943
- if (~this.transports.indexOf(upgrades[i]))
14944
- filteredUpgrades.push(upgrades[i]);
14945
- }
14946
- return filteredUpgrades;
14947
- }
14948
- }
14949
- /**
14950
- * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
14951
- * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
14952
- *
14953
- * This class comes with an upgrade mechanism, which means that once the connection is established with the first
14954
- * low-level transport, it will try to upgrade to a better transport.
14955
- *
14956
- * @example
14957
- * import { Socket } from "engine.io-client";
14958
- *
14959
- * const socket = new Socket();
14960
- *
14961
- * socket.on("open", () => {
14962
- * socket.send("hello");
14963
- * });
14964
- *
14965
- * @see SocketWithoutUpgrade
14966
- * @see SocketWithUpgrade
14967
- */
14968
- let Socket$1 = class Socket extends SocketWithUpgrade {
14969
- constructor(uri, opts = {}) {
14970
- const o = typeof uri === "object" ? uri : opts;
14971
- if (!o.transports ||
14972
- (o.transports && typeof o.transports[0] === "string")) {
14973
- o.transports = (o.transports || ["polling", "websocket", "webtransport"])
14974
- .map((transportName) => transports[transportName])
14975
- .filter((t) => !!t);
14976
- }
14977
- super(uri, o);
14978
- }
14979
- };
14980
-
14981
- /**
14982
- * URL parser.
14983
- *
14984
- * @param uri - url
14985
- * @param path - the request path of the connection
14986
- * @param loc - An object meant to mimic window.location.
14987
- * Defaults to window.location.
14988
- * @public
14989
- */
14990
- function url(uri, path = "", loc) {
14991
- let obj = uri;
14992
- // default to window.location
14993
- loc = loc || (typeof location !== "undefined" && location);
14994
- if (null == uri)
14995
- uri = loc.protocol + "//" + loc.host;
14996
- // relative path support
14997
- if (typeof uri === "string") {
14998
- if ("/" === uri.charAt(0)) {
14999
- if ("/" === uri.charAt(1)) {
15000
- uri = loc.protocol + uri;
15001
- }
15002
- else {
15003
- uri = loc.host + uri;
15004
- }
15005
- }
15006
- if (!/^(https?|wss?):\/\//.test(uri)) {
15007
- if ("undefined" !== typeof loc) {
15008
- uri = loc.protocol + "//" + uri;
15009
- }
15010
- else {
15011
- uri = "https://" + uri;
15012
- }
15013
- }
15014
- // parse
15015
- obj = parse(uri);
15016
- }
15017
- // make sure we treat `localhost:80` and `localhost` equally
15018
- if (!obj.port) {
15019
- if (/^(http|ws)$/.test(obj.protocol)) {
15020
- obj.port = "80";
15021
- }
15022
- else if (/^(http|ws)s$/.test(obj.protocol)) {
15023
- obj.port = "443";
15024
- }
15025
- }
15026
- obj.path = obj.path || "/";
15027
- const ipv6 = obj.host.indexOf(":") !== -1;
15028
- const host = ipv6 ? "[" + obj.host + "]" : obj.host;
15029
- // define unique id
15030
- obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
15031
- // define href
15032
- obj.href =
15033
- obj.protocol +
15034
- "://" +
15035
- host +
15036
- (loc && loc.port === obj.port ? "" : ":" + obj.port);
15037
- return obj;
15038
- }
15039
-
15040
- const withNativeArrayBuffer = typeof ArrayBuffer === "function";
15041
- const isView = (obj) => {
15042
- return typeof ArrayBuffer.isView === "function"
15043
- ? ArrayBuffer.isView(obj)
15044
- : obj.buffer instanceof ArrayBuffer;
15045
- };
15046
- const toString = Object.prototype.toString;
15047
- const withNativeBlob = typeof Blob === "function" ||
15048
- (typeof Blob !== "undefined" &&
15049
- toString.call(Blob) === "[object BlobConstructor]");
15050
- const withNativeFile = typeof File === "function" ||
15051
- (typeof File !== "undefined" &&
15052
- toString.call(File) === "[object FileConstructor]");
15053
- /**
15054
- * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
15055
- *
15056
- * @private
15057
- */
15058
- function isBinary(obj) {
15059
- return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||
15060
- (withNativeBlob && obj instanceof Blob) ||
15061
- (withNativeFile && obj instanceof File));
15062
- }
15063
- function hasBinary(obj, toJSON) {
15064
- if (!obj || typeof obj !== "object") {
15065
- return false;
15066
- }
15067
- if (Array.isArray(obj)) {
15068
- for (let i = 0, l = obj.length; i < l; i++) {
15069
- if (hasBinary(obj[i])) {
15070
- return true;
15071
- }
15072
- }
15073
- return false;
15074
- }
15075
- if (isBinary(obj)) {
15076
- return true;
15077
- }
15078
- if (obj.toJSON &&
15079
- typeof obj.toJSON === "function" &&
15080
- arguments.length === 1) {
15081
- return hasBinary(obj.toJSON(), true);
15082
- }
15083
- for (const key in obj) {
15084
- if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
15085
- return true;
15086
- }
15087
- }
15088
- return false;
15089
- }
15090
-
15091
- /**
15092
- * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
15093
- *
15094
- * @param {Object} packet - socket.io event packet
15095
- * @return {Object} with deconstructed packet and list of buffers
15096
- * @public
15097
- */
15098
- function deconstructPacket(packet) {
15099
- const buffers = [];
15100
- const packetData = packet.data;
15101
- const pack = packet;
15102
- pack.data = _deconstructPacket(packetData, buffers);
15103
- pack.attachments = buffers.length; // number of binary 'attachments'
15104
- return { packet: pack, buffers: buffers };
15105
- }
15106
- function _deconstructPacket(data, buffers) {
15107
- if (!data)
15108
- return data;
15109
- if (isBinary(data)) {
15110
- const placeholder = { _placeholder: true, num: buffers.length };
15111
- buffers.push(data);
15112
- return placeholder;
15113
- }
15114
- else if (Array.isArray(data)) {
15115
- const newData = new Array(data.length);
15116
- for (let i = 0; i < data.length; i++) {
15117
- newData[i] = _deconstructPacket(data[i], buffers);
15118
- }
15119
- return newData;
15120
- }
15121
- else if (typeof data === "object" && !(data instanceof Date)) {
15122
- const newData = {};
15123
- for (const key in data) {
15124
- if (Object.prototype.hasOwnProperty.call(data, key)) {
15125
- newData[key] = _deconstructPacket(data[key], buffers);
15126
- }
15127
- }
15128
- return newData;
15129
- }
15130
- return data;
15131
- }
15132
- /**
15133
- * Reconstructs a binary packet from its placeholder packet and buffers
15134
- *
15135
- * @param {Object} packet - event packet with placeholders
15136
- * @param {Array} buffers - binary buffers to put in placeholder positions
15137
- * @return {Object} reconstructed packet
15138
- * @public
15139
- */
15140
- function reconstructPacket(packet, buffers) {
15141
- packet.data = _reconstructPacket(packet.data, buffers);
15142
- delete packet.attachments; // no longer useful
15143
- return packet;
15144
- }
15145
- function _reconstructPacket(data, buffers) {
15146
- if (!data)
15147
- return data;
15148
- if (data && data._placeholder === true) {
15149
- const isIndexValid = typeof data.num === "number" &&
15150
- data.num >= 0 &&
15151
- data.num < buffers.length;
15152
- if (isIndexValid) {
15153
- return buffers[data.num]; // appropriate buffer (should be natural order anyway)
15154
- }
15155
- else {
15156
- throw new Error("illegal attachments");
15157
- }
15158
- }
15159
- else if (Array.isArray(data)) {
15160
- for (let i = 0; i < data.length; i++) {
15161
- data[i] = _reconstructPacket(data[i], buffers);
15162
- }
15163
- }
15164
- else if (typeof data === "object") {
15165
- for (const key in data) {
15166
- if (Object.prototype.hasOwnProperty.call(data, key)) {
15167
- data[key] = _reconstructPacket(data[key], buffers);
15168
- }
15169
- }
15170
- }
15171
- return data;
15172
- }
15173
-
15174
- /**
15175
- * These strings must not be used as event names, as they have a special meaning.
15176
- */
15177
- const RESERVED_EVENTS$1 = [
15178
- "connect",
15179
- "connect_error",
15180
- "disconnect",
15181
- "disconnecting",
15182
- "newListener",
15183
- "removeListener", // used by the Node.js EventEmitter
15184
- ];
15185
- /**
15186
- * Protocol version.
15187
- *
15188
- * @public
15189
- */
15190
- const protocol = 5;
15191
- var PacketType;
15192
- (function (PacketType) {
15193
- PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
15194
- PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
15195
- PacketType[PacketType["EVENT"] = 2] = "EVENT";
15196
- PacketType[PacketType["ACK"] = 3] = "ACK";
15197
- PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
15198
- PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
15199
- PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
15200
- })(PacketType || (PacketType = {}));
15201
- /**
15202
- * A socket.io Encoder instance
15203
- */
15204
- class Encoder {
15205
- /**
15206
- * Encoder constructor
15207
- *
15208
- * @param {function} replacer - custom replacer to pass down to JSON.parse
15209
- */
15210
- constructor(replacer) {
15211
- this.replacer = replacer;
15212
- }
15213
- /**
15214
- * Encode a packet as a single string if non-binary, or as a
15215
- * buffer sequence, depending on packet type.
15216
- *
15217
- * @param {Object} obj - packet object
15218
- */
15219
- encode(obj) {
15220
- if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
15221
- if (hasBinary(obj)) {
15222
- return this.encodeAsBinary({
15223
- type: obj.type === PacketType.EVENT
15224
- ? PacketType.BINARY_EVENT
15225
- : PacketType.BINARY_ACK,
15226
- nsp: obj.nsp,
15227
- data: obj.data,
15228
- id: obj.id,
15229
- });
15230
- }
15231
- }
15232
- return [this.encodeAsString(obj)];
15233
- }
15234
- /**
15235
- * Encode packet as string.
15236
- */
15237
- encodeAsString(obj) {
15238
- // first is type
15239
- let str = "" + obj.type;
15240
- // attachments if we have them
15241
- if (obj.type === PacketType.BINARY_EVENT ||
15242
- obj.type === PacketType.BINARY_ACK) {
15243
- str += obj.attachments + "-";
15244
- }
15245
- // if we have a namespace other than `/`
15246
- // we append it followed by a comma `,`
15247
- if (obj.nsp && "/" !== obj.nsp) {
15248
- str += obj.nsp + ",";
15249
- }
15250
- // immediately followed by the id
15251
- if (null != obj.id) {
15252
- str += obj.id;
15253
- }
15254
- // json data
15255
- if (null != obj.data) {
15256
- str += JSON.stringify(obj.data, this.replacer);
15257
- }
15258
- return str;
15259
- }
15260
- /**
15261
- * Encode packet as 'buffer sequence' by removing blobs, and
15262
- * deconstructing packet into object with placeholders and
15263
- * a list of buffers.
15264
- */
15265
- encodeAsBinary(obj) {
15266
- const deconstruction = deconstructPacket(obj);
15267
- const pack = this.encodeAsString(deconstruction.packet);
15268
- const buffers = deconstruction.buffers;
15269
- buffers.unshift(pack); // add packet info to beginning of data list
15270
- return buffers; // write all the buffers
15271
- }
15272
- }
15273
- // see https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
15274
- function isObject(value) {
15275
- return Object.prototype.toString.call(value) === "[object Object]";
15276
- }
15277
- /**
15278
- * A socket.io Decoder instance
15279
- *
15280
- * @return {Object} decoder
15281
- */
15282
- class Decoder extends Emitter {
15283
- /**
15284
- * Decoder constructor
15285
- *
15286
- * @param {function} reviver - custom reviver to pass down to JSON.stringify
15287
- */
15288
- constructor(reviver) {
15289
- super();
15290
- this.reviver = reviver;
15291
- }
15292
- /**
15293
- * Decodes an encoded packet string into packet JSON.
15294
- *
15295
- * @param {String} obj - encoded packet
15296
- */
15297
- add(obj) {
15298
- let packet;
15299
- if (typeof obj === "string") {
15300
- if (this.reconstructor) {
15301
- throw new Error("got plaintext data when reconstructing a packet");
15302
- }
15303
- packet = this.decodeString(obj);
15304
- const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
15305
- if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
15306
- packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
15307
- // binary packet's json
15308
- this.reconstructor = new BinaryReconstructor(packet);
15309
- // no attachments, labeled binary but no binary data to follow
15310
- if (packet.attachments === 0) {
15311
- super.emitReserved("decoded", packet);
15312
- }
15313
- }
15314
- else {
15315
- // non-binary full packet
15316
- super.emitReserved("decoded", packet);
15317
- }
15318
- }
15319
- else if (isBinary(obj) || obj.base64) {
15320
- // raw binary data
15321
- if (!this.reconstructor) {
15322
- throw new Error("got binary data when not reconstructing a packet");
15323
- }
15324
- else {
15325
- packet = this.reconstructor.takeBinaryData(obj);
15326
- if (packet) {
15327
- // received final buffer
15328
- this.reconstructor = null;
15329
- super.emitReserved("decoded", packet);
15330
- }
15331
- }
15332
- }
15333
- else {
15334
- throw new Error("Unknown type: " + obj);
15335
- }
15336
- }
15337
- /**
15338
- * Decode a packet String (JSON data)
15339
- *
15340
- * @param {String} str
15341
- * @return {Object} packet
15342
- */
15343
- decodeString(str) {
15344
- let i = 0;
15345
- // look up type
15346
- const p = {
15347
- type: Number(str.charAt(0)),
15348
- };
15349
- if (PacketType[p.type] === undefined) {
15350
- throw new Error("unknown packet type " + p.type);
15351
- }
15352
- // look up attachments if type binary
15353
- if (p.type === PacketType.BINARY_EVENT ||
15354
- p.type === PacketType.BINARY_ACK) {
15355
- const start = i + 1;
15356
- while (str.charAt(++i) !== "-" && i != str.length) { }
15357
- const buf = str.substring(start, i);
15358
- if (buf != Number(buf) || str.charAt(i) !== "-") {
15359
- throw new Error("Illegal attachments");
15360
- }
15361
- p.attachments = Number(buf);
15362
- }
15363
- // look up namespace (if any)
15364
- if ("/" === str.charAt(i + 1)) {
15365
- const start = i + 1;
15366
- while (++i) {
15367
- const c = str.charAt(i);
15368
- if ("," === c)
15369
- break;
15370
- if (i === str.length)
15371
- break;
15372
- }
15373
- p.nsp = str.substring(start, i);
15374
- }
15375
- else {
15376
- p.nsp = "/";
15377
- }
15378
- // look up id
15379
- const next = str.charAt(i + 1);
15380
- if ("" !== next && Number(next) == next) {
15381
- const start = i + 1;
15382
- while (++i) {
15383
- const c = str.charAt(i);
15384
- if (null == c || Number(c) != c) {
15385
- --i;
15386
- break;
15387
- }
15388
- if (i === str.length)
15389
- break;
15390
- }
15391
- p.id = Number(str.substring(start, i + 1));
15392
- }
15393
- // look up json data
15394
- if (str.charAt(++i)) {
15395
- const payload = this.tryParse(str.substr(i));
15396
- if (Decoder.isPayloadValid(p.type, payload)) {
15397
- p.data = payload;
15398
- }
15399
- else {
15400
- throw new Error("invalid payload");
15401
- }
15402
- }
15403
- return p;
15404
- }
15405
- tryParse(str) {
15406
- try {
15407
- return JSON.parse(str, this.reviver);
15408
- }
15409
- catch (e) {
15410
- return false;
15411
- }
15412
- }
15413
- static isPayloadValid(type, payload) {
15414
- switch (type) {
15415
- case PacketType.CONNECT:
15416
- return isObject(payload);
15417
- case PacketType.DISCONNECT:
15418
- return payload === undefined;
15419
- case PacketType.CONNECT_ERROR:
15420
- return typeof payload === "string" || isObject(payload);
15421
- case PacketType.EVENT:
15422
- case PacketType.BINARY_EVENT:
15423
- return (Array.isArray(payload) &&
15424
- (typeof payload[0] === "number" ||
15425
- (typeof payload[0] === "string" &&
15426
- RESERVED_EVENTS$1.indexOf(payload[0]) === -1)));
15427
- case PacketType.ACK:
15428
- case PacketType.BINARY_ACK:
15429
- return Array.isArray(payload);
15430
- }
15431
- }
15432
- /**
15433
- * Deallocates a parser's resources
15434
- */
15435
- destroy() {
15436
- if (this.reconstructor) {
15437
- this.reconstructor.finishedReconstruction();
15438
- this.reconstructor = null;
15439
- }
15440
- }
15441
- }
15442
- /**
15443
- * A manager of a binary event's 'buffer sequence'. Should
15444
- * be constructed whenever a packet of type BINARY_EVENT is
15445
- * decoded.
15446
- *
15447
- * @param {Object} packet
15448
- * @return {BinaryReconstructor} initialized reconstructor
15449
- */
15450
- class BinaryReconstructor {
15451
- constructor(packet) {
15452
- this.packet = packet;
15453
- this.buffers = [];
15454
- this.reconPack = packet;
15455
- }
15456
- /**
15457
- * Method to be called when binary data received from connection
15458
- * after a BINARY_EVENT packet.
15459
- *
15460
- * @param {Buffer | ArrayBuffer} binData - the raw binary data received
15461
- * @return {null | Object} returns null if more binary data is expected or
15462
- * a reconstructed packet object if all buffers have been received.
15463
- */
15464
- takeBinaryData(binData) {
15465
- this.buffers.push(binData);
15466
- if (this.buffers.length === this.reconPack.attachments) {
15467
- // done with buffer list
15468
- const packet = reconstructPacket(this.reconPack, this.buffers);
15469
- this.finishedReconstruction();
15470
- return packet;
15471
- }
15472
- return null;
15473
- }
15474
- /**
15475
- * Cleans up binary packet reconstruction variables.
15476
- */
15477
- finishedReconstruction() {
15478
- this.reconPack = null;
15479
- this.buffers = [];
15480
- }
15481
- }
15482
-
15483
- var parser = /*#__PURE__*/Object.freeze({
15484
- __proto__: null,
15485
- Decoder: Decoder,
15486
- Encoder: Encoder,
15487
- get PacketType () { return PacketType; },
15488
- protocol: protocol
15489
- });
15490
-
15491
- function on(obj, ev, fn) {
15492
- obj.on(ev, fn);
15493
- return function subDestroy() {
15494
- obj.off(ev, fn);
15495
- };
15496
- }
15497
-
15498
- /**
15499
- * Internal events.
15500
- * These events can't be emitted by the user.
15501
- */
15502
- const RESERVED_EVENTS = Object.freeze({
15503
- connect: 1,
15504
- connect_error: 1,
15505
- disconnect: 1,
15506
- disconnecting: 1,
15507
- // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
15508
- newListener: 1,
15509
- removeListener: 1,
15510
- });
15511
- /**
15512
- * A Socket is the fundamental class for interacting with the server.
15513
- *
15514
- * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
15515
- *
15516
- * @example
15517
- * const socket = io();
15518
- *
15519
- * socket.on("connect", () => {
15520
- * console.log("connected");
15521
- * });
15522
- *
15523
- * // send an event to the server
15524
- * socket.emit("foo", "bar");
15525
- *
15526
- * socket.on("foobar", () => {
15527
- * // an event was received from the server
15528
- * });
15529
- *
15530
- * // upon disconnection
15531
- * socket.on("disconnect", (reason) => {
15532
- * console.log(`disconnected due to ${reason}`);
15533
- * });
15534
- */
15535
- class Socket extends Emitter {
15536
- /**
15537
- * `Socket` constructor.
15538
- */
15539
- constructor(io, nsp, opts) {
15540
- super();
15541
- /**
15542
- * Whether the socket is currently connected to the server.
15543
- *
15544
- * @example
15545
- * const socket = io();
15546
- *
15547
- * socket.on("connect", () => {
15548
- * console.log(socket.connected); // true
15549
- * });
15550
- *
15551
- * socket.on("disconnect", () => {
15552
- * console.log(socket.connected); // false
15553
- * });
15554
- */
15555
- this.connected = false;
15556
- /**
15557
- * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
15558
- * be transmitted by the server.
15559
- */
15560
- this.recovered = false;
15561
- /**
15562
- * Buffer for packets received before the CONNECT packet
15563
- */
15564
- this.receiveBuffer = [];
15565
- /**
15566
- * Buffer for packets that will be sent once the socket is connected
15567
- */
15568
- this.sendBuffer = [];
15569
- /**
15570
- * The queue of packets to be sent with retry in case of failure.
15571
- *
15572
- * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
15573
- * @private
15574
- */
15575
- this._queue = [];
15576
- /**
15577
- * A sequence to generate the ID of the {@link QueuedPacket}.
15578
- * @private
15579
- */
15580
- this._queueSeq = 0;
15581
- this.ids = 0;
15582
- /**
15583
- * A map containing acknowledgement handlers.
15584
- *
15585
- * The `withError` attribute is used to differentiate handlers that accept an error as first argument:
15586
- *
15587
- * - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
15588
- * - `socket.timeout(5000).emit("test", (err, value) => { ... })`
15589
- * - `const value = await socket.emitWithAck("test")`
15590
- *
15591
- * From those that don't:
15592
- *
15593
- * - `socket.emit("test", (value) => { ... });`
15594
- *
15595
- * In the first case, the handlers will be called with an error when:
15596
- *
15597
- * - the timeout is reached
15598
- * - the socket gets disconnected
15599
- *
15600
- * In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
15601
- * an acknowledgement from the server.
15602
- *
15603
- * @private
15604
- */
15605
- this.acks = {};
15606
- this.flags = {};
15607
- this.io = io;
15608
- this.nsp = nsp;
15609
- if (opts && opts.auth) {
15610
- this.auth = opts.auth;
15611
- }
15612
- this._opts = Object.assign({}, opts);
15613
- if (this.io._autoConnect)
15614
- this.open();
15615
- }
15616
- /**
15617
- * Whether the socket is currently disconnected
15618
- *
15619
- * @example
15620
- * const socket = io();
15621
- *
15622
- * socket.on("connect", () => {
15623
- * console.log(socket.disconnected); // false
15624
- * });
15625
- *
15626
- * socket.on("disconnect", () => {
15627
- * console.log(socket.disconnected); // true
15628
- * });
15629
- */
15630
- get disconnected() {
15631
- return !this.connected;
15632
- }
15633
- /**
15634
- * Subscribe to open, close and packet events
15635
- *
15636
- * @private
15637
- */
15638
- subEvents() {
15639
- if (this.subs)
15640
- return;
15641
- const io = this.io;
15642
- this.subs = [
15643
- on(io, "open", this.onopen.bind(this)),
15644
- on(io, "packet", this.onpacket.bind(this)),
15645
- on(io, "error", this.onerror.bind(this)),
15646
- on(io, "close", this.onclose.bind(this)),
15647
- ];
15648
- }
15649
- /**
15650
- * Whether the Socket will try to reconnect when its Manager connects or reconnects.
15651
- *
15652
- * @example
15653
- * const socket = io();
15654
- *
15655
- * console.log(socket.active); // true
15656
- *
15657
- * socket.on("disconnect", (reason) => {
15658
- * if (reason === "io server disconnect") {
15659
- * // the disconnection was initiated by the server, you need to manually reconnect
15660
- * console.log(socket.active); // false
15661
- * }
15662
- * // else the socket will automatically try to reconnect
15663
- * console.log(socket.active); // true
15664
- * });
15665
- */
15666
- get active() {
15667
- return !!this.subs;
15668
- }
15669
- /**
15670
- * "Opens" the socket.
15671
- *
15672
- * @example
15673
- * const socket = io({
15674
- * autoConnect: false
15675
- * });
15676
- *
15677
- * socket.connect();
15678
- */
15679
- connect() {
15680
- if (this.connected)
15681
- return this;
15682
- this.subEvents();
15683
- if (!this.io["_reconnecting"])
15684
- this.io.open(); // ensure open
15685
- if ("open" === this.io._readyState)
15686
- this.onopen();
15687
- return this;
15688
- }
15689
- /**
15690
- * Alias for {@link connect()}.
15691
- */
15692
- open() {
15693
- return this.connect();
15694
- }
15695
- /**
15696
- * Sends a `message` event.
15697
- *
15698
- * This method mimics the WebSocket.send() method.
15699
- *
15700
- * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
15701
- *
15702
- * @example
15703
- * socket.send("hello");
15704
- *
15705
- * // this is equivalent to
15706
- * socket.emit("message", "hello");
15707
- *
15708
- * @return self
15709
- */
15710
- send(...args) {
15711
- args.unshift("message");
15712
- this.emit.apply(this, args);
15713
- return this;
15714
- }
15715
- /**
15716
- * Override `emit`.
15717
- * If the event is in `events`, it's emitted normally.
15718
- *
15719
- * @example
15720
- * socket.emit("hello", "world");
15721
- *
15722
- * // all serializable datastructures are supported (no need to call JSON.stringify)
15723
- * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
15724
- *
15725
- * // with an acknowledgement from the server
15726
- * socket.emit("hello", "world", (val) => {
15727
- * // ...
15728
- * });
15729
- *
15730
- * @return self
15731
- */
15732
- emit(ev, ...args) {
15733
- var _a, _b, _c;
15734
- if (RESERVED_EVENTS.hasOwnProperty(ev)) {
15735
- throw new Error('"' + ev.toString() + '" is a reserved event name');
15736
- }
15737
- args.unshift(ev);
15738
- if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
15739
- this._addToQueue(args);
15740
- return this;
15741
- }
15742
- const packet = {
15743
- type: PacketType.EVENT,
15744
- data: args,
15745
- };
15746
- packet.options = {};
15747
- packet.options.compress = this.flags.compress !== false;
15748
- // event ack callback
15749
- if ("function" === typeof args[args.length - 1]) {
15750
- const id = this.ids++;
15751
- const ack = args.pop();
15752
- this._registerAckCallback(id, ack);
15753
- packet.id = id;
15754
- }
15755
- const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
15756
- const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
15757
- const discardPacket = this.flags.volatile && !isTransportWritable;
15758
- if (discardPacket) ;
15759
- else if (isConnected) {
15760
- this.notifyOutgoingListeners(packet);
15761
- this.packet(packet);
15762
- }
15763
- else {
15764
- this.sendBuffer.push(packet);
15765
- }
15766
- this.flags = {};
15767
- return this;
15768
- }
15769
- /**
15770
- * @private
15771
- */
15772
- _registerAckCallback(id, ack) {
15773
- var _a;
15774
- const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
15775
- if (timeout === undefined) {
15776
- this.acks[id] = ack;
15777
- return;
15778
- }
15779
- // @ts-ignore
15780
- const timer = this.io.setTimeoutFn(() => {
15781
- delete this.acks[id];
15782
- for (let i = 0; i < this.sendBuffer.length; i++) {
15783
- if (this.sendBuffer[i].id === id) {
15784
- this.sendBuffer.splice(i, 1);
15785
- }
15786
- }
15787
- ack.call(this, new Error("operation has timed out"));
15788
- }, timeout);
15789
- const fn = (...args) => {
15790
- // @ts-ignore
15791
- this.io.clearTimeoutFn(timer);
15792
- ack.apply(this, args);
15793
- };
15794
- fn.withError = true;
15795
- this.acks[id] = fn;
15796
- }
15797
- /**
15798
- * Emits an event and waits for an acknowledgement
15799
- *
15800
- * @example
15801
- * // without timeout
15802
- * const response = await socket.emitWithAck("hello", "world");
15803
- *
15804
- * // with a specific timeout
15805
- * try {
15806
- * const response = await socket.timeout(1000).emitWithAck("hello", "world");
15807
- * } catch (err) {
15808
- * // the server did not acknowledge the event in the given delay
15809
- * }
15810
- *
15811
- * @return a Promise that will be fulfilled when the server acknowledges the event
15812
- */
15813
- emitWithAck(ev, ...args) {
15814
- return new Promise((resolve, reject) => {
15815
- const fn = (arg1, arg2) => {
15816
- return arg1 ? reject(arg1) : resolve(arg2);
15817
- };
15818
- fn.withError = true;
15819
- args.push(fn);
15820
- this.emit(ev, ...args);
15821
- });
15822
- }
15823
- /**
15824
- * Add the packet to the queue.
15825
- * @param args
15826
- * @private
15827
- */
15828
- _addToQueue(args) {
15829
- let ack;
15830
- if (typeof args[args.length - 1] === "function") {
15831
- ack = args.pop();
15832
- }
15833
- const packet = {
15834
- id: this._queueSeq++,
15835
- tryCount: 0,
15836
- pending: false,
15837
- args,
15838
- flags: Object.assign({ fromQueue: true }, this.flags),
15839
- };
15840
- args.push((err, ...responseArgs) => {
15841
- if (packet !== this._queue[0]) {
15842
- // the packet has already been acknowledged
15843
- return;
15844
- }
15845
- const hasError = err !== null;
15846
- if (hasError) {
15847
- if (packet.tryCount > this._opts.retries) {
15848
- this._queue.shift();
15849
- if (ack) {
15850
- ack(err);
15851
- }
15852
- }
15853
- }
15854
- else {
15855
- this._queue.shift();
15856
- if (ack) {
15857
- ack(null, ...responseArgs);
15858
- }
15859
- }
15860
- packet.pending = false;
15861
- return this._drainQueue();
15862
- });
15863
- this._queue.push(packet);
15864
- this._drainQueue();
15865
- }
15866
- /**
15867
- * Send the first packet of the queue, and wait for an acknowledgement from the server.
15868
- * @param force - whether to resend a packet that has not been acknowledged yet
15869
- *
15870
- * @private
15871
- */
15872
- _drainQueue(force = false) {
15873
- if (!this.connected || this._queue.length === 0) {
15874
- return;
15875
- }
15876
- const packet = this._queue[0];
15877
- if (packet.pending && !force) {
15878
- return;
15879
- }
15880
- packet.pending = true;
15881
- packet.tryCount++;
15882
- this.flags = packet.flags;
15883
- this.emit.apply(this, packet.args);
15884
- }
15885
- /**
15886
- * Sends a packet.
15887
- *
15888
- * @param packet
15889
- * @private
15890
- */
15891
- packet(packet) {
15892
- packet.nsp = this.nsp;
15893
- this.io._packet(packet);
15894
- }
15895
- /**
15896
- * Called upon engine `open`.
15897
- *
15898
- * @private
15899
- */
15900
- onopen() {
15901
- if (typeof this.auth == "function") {
15902
- this.auth((data) => {
15903
- this._sendConnectPacket(data);
15904
- });
15905
- }
15906
- else {
15907
- this._sendConnectPacket(this.auth);
15908
- }
15909
- }
15910
- /**
15911
- * Sends a CONNECT packet to initiate the Socket.IO session.
15912
- *
15913
- * @param data
15914
- * @private
15915
- */
15916
- _sendConnectPacket(data) {
15917
- this.packet({
15918
- type: PacketType.CONNECT,
15919
- data: this._pid
15920
- ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)
15921
- : data,
15922
- });
15923
- }
15924
- /**
15925
- * Called upon engine or manager `error`.
15926
- *
15927
- * @param err
15928
- * @private
15929
- */
15930
- onerror(err) {
15931
- if (!this.connected) {
15932
- this.emitReserved("connect_error", err);
15933
- }
15934
- }
15935
- /**
15936
- * Called upon engine `close`.
15937
- *
15938
- * @param reason
15939
- * @param description
15940
- * @private
15941
- */
15942
- onclose(reason, description) {
15943
- this.connected = false;
15944
- delete this.id;
15945
- this.emitReserved("disconnect", reason, description);
15946
- this._clearAcks();
15947
- }
15948
- /**
15949
- * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
15950
- * the server.
15951
- *
15952
- * @private
15953
- */
15954
- _clearAcks() {
15955
- Object.keys(this.acks).forEach((id) => {
15956
- const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
15957
- if (!isBuffered) {
15958
- // note: handlers that do not accept an error as first argument are ignored here
15959
- const ack = this.acks[id];
15960
- delete this.acks[id];
15961
- if (ack.withError) {
15962
- ack.call(this, new Error("socket has been disconnected"));
15963
- }
15964
- }
15965
- });
15966
- }
15967
- /**
15968
- * Called with socket packet.
15969
- *
15970
- * @param packet
15971
- * @private
15972
- */
15973
- onpacket(packet) {
15974
- const sameNamespace = packet.nsp === this.nsp;
15975
- if (!sameNamespace)
15976
- return;
15977
- switch (packet.type) {
15978
- case PacketType.CONNECT:
15979
- if (packet.data && packet.data.sid) {
15980
- this.onconnect(packet.data.sid, packet.data.pid);
15981
- }
15982
- else {
15983
- 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/)"));
15984
- }
15985
- break;
15986
- case PacketType.EVENT:
15987
- case PacketType.BINARY_EVENT:
15988
- this.onevent(packet);
15989
- break;
15990
- case PacketType.ACK:
15991
- case PacketType.BINARY_ACK:
15992
- this.onack(packet);
15993
- break;
15994
- case PacketType.DISCONNECT:
15995
- this.ondisconnect();
15996
- break;
15997
- case PacketType.CONNECT_ERROR:
15998
- this.destroy();
15999
- const err = new Error(packet.data.message);
16000
- // @ts-ignore
16001
- err.data = packet.data.data;
16002
- this.emitReserved("connect_error", err);
16003
- break;
16004
- }
16005
- }
16006
- /**
16007
- * Called upon a server event.
16008
- *
16009
- * @param packet
16010
- * @private
16011
- */
16012
- onevent(packet) {
16013
- const args = packet.data || [];
16014
- if (null != packet.id) {
16015
- args.push(this.ack(packet.id));
16016
- }
16017
- if (this.connected) {
16018
- this.emitEvent(args);
16019
- }
16020
- else {
16021
- this.receiveBuffer.push(Object.freeze(args));
16022
- }
16023
- }
16024
- emitEvent(args) {
16025
- if (this._anyListeners && this._anyListeners.length) {
16026
- const listeners = this._anyListeners.slice();
16027
- for (const listener of listeners) {
16028
- listener.apply(this, args);
16029
- }
16030
- }
16031
- super.emit.apply(this, args);
16032
- if (this._pid && args.length && typeof args[args.length - 1] === "string") {
16033
- this._lastOffset = args[args.length - 1];
16034
- }
16035
- }
16036
- /**
16037
- * Produces an ack callback to emit with an event.
16038
- *
16039
- * @private
16040
- */
16041
- ack(id) {
16042
- const self = this;
16043
- let sent = false;
16044
- return function (...args) {
16045
- // prevent double callbacks
16046
- if (sent)
16047
- return;
16048
- sent = true;
16049
- self.packet({
16050
- type: PacketType.ACK,
16051
- id: id,
16052
- data: args,
16053
- });
16054
- };
16055
- }
16056
- /**
16057
- * Called upon a server acknowledgement.
16058
- *
16059
- * @param packet
16060
- * @private
16061
- */
16062
- onack(packet) {
16063
- const ack = this.acks[packet.id];
16064
- if (typeof ack !== "function") {
16065
- return;
16066
- }
16067
- delete this.acks[packet.id];
16068
- // @ts-ignore FIXME ack is incorrectly inferred as 'never'
16069
- if (ack.withError) {
16070
- packet.data.unshift(null);
16071
- }
16072
- // @ts-ignore
16073
- ack.apply(this, packet.data);
16074
- }
16075
- /**
16076
- * Called upon server connect.
16077
- *
16078
- * @private
16079
- */
16080
- onconnect(id, pid) {
16081
- this.id = id;
16082
- this.recovered = pid && this._pid === pid;
16083
- this._pid = pid; // defined only if connection state recovery is enabled
16084
- this.connected = true;
16085
- this.emitBuffered();
16086
- this.emitReserved("connect");
16087
- this._drainQueue(true);
16088
- }
16089
- /**
16090
- * Emit buffered events (received and emitted).
16091
- *
16092
- * @private
16093
- */
16094
- emitBuffered() {
16095
- this.receiveBuffer.forEach((args) => this.emitEvent(args));
16096
- this.receiveBuffer = [];
16097
- this.sendBuffer.forEach((packet) => {
16098
- this.notifyOutgoingListeners(packet);
16099
- this.packet(packet);
16100
- });
16101
- this.sendBuffer = [];
16102
- }
16103
- /**
16104
- * Called upon server disconnect.
16105
- *
16106
- * @private
16107
- */
16108
- ondisconnect() {
16109
- this.destroy();
16110
- this.onclose("io server disconnect");
16111
- }
16112
- /**
16113
- * Called upon forced client/server side disconnections,
16114
- * this method ensures the manager stops tracking us and
16115
- * that reconnections don't get triggered for this.
16116
- *
16117
- * @private
16118
- */
16119
- destroy() {
16120
- if (this.subs) {
16121
- // clean subscriptions to avoid reconnections
16122
- this.subs.forEach((subDestroy) => subDestroy());
16123
- this.subs = undefined;
16124
- }
16125
- this.io["_destroy"](this);
16126
- }
16127
- /**
16128
- * Disconnects the socket manually. In that case, the socket will not try to reconnect.
16129
- *
16130
- * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
16131
- *
16132
- * @example
16133
- * const socket = io();
16134
- *
16135
- * socket.on("disconnect", (reason) => {
16136
- * // console.log(reason); prints "io client disconnect"
16137
- * });
16138
- *
16139
- * socket.disconnect();
16140
- *
16141
- * @return self
16142
- */
16143
- disconnect() {
16144
- if (this.connected) {
16145
- this.packet({ type: PacketType.DISCONNECT });
16146
- }
16147
- // remove socket from pool
16148
- this.destroy();
16149
- if (this.connected) {
16150
- // fire events
16151
- this.onclose("io client disconnect");
16152
- }
16153
- return this;
16154
- }
16155
- /**
16156
- * Alias for {@link disconnect()}.
16157
- *
16158
- * @return self
16159
- */
16160
- close() {
16161
- return this.disconnect();
16162
- }
16163
- /**
16164
- * Sets the compress flag.
16165
- *
16166
- * @example
16167
- * socket.compress(false).emit("hello");
16168
- *
16169
- * @param compress - if `true`, compresses the sending data
16170
- * @return self
16171
- */
16172
- compress(compress) {
16173
- this.flags.compress = compress;
16174
- return this;
16175
- }
16176
- /**
16177
- * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
16178
- * ready to send messages.
16179
- *
16180
- * @example
16181
- * socket.volatile.emit("hello"); // the server may or may not receive it
16182
- *
16183
- * @returns self
16184
- */
16185
- get volatile() {
16186
- this.flags.volatile = true;
16187
- return this;
16188
- }
16189
- /**
16190
- * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
16191
- * given number of milliseconds have elapsed without an acknowledgement from the server:
16192
- *
16193
- * @example
16194
- * socket.timeout(5000).emit("my-event", (err) => {
16195
- * if (err) {
16196
- * // the server did not acknowledge the event in the given delay
16197
- * }
16198
- * });
16199
- *
16200
- * @returns self
16201
- */
16202
- timeout(timeout) {
16203
- this.flags.timeout = timeout;
16204
- return this;
16205
- }
16206
- /**
16207
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
16208
- * callback.
16209
- *
16210
- * @example
16211
- * socket.onAny((event, ...args) => {
16212
- * console.log(`got ${event}`);
16213
- * });
16214
- *
16215
- * @param listener
16216
- */
16217
- onAny(listener) {
16218
- this._anyListeners = this._anyListeners || [];
16219
- this._anyListeners.push(listener);
16220
- return this;
16221
- }
16222
- /**
16223
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
16224
- * callback. The listener is added to the beginning of the listeners array.
16225
- *
16226
- * @example
16227
- * socket.prependAny((event, ...args) => {
16228
- * console.log(`got event ${event}`);
16229
- * });
16230
- *
16231
- * @param listener
16232
- */
16233
- prependAny(listener) {
16234
- this._anyListeners = this._anyListeners || [];
16235
- this._anyListeners.unshift(listener);
16236
- return this;
16237
- }
16238
- /**
16239
- * Removes the listener that will be fired when any event is emitted.
16240
- *
16241
- * @example
16242
- * const catchAllListener = (event, ...args) => {
16243
- * console.log(`got event ${event}`);
16244
- * }
16245
- *
16246
- * socket.onAny(catchAllListener);
16247
- *
16248
- * // remove a specific listener
16249
- * socket.offAny(catchAllListener);
16250
- *
16251
- * // or remove all listeners
16252
- * socket.offAny();
16253
- *
16254
- * @param listener
16255
- */
16256
- offAny(listener) {
16257
- if (!this._anyListeners) {
16258
- return this;
16259
- }
16260
- if (listener) {
16261
- const listeners = this._anyListeners;
16262
- for (let i = 0; i < listeners.length; i++) {
16263
- if (listener === listeners[i]) {
16264
- listeners.splice(i, 1);
16265
- return this;
16266
- }
16267
- }
16268
- }
16269
- else {
16270
- this._anyListeners = [];
16271
- }
16272
- return this;
16273
- }
16274
- /**
16275
- * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
16276
- * e.g. to remove listeners.
16277
- */
16278
- listenersAny() {
16279
- return this._anyListeners || [];
16280
- }
16281
- /**
16282
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
16283
- * callback.
16284
- *
16285
- * Note: acknowledgements sent to the server are not included.
16286
- *
16287
- * @example
16288
- * socket.onAnyOutgoing((event, ...args) => {
16289
- * console.log(`sent event ${event}`);
16290
- * });
16291
- *
16292
- * @param listener
16293
- */
16294
- onAnyOutgoing(listener) {
16295
- this._anyOutgoingListeners = this._anyOutgoingListeners || [];
16296
- this._anyOutgoingListeners.push(listener);
16297
- return this;
16298
- }
16299
- /**
16300
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
16301
- * callback. The listener is added to the beginning of the listeners array.
16302
- *
16303
- * Note: acknowledgements sent to the server are not included.
16304
- *
16305
- * @example
16306
- * socket.prependAnyOutgoing((event, ...args) => {
16307
- * console.log(`sent event ${event}`);
16308
- * });
16309
- *
16310
- * @param listener
16311
- */
16312
- prependAnyOutgoing(listener) {
16313
- this._anyOutgoingListeners = this._anyOutgoingListeners || [];
16314
- this._anyOutgoingListeners.unshift(listener);
16315
- return this;
16316
- }
16317
- /**
16318
- * Removes the listener that will be fired when any event is emitted.
16319
- *
16320
- * @example
16321
- * const catchAllListener = (event, ...args) => {
16322
- * console.log(`sent event ${event}`);
16323
- * }
16324
- *
16325
- * socket.onAnyOutgoing(catchAllListener);
16326
- *
16327
- * // remove a specific listener
16328
- * socket.offAnyOutgoing(catchAllListener);
16329
- *
16330
- * // or remove all listeners
16331
- * socket.offAnyOutgoing();
16332
- *
16333
- * @param [listener] - the catch-all listener (optional)
16334
- */
16335
- offAnyOutgoing(listener) {
16336
- if (!this._anyOutgoingListeners) {
16337
- return this;
16338
- }
16339
- if (listener) {
16340
- const listeners = this._anyOutgoingListeners;
16341
- for (let i = 0; i < listeners.length; i++) {
16342
- if (listener === listeners[i]) {
16343
- listeners.splice(i, 1);
16344
- return this;
16345
- }
16346
- }
16347
- }
16348
- else {
16349
- this._anyOutgoingListeners = [];
16350
- }
16351
- return this;
16352
- }
16353
- /**
16354
- * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
16355
- * e.g. to remove listeners.
16356
- */
16357
- listenersAnyOutgoing() {
16358
- return this._anyOutgoingListeners || [];
16359
- }
16360
- /**
16361
- * Notify the listeners for each packet sent
16362
- *
16363
- * @param packet
16364
- *
16365
- * @private
16366
- */
16367
- notifyOutgoingListeners(packet) {
16368
- if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
16369
- const listeners = this._anyOutgoingListeners.slice();
16370
- for (const listener of listeners) {
16371
- listener.apply(this, packet.data);
16372
- }
16373
- }
16374
- }
16375
- }
16376
-
16377
- /**
16378
- * Initialize backoff timer with `opts`.
16379
- *
16380
- * - `min` initial timeout in milliseconds [100]
16381
- * - `max` max timeout [10000]
16382
- * - `jitter` [0]
16383
- * - `factor` [2]
16384
- *
16385
- * @param {Object} opts
16386
- * @api public
16387
- */
16388
- function Backoff(opts) {
16389
- opts = opts || {};
16390
- this.ms = opts.min || 100;
16391
- this.max = opts.max || 10000;
16392
- this.factor = opts.factor || 2;
16393
- this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
16394
- this.attempts = 0;
16395
- }
16396
- /**
16397
- * Return the backoff duration.
16398
- *
16399
- * @return {Number}
16400
- * @api public
16401
- */
16402
- Backoff.prototype.duration = function () {
16403
- var ms = this.ms * Math.pow(this.factor, this.attempts++);
16404
- if (this.jitter) {
16405
- var rand = Math.random();
16406
- var deviation = Math.floor(rand * this.jitter * ms);
16407
- ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
16408
- }
16409
- return Math.min(ms, this.max) | 0;
16410
- };
16411
- /**
16412
- * Reset the number of attempts.
16413
- *
16414
- * @api public
16415
- */
16416
- Backoff.prototype.reset = function () {
16417
- this.attempts = 0;
16418
- };
16419
- /**
16420
- * Set the minimum duration
16421
- *
16422
- * @api public
16423
- */
16424
- Backoff.prototype.setMin = function (min) {
16425
- this.ms = min;
16426
- };
16427
- /**
16428
- * Set the maximum duration
16429
- *
16430
- * @api public
16431
- */
16432
- Backoff.prototype.setMax = function (max) {
16433
- this.max = max;
16434
- };
16435
- /**
16436
- * Set the jitter
16437
- *
16438
- * @api public
16439
- */
16440
- Backoff.prototype.setJitter = function (jitter) {
16441
- this.jitter = jitter;
16442
- };
16443
-
16444
- class Manager extends Emitter {
16445
- constructor(uri, opts) {
16446
- var _a;
16447
- super();
16448
- this.nsps = {};
16449
- this.subs = [];
16450
- if (uri && "object" === typeof uri) {
16451
- opts = uri;
16452
- uri = undefined;
16453
- }
16454
- opts = opts || {};
16455
- opts.path = opts.path || "/socket.io";
16456
- this.opts = opts;
16457
- installTimerFunctions(this, opts);
16458
- this.reconnection(opts.reconnection !== false);
16459
- this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
16460
- this.reconnectionDelay(opts.reconnectionDelay || 1000);
16461
- this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
16462
- this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
16463
- this.backoff = new Backoff({
16464
- min: this.reconnectionDelay(),
16465
- max: this.reconnectionDelayMax(),
16466
- jitter: this.randomizationFactor(),
16467
- });
16468
- this.timeout(null == opts.timeout ? 20000 : opts.timeout);
16469
- this._readyState = "closed";
16470
- this.uri = uri;
16471
- const _parser = opts.parser || parser;
16472
- this.encoder = new _parser.Encoder();
16473
- this.decoder = new _parser.Decoder();
16474
- this._autoConnect = opts.autoConnect !== false;
16475
- if (this._autoConnect)
16476
- this.open();
16477
- }
16478
- reconnection(v) {
16479
- if (!arguments.length)
16480
- return this._reconnection;
16481
- this._reconnection = !!v;
16482
- if (!v) {
16483
- this.skipReconnect = true;
16484
- }
16485
- return this;
16486
- }
16487
- reconnectionAttempts(v) {
16488
- if (v === undefined)
16489
- return this._reconnectionAttempts;
16490
- this._reconnectionAttempts = v;
16491
- return this;
16492
- }
16493
- reconnectionDelay(v) {
16494
- var _a;
16495
- if (v === undefined)
16496
- return this._reconnectionDelay;
16497
- this._reconnectionDelay = v;
16498
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
16499
- return this;
16500
- }
16501
- randomizationFactor(v) {
16502
- var _a;
16503
- if (v === undefined)
16504
- return this._randomizationFactor;
16505
- this._randomizationFactor = v;
16506
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
16507
- return this;
16508
- }
16509
- reconnectionDelayMax(v) {
16510
- var _a;
16511
- if (v === undefined)
16512
- return this._reconnectionDelayMax;
16513
- this._reconnectionDelayMax = v;
16514
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
16515
- return this;
16516
- }
16517
- timeout(v) {
16518
- if (!arguments.length)
16519
- return this._timeout;
16520
- this._timeout = v;
16521
- return this;
16522
- }
16523
- /**
16524
- * Starts trying to reconnect if reconnection is enabled and we have not
16525
- * started reconnecting yet
16526
- *
16527
- * @private
16528
- */
16529
- maybeReconnectOnOpen() {
16530
- // Only try to reconnect if it's the first time we're connecting
16531
- if (!this._reconnecting &&
16532
- this._reconnection &&
16533
- this.backoff.attempts === 0) {
16534
- // keeps reconnection from firing twice for the same reconnection loop
16535
- this.reconnect();
16536
- }
16537
- }
16538
- /**
16539
- * Sets the current transport `socket`.
16540
- *
16541
- * @param {Function} fn - optional, callback
16542
- * @return self
16543
- * @public
16544
- */
16545
- open(fn) {
16546
- if (~this._readyState.indexOf("open"))
16547
- return this;
16548
- this.engine = new Socket$1(this.uri, this.opts);
16549
- const socket = this.engine;
16550
- const self = this;
16551
- this._readyState = "opening";
16552
- this.skipReconnect = false;
16553
- // emit `open`
16554
- const openSubDestroy = on(socket, "open", function () {
16555
- self.onopen();
16556
- fn && fn();
16557
- });
16558
- const onError = (err) => {
16559
- this.cleanup();
16560
- this._readyState = "closed";
16561
- this.emitReserved("error", err);
16562
- if (fn) {
16563
- fn(err);
16564
- }
16565
- else {
16566
- // Only do this if there is no fn to handle the error
16567
- this.maybeReconnectOnOpen();
16568
- }
16569
- };
16570
- // emit `error`
16571
- const errorSub = on(socket, "error", onError);
16572
- if (false !== this._timeout) {
16573
- const timeout = this._timeout;
16574
- // set timer
16575
- const timer = this.setTimeoutFn(() => {
16576
- openSubDestroy();
16577
- onError(new Error("timeout"));
16578
- socket.close();
16579
- }, timeout);
16580
- if (this.opts.autoUnref) {
16581
- timer.unref();
16582
- }
16583
- this.subs.push(() => {
16584
- this.clearTimeoutFn(timer);
16585
- });
16586
- }
16587
- this.subs.push(openSubDestroy);
16588
- this.subs.push(errorSub);
16589
- return this;
16590
- }
16591
- /**
16592
- * Alias for open()
16593
- *
16594
- * @return self
16595
- * @public
16596
- */
16597
- connect(fn) {
16598
- return this.open(fn);
16599
- }
16600
- /**
16601
- * Called upon transport open.
16602
- *
16603
- * @private
16604
- */
16605
- onopen() {
16606
- // clear old subs
16607
- this.cleanup();
16608
- // mark as open
16609
- this._readyState = "open";
16610
- this.emitReserved("open");
16611
- // add new subs
16612
- const socket = this.engine;
16613
- 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)),
16614
- // @ts-ignore
16615
- on(this.decoder, "decoded", this.ondecoded.bind(this)));
16616
- }
16617
- /**
16618
- * Called upon a ping.
16619
- *
16620
- * @private
16621
- */
16622
- onping() {
16623
- this.emitReserved("ping");
16624
- }
16625
- /**
16626
- * Called with data.
16627
- *
16628
- * @private
16629
- */
16630
- ondata(data) {
16631
- try {
16632
- this.decoder.add(data);
16633
- }
16634
- catch (e) {
16635
- this.onclose("parse error", e);
16636
- }
16637
- }
16638
- /**
16639
- * Called when parser fully decodes a packet.
16640
- *
16641
- * @private
16642
- */
16643
- ondecoded(packet) {
16644
- // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
16645
- nextTick(() => {
16646
- this.emitReserved("packet", packet);
16647
- }, this.setTimeoutFn);
16648
- }
16649
- /**
16650
- * Called upon socket error.
16651
- *
16652
- * @private
16653
- */
16654
- onerror(err) {
16655
- this.emitReserved("error", err);
16656
- }
16657
- /**
16658
- * Creates a new socket for the given `nsp`.
16659
- *
16660
- * @return {Socket}
16661
- * @public
16662
- */
16663
- socket(nsp, opts) {
16664
- let socket = this.nsps[nsp];
16665
- if (!socket) {
16666
- socket = new Socket(this, nsp, opts);
16667
- this.nsps[nsp] = socket;
16668
- }
16669
- else if (this._autoConnect && !socket.active) {
16670
- socket.connect();
16671
- }
16672
- return socket;
16673
- }
16674
- /**
16675
- * Called upon a socket close.
16676
- *
16677
- * @param socket
16678
- * @private
16679
- */
16680
- _destroy(socket) {
16681
- const nsps = Object.keys(this.nsps);
16682
- for (const nsp of nsps) {
16683
- const socket = this.nsps[nsp];
16684
- if (socket.active) {
16685
- return;
16686
- }
16687
- }
16688
- this._close();
16689
- }
16690
- /**
16691
- * Writes a packet.
16692
- *
16693
- * @param packet
16694
- * @private
16695
- */
16696
- _packet(packet) {
16697
- const encodedPackets = this.encoder.encode(packet);
16698
- for (let i = 0; i < encodedPackets.length; i++) {
16699
- this.engine.write(encodedPackets[i], packet.options);
16700
- }
16701
- }
16702
- /**
16703
- * Clean up transport subscriptions and packet buffer.
16704
- *
16705
- * @private
16706
- */
16707
- cleanup() {
16708
- this.subs.forEach((subDestroy) => subDestroy());
16709
- this.subs.length = 0;
16710
- this.decoder.destroy();
16711
- }
16712
- /**
16713
- * Close the current socket.
16714
- *
16715
- * @private
16716
- */
16717
- _close() {
16718
- this.skipReconnect = true;
16719
- this._reconnecting = false;
16720
- this.onclose("forced close");
16721
- }
16722
- /**
16723
- * Alias for close()
16724
- *
16725
- * @private
16726
- */
16727
- disconnect() {
16728
- return this._close();
16729
- }
16730
- /**
16731
- * Called when:
16732
- *
16733
- * - the low-level engine is closed
16734
- * - the parser encountered a badly formatted packet
16735
- * - all sockets are disconnected
16736
- *
16737
- * @private
16738
- */
16739
- onclose(reason, description) {
16740
- var _a;
16741
- this.cleanup();
16742
- (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
16743
- this.backoff.reset();
16744
- this._readyState = "closed";
16745
- this.emitReserved("close", reason, description);
16746
- if (this._reconnection && !this.skipReconnect) {
16747
- this.reconnect();
16748
- }
16749
- }
16750
- /**
16751
- * Attempt a reconnection.
16752
- *
16753
- * @private
16754
- */
16755
- reconnect() {
16756
- if (this._reconnecting || this.skipReconnect)
16757
- return this;
16758
- const self = this;
16759
- if (this.backoff.attempts >= this._reconnectionAttempts) {
16760
- this.backoff.reset();
16761
- this.emitReserved("reconnect_failed");
16762
- this._reconnecting = false;
16763
- }
16764
- else {
16765
- const delay = this.backoff.duration();
16766
- this._reconnecting = true;
16767
- const timer = this.setTimeoutFn(() => {
16768
- if (self.skipReconnect)
16769
- return;
16770
- this.emitReserved("reconnect_attempt", self.backoff.attempts);
16771
- // check again for the case socket closed in above events
16772
- if (self.skipReconnect)
16773
- return;
16774
- self.open((err) => {
16775
- if (err) {
16776
- self._reconnecting = false;
16777
- self.reconnect();
16778
- this.emitReserved("reconnect_error", err);
16779
- }
16780
- else {
16781
- self.onreconnect();
16782
- }
16783
- });
16784
- }, delay);
16785
- if (this.opts.autoUnref) {
16786
- timer.unref();
16787
- }
16788
- this.subs.push(() => {
16789
- this.clearTimeoutFn(timer);
16790
- });
16791
- }
16792
- }
16793
- /**
16794
- * Called upon successful reconnect.
16795
- *
16796
- * @private
16797
- */
16798
- onreconnect() {
16799
- const attempt = this.backoff.attempts;
16800
- this._reconnecting = false;
16801
- this.backoff.reset();
16802
- this.emitReserved("reconnect", attempt);
16803
- }
16804
- }
16805
-
16806
- /**
16807
- * Managers cache.
16808
- */
16809
- const cache = {};
16810
- function lookup(uri, opts) {
16811
- if (typeof uri === "object") {
16812
- opts = uri;
16813
- uri = undefined;
16814
- }
16815
- opts = opts || {};
16816
- const parsed = url(uri, opts.path || "/socket.io");
16817
- const source = parsed.source;
16818
- const id = parsed.id;
16819
- const path = parsed.path;
16820
- const sameNamespace = cache[id] && path in cache[id]["nsps"];
16821
- const newConnection = opts.forceNew ||
16822
- opts["force new connection"] ||
16823
- false === opts.multiplex ||
16824
- sameNamespace;
16825
- let io;
16826
- if (newConnection) {
16827
- io = new Manager(source, opts);
16828
- }
16829
- else {
16830
- if (!cache[id]) {
16831
- cache[id] = new Manager(source, opts);
16832
- }
16833
- io = cache[id];
16834
- }
16835
- if (parsed.query && !opts.query) {
16836
- opts.query = parsed.queryKey;
16837
- }
16838
- return io.socket(parsed.path, opts);
16839
- }
16840
- // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
16841
- // namespace (e.g. `io.connect(...)`), for backward compatibility
16842
- Object.assign(lookup, {
16843
- Manager,
16844
- Socket,
16845
- io: lookup,
16846
- connect: lookup,
16847
- });
16848
-
16849
- var index = /*#__PURE__*/Object.freeze({
16850
- __proto__: null,
16851
- Manager: Manager,
16852
- NodeWebSocket: WS,
16853
- NodeXHR: XHR,
16854
- Socket: Socket,
16855
- WebSocket: WS,
16856
- WebTransport: WT,
16857
- XHR: XHR,
16858
- connect: lookup,
16859
- default: lookup,
16860
- io: lookup,
16861
- protocol: protocol
16862
- });
16863
-
16864
12737
  exports.Zaplier = Zaplier;
16865
12738
  exports.ZaplierSDK = ZaplierSDK;
16866
12739
  exports.analyzeUserAgent = analyzeUserAgent;