@zaplier/sdk 1.2.1 → 1.2.3

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