socket.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.Socket = void 0;
  7. const socket_io_parser_1 = require("socket.io-parser");
  8. const on_js_1 = require("./on.js");
  9. const component_emitter_1 = require("@socket.io/component-emitter");
  10. const debug_1 = __importDefault(require("debug")); // debug()
  11. const debug = debug_1.default("socket.io-client:socket"); // debug()
  12. /**
  13. * Internal events.
  14. * These events can't be emitted by the user.
  15. */
  16. const RESERVED_EVENTS = Object.freeze({
  17. connect: 1,
  18. connect_error: 1,
  19. disconnect: 1,
  20. disconnecting: 1,
  21. // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
  22. newListener: 1,
  23. removeListener: 1,
  24. });
  25. class Socket extends component_emitter_1.Emitter {
  26. /**
  27. * `Socket` constructor.
  28. *
  29. * @public
  30. */
  31. constructor(io, nsp, opts) {
  32. super();
  33. this.connected = false;
  34. this.disconnected = true;
  35. this.receiveBuffer = [];
  36. this.sendBuffer = [];
  37. this.ids = 0;
  38. this.acks = {};
  39. this.flags = {};
  40. this.io = io;
  41. this.nsp = nsp;
  42. if (opts && opts.auth) {
  43. this.auth = opts.auth;
  44. }
  45. if (this.io._autoConnect)
  46. this.open();
  47. }
  48. /**
  49. * Subscribe to open, close and packet events
  50. *
  51. * @private
  52. */
  53. subEvents() {
  54. if (this.subs)
  55. return;
  56. const io = this.io;
  57. this.subs = [
  58. on_js_1.on(io, "open", this.onopen.bind(this)),
  59. on_js_1.on(io, "packet", this.onpacket.bind(this)),
  60. on_js_1.on(io, "error", this.onerror.bind(this)),
  61. on_js_1.on(io, "close", this.onclose.bind(this)),
  62. ];
  63. }
  64. /**
  65. * Whether the Socket will try to reconnect when its Manager connects or reconnects
  66. */
  67. get active() {
  68. return !!this.subs;
  69. }
  70. /**
  71. * "Opens" the socket.
  72. *
  73. * @public
  74. */
  75. connect() {
  76. if (this.connected)
  77. return this;
  78. this.subEvents();
  79. if (!this.io["_reconnecting"])
  80. this.io.open(); // ensure open
  81. if ("open" === this.io._readyState)
  82. this.onopen();
  83. return this;
  84. }
  85. /**
  86. * Alias for connect()
  87. */
  88. open() {
  89. return this.connect();
  90. }
  91. /**
  92. * Sends a `message` event.
  93. *
  94. * @return self
  95. * @public
  96. */
  97. send(...args) {
  98. args.unshift("message");
  99. this.emit.apply(this, args);
  100. return this;
  101. }
  102. /**
  103. * Override `emit`.
  104. * If the event is in `events`, it's emitted normally.
  105. *
  106. * @return self
  107. * @public
  108. */
  109. emit(ev, ...args) {
  110. if (RESERVED_EVENTS.hasOwnProperty(ev)) {
  111. throw new Error('"' + ev + '" is a reserved event name');
  112. }
  113. args.unshift(ev);
  114. const packet = {
  115. type: socket_io_parser_1.PacketType.EVENT,
  116. data: args,
  117. };
  118. packet.options = {};
  119. packet.options.compress = this.flags.compress !== false;
  120. // event ack callback
  121. if ("function" === typeof args[args.length - 1]) {
  122. const id = this.ids++;
  123. debug("emitting packet with ack id %d", id);
  124. const ack = args.pop();
  125. this._registerAckCallback(id, ack);
  126. packet.id = id;
  127. }
  128. const isTransportWritable = this.io.engine &&
  129. this.io.engine.transport &&
  130. this.io.engine.transport.writable;
  131. const discardPacket = this.flags.volatile && (!isTransportWritable || !this.connected);
  132. if (discardPacket) {
  133. debug("discard packet as the transport is not currently writable");
  134. }
  135. else if (this.connected) {
  136. this.packet(packet);
  137. }
  138. else {
  139. this.sendBuffer.push(packet);
  140. }
  141. this.flags = {};
  142. return this;
  143. }
  144. /**
  145. * @private
  146. */
  147. _registerAckCallback(id, ack) {
  148. const timeout = this.flags.timeout;
  149. if (timeout === undefined) {
  150. this.acks[id] = ack;
  151. return;
  152. }
  153. // @ts-ignore
  154. const timer = this.io.setTimeoutFn(() => {
  155. delete this.acks[id];
  156. for (let i = 0; i < this.sendBuffer.length; i++) {
  157. if (this.sendBuffer[i].id === id) {
  158. debug("removing packet with ack id %d from the buffer", id);
  159. this.sendBuffer.splice(i, 1);
  160. }
  161. }
  162. debug("event with ack id %d has timed out after %d ms", id, timeout);
  163. ack.call(this, new Error("operation has timed out"));
  164. }, timeout);
  165. this.acks[id] = (...args) => {
  166. // @ts-ignore
  167. this.io.clearTimeoutFn(timer);
  168. ack.apply(this, [null, ...args]);
  169. };
  170. }
  171. /**
  172. * Sends a packet.
  173. *
  174. * @param packet
  175. * @private
  176. */
  177. packet(packet) {
  178. packet.nsp = this.nsp;
  179. this.io._packet(packet);
  180. }
  181. /**
  182. * Called upon engine `open`.
  183. *
  184. * @private
  185. */
  186. onopen() {
  187. debug("transport is open - connecting");
  188. if (typeof this.auth == "function") {
  189. this.auth((data) => {
  190. this.packet({ type: socket_io_parser_1.PacketType.CONNECT, data });
  191. });
  192. }
  193. else {
  194. this.packet({ type: socket_io_parser_1.PacketType.CONNECT, data: this.auth });
  195. }
  196. }
  197. /**
  198. * Called upon engine or manager `error`.
  199. *
  200. * @param err
  201. * @private
  202. */
  203. onerror(err) {
  204. if (!this.connected) {
  205. this.emitReserved("connect_error", err);
  206. }
  207. }
  208. /**
  209. * Called upon engine `close`.
  210. *
  211. * @param reason
  212. * @private
  213. */
  214. onclose(reason) {
  215. debug("close (%s)", reason);
  216. this.connected = false;
  217. this.disconnected = true;
  218. delete this.id;
  219. this.emitReserved("disconnect", reason);
  220. }
  221. /**
  222. * Called with socket packet.
  223. *
  224. * @param packet
  225. * @private
  226. */
  227. onpacket(packet) {
  228. const sameNamespace = packet.nsp === this.nsp;
  229. if (!sameNamespace)
  230. return;
  231. switch (packet.type) {
  232. case socket_io_parser_1.PacketType.CONNECT:
  233. if (packet.data && packet.data.sid) {
  234. const id = packet.data.sid;
  235. this.onconnect(id);
  236. }
  237. else {
  238. 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/)"));
  239. }
  240. break;
  241. case socket_io_parser_1.PacketType.EVENT:
  242. this.onevent(packet);
  243. break;
  244. case socket_io_parser_1.PacketType.BINARY_EVENT:
  245. this.onevent(packet);
  246. break;
  247. case socket_io_parser_1.PacketType.ACK:
  248. this.onack(packet);
  249. break;
  250. case socket_io_parser_1.PacketType.BINARY_ACK:
  251. this.onack(packet);
  252. break;
  253. case socket_io_parser_1.PacketType.DISCONNECT:
  254. this.ondisconnect();
  255. break;
  256. case socket_io_parser_1.PacketType.CONNECT_ERROR:
  257. this.destroy();
  258. const err = new Error(packet.data.message);
  259. // @ts-ignore
  260. err.data = packet.data.data;
  261. this.emitReserved("connect_error", err);
  262. break;
  263. }
  264. }
  265. /**
  266. * Called upon a server event.
  267. *
  268. * @param packet
  269. * @private
  270. */
  271. onevent(packet) {
  272. const args = packet.data || [];
  273. debug("emitting event %j", args);
  274. if (null != packet.id) {
  275. debug("attaching ack callback to event");
  276. args.push(this.ack(packet.id));
  277. }
  278. if (this.connected) {
  279. this.emitEvent(args);
  280. }
  281. else {
  282. this.receiveBuffer.push(Object.freeze(args));
  283. }
  284. }
  285. emitEvent(args) {
  286. if (this._anyListeners && this._anyListeners.length) {
  287. const listeners = this._anyListeners.slice();
  288. for (const listener of listeners) {
  289. listener.apply(this, args);
  290. }
  291. }
  292. super.emit.apply(this, args);
  293. }
  294. /**
  295. * Produces an ack callback to emit with an event.
  296. *
  297. * @private
  298. */
  299. ack(id) {
  300. const self = this;
  301. let sent = false;
  302. return function (...args) {
  303. // prevent double callbacks
  304. if (sent)
  305. return;
  306. sent = true;
  307. debug("sending ack %j", args);
  308. self.packet({
  309. type: socket_io_parser_1.PacketType.ACK,
  310. id: id,
  311. data: args,
  312. });
  313. };
  314. }
  315. /**
  316. * Called upon a server acknowlegement.
  317. *
  318. * @param packet
  319. * @private
  320. */
  321. onack(packet) {
  322. const ack = this.acks[packet.id];
  323. if ("function" === typeof ack) {
  324. debug("calling ack %s with %j", packet.id, packet.data);
  325. ack.apply(this, packet.data);
  326. delete this.acks[packet.id];
  327. }
  328. else {
  329. debug("bad ack %s", packet.id);
  330. }
  331. }
  332. /**
  333. * Called upon server connect.
  334. *
  335. * @private
  336. */
  337. onconnect(id) {
  338. debug("socket connected with id %s", id);
  339. this.id = id;
  340. this.connected = true;
  341. this.disconnected = false;
  342. this.emitBuffered();
  343. this.emitReserved("connect");
  344. }
  345. /**
  346. * Emit buffered events (received and emitted).
  347. *
  348. * @private
  349. */
  350. emitBuffered() {
  351. this.receiveBuffer.forEach((args) => this.emitEvent(args));
  352. this.receiveBuffer = [];
  353. this.sendBuffer.forEach((packet) => this.packet(packet));
  354. this.sendBuffer = [];
  355. }
  356. /**
  357. * Called upon server disconnect.
  358. *
  359. * @private
  360. */
  361. ondisconnect() {
  362. debug("server disconnect (%s)", this.nsp);
  363. this.destroy();
  364. this.onclose("io server disconnect");
  365. }
  366. /**
  367. * Called upon forced client/server side disconnections,
  368. * this method ensures the manager stops tracking us and
  369. * that reconnections don't get triggered for this.
  370. *
  371. * @private
  372. */
  373. destroy() {
  374. if (this.subs) {
  375. // clean subscriptions to avoid reconnections
  376. this.subs.forEach((subDestroy) => subDestroy());
  377. this.subs = undefined;
  378. }
  379. this.io["_destroy"](this);
  380. }
  381. /**
  382. * Disconnects the socket manually.
  383. *
  384. * @return self
  385. * @public
  386. */
  387. disconnect() {
  388. if (this.connected) {
  389. debug("performing disconnect (%s)", this.nsp);
  390. this.packet({ type: socket_io_parser_1.PacketType.DISCONNECT });
  391. }
  392. // remove socket from pool
  393. this.destroy();
  394. if (this.connected) {
  395. // fire events
  396. this.onclose("io client disconnect");
  397. }
  398. return this;
  399. }
  400. /**
  401. * Alias for disconnect()
  402. *
  403. * @return self
  404. * @public
  405. */
  406. close() {
  407. return this.disconnect();
  408. }
  409. /**
  410. * Sets the compress flag.
  411. *
  412. * @param compress - if `true`, compresses the sending data
  413. * @return self
  414. * @public
  415. */
  416. compress(compress) {
  417. this.flags.compress = compress;
  418. return this;
  419. }
  420. /**
  421. * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
  422. * ready to send messages.
  423. *
  424. * @returns self
  425. * @public
  426. */
  427. get volatile() {
  428. this.flags.volatile = true;
  429. return this;
  430. }
  431. /**
  432. * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
  433. * given number of milliseconds have elapsed without an acknowledgement from the server:
  434. *
  435. * ```
  436. * socket.timeout(5000).emit("my-event", (err) => {
  437. * if (err) {
  438. * // the server did not acknowledge the event in the given delay
  439. * }
  440. * });
  441. * ```
  442. *
  443. * @returns self
  444. * @public
  445. */
  446. timeout(timeout) {
  447. this.flags.timeout = timeout;
  448. return this;
  449. }
  450. /**
  451. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  452. * callback.
  453. *
  454. * @param listener
  455. * @public
  456. */
  457. onAny(listener) {
  458. this._anyListeners = this._anyListeners || [];
  459. this._anyListeners.push(listener);
  460. return this;
  461. }
  462. /**
  463. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  464. * callback. The listener is added to the beginning of the listeners array.
  465. *
  466. * @param listener
  467. * @public
  468. */
  469. prependAny(listener) {
  470. this._anyListeners = this._anyListeners || [];
  471. this._anyListeners.unshift(listener);
  472. return this;
  473. }
  474. /**
  475. * Removes the listener that will be fired when any event is emitted.
  476. *
  477. * @param listener
  478. * @public
  479. */
  480. offAny(listener) {
  481. if (!this._anyListeners) {
  482. return this;
  483. }
  484. if (listener) {
  485. const listeners = this._anyListeners;
  486. for (let i = 0; i < listeners.length; i++) {
  487. if (listener === listeners[i]) {
  488. listeners.splice(i, 1);
  489. return this;
  490. }
  491. }
  492. }
  493. else {
  494. this._anyListeners = [];
  495. }
  496. return this;
  497. }
  498. /**
  499. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  500. * e.g. to remove listeners.
  501. *
  502. * @public
  503. */
  504. listenersAny() {
  505. return this._anyListeners || [];
  506. }
  507. }
  508. exports.Socket = Socket;