namespace.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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.Namespace = exports.RESERVED_EVENTS = void 0;
  7. const socket_1 = require("./socket");
  8. const typed_events_1 = require("./typed-events");
  9. const debug_1 = __importDefault(require("debug"));
  10. const broadcast_operator_1 = require("./broadcast-operator");
  11. const debug = (0, debug_1.default)("socket.io:namespace");
  12. exports.RESERVED_EVENTS = new Set(["connect", "connection", "new_namespace"]);
  13. /**
  14. * A Namespace is a communication channel that allows you to split the logic of your application over a single shared
  15. * connection.
  16. *
  17. * Each namespace has its own:
  18. *
  19. * - event handlers
  20. *
  21. * ```
  22. * io.of("/orders").on("connection", (socket) => {
  23. * socket.on("order:list", () => {});
  24. * socket.on("order:create", () => {});
  25. * });
  26. *
  27. * io.of("/users").on("connection", (socket) => {
  28. * socket.on("user:list", () => {});
  29. * });
  30. * ```
  31. *
  32. * - rooms
  33. *
  34. * ```
  35. * const orderNamespace = io.of("/orders");
  36. *
  37. * orderNamespace.on("connection", (socket) => {
  38. * socket.join("room1");
  39. * orderNamespace.to("room1").emit("hello");
  40. * });
  41. *
  42. * const userNamespace = io.of("/users");
  43. *
  44. * userNamespace.on("connection", (socket) => {
  45. * socket.join("room1"); // distinct from the room in the "orders" namespace
  46. * userNamespace.to("room1").emit("holà");
  47. * });
  48. * ```
  49. *
  50. * - middlewares
  51. *
  52. * ```
  53. * const orderNamespace = io.of("/orders");
  54. *
  55. * orderNamespace.use((socket, next) => {
  56. * // ensure the socket has access to the "orders" namespace
  57. * });
  58. *
  59. * const userNamespace = io.of("/users");
  60. *
  61. * userNamespace.use((socket, next) => {
  62. * // ensure the socket has access to the "users" namespace
  63. * });
  64. * ```
  65. */
  66. class Namespace extends typed_events_1.StrictEventEmitter {
  67. /**
  68. * Namespace constructor.
  69. *
  70. * @param server instance
  71. * @param name
  72. */
  73. constructor(server, name) {
  74. super();
  75. this.sockets = new Map();
  76. /** @private */
  77. this._fns = [];
  78. /** @private */
  79. this._ids = 0;
  80. this.server = server;
  81. this.name = name;
  82. this._initAdapter();
  83. }
  84. /**
  85. * Initializes the `Adapter` for this nsp.
  86. * Run upon changing adapter by `Server#adapter`
  87. * in addition to the constructor.
  88. *
  89. * @private
  90. */
  91. _initAdapter() {
  92. // @ts-ignore
  93. this.adapter = new (this.server.adapter())(this);
  94. }
  95. /**
  96. * Registers a middleware, which is a function that gets executed for every incoming {@link Socket}.
  97. *
  98. * @example
  99. * const myNamespace = io.of("/my-namespace");
  100. *
  101. * myNamespace.use((socket, next) => {
  102. * // ...
  103. * next();
  104. * });
  105. *
  106. * @param fn - the middleware function
  107. */
  108. use(fn) {
  109. this._fns.push(fn);
  110. return this;
  111. }
  112. /**
  113. * Executes the middleware for an incoming client.
  114. *
  115. * @param socket - the socket that will get added
  116. * @param fn - last fn call in the middleware
  117. * @private
  118. */
  119. run(socket, fn) {
  120. const fns = this._fns.slice(0);
  121. if (!fns.length)
  122. return fn(null);
  123. function run(i) {
  124. fns[i](socket, function (err) {
  125. // upon error, short-circuit
  126. if (err)
  127. return fn(err);
  128. // if no middleware left, summon callback
  129. if (!fns[i + 1])
  130. return fn(null);
  131. // go on to next
  132. run(i + 1);
  133. });
  134. }
  135. run(0);
  136. }
  137. /**
  138. * Targets a room when emitting.
  139. *
  140. * @example
  141. * const myNamespace = io.of("/my-namespace");
  142. *
  143. * // the “foo” event will be broadcast to all connected clients in the “room-101” room
  144. * myNamespace.to("room-101").emit("foo", "bar");
  145. *
  146. * // with an array of rooms (a client will be notified at most once)
  147. * myNamespace.to(["room-101", "room-102"]).emit("foo", "bar");
  148. *
  149. * // with multiple chained calls
  150. * myNamespace.to("room-101").to("room-102").emit("foo", "bar");
  151. *
  152. * @param room - a room, or an array of rooms
  153. * @return a new {@link BroadcastOperator} instance for chaining
  154. */
  155. to(room) {
  156. return new broadcast_operator_1.BroadcastOperator(this.adapter).to(room);
  157. }
  158. /**
  159. * Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases:
  160. *
  161. * @example
  162. * const myNamespace = io.of("/my-namespace");
  163. *
  164. * // disconnect all clients in the "room-101" room
  165. * myNamespace.in("room-101").disconnectSockets();
  166. *
  167. * @param room - a room, or an array of rooms
  168. * @return a new {@link BroadcastOperator} instance for chaining
  169. */
  170. in(room) {
  171. return new broadcast_operator_1.BroadcastOperator(this.adapter).in(room);
  172. }
  173. /**
  174. * Excludes a room when emitting.
  175. *
  176. * @example
  177. * const myNamespace = io.of("/my-namespace");
  178. *
  179. * // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room
  180. * myNamespace.except("room-101").emit("foo", "bar");
  181. *
  182. * // with an array of rooms
  183. * myNamespace.except(["room-101", "room-102"]).emit("foo", "bar");
  184. *
  185. * // with multiple chained calls
  186. * myNamespace.except("room-101").except("room-102").emit("foo", "bar");
  187. *
  188. * @param room - a room, or an array of rooms
  189. * @return a new {@link BroadcastOperator} instance for chaining
  190. */
  191. except(room) {
  192. return new broadcast_operator_1.BroadcastOperator(this.adapter).except(room);
  193. }
  194. /**
  195. * Adds a new client.
  196. *
  197. * @return {Socket}
  198. * @private
  199. */
  200. async _add(client, auth, fn) {
  201. var _a;
  202. debug("adding socket to nsp %s", this.name);
  203. const socket = await this._createSocket(client, auth);
  204. if (
  205. // @ts-ignore
  206. ((_a = this.server.opts.connectionStateRecovery) === null || _a === void 0 ? void 0 : _a.skipMiddlewares) &&
  207. socket.recovered &&
  208. client.conn.readyState === "open") {
  209. return this._doConnect(socket, fn);
  210. }
  211. this.run(socket, (err) => {
  212. process.nextTick(() => {
  213. if ("open" !== client.conn.readyState) {
  214. debug("next called after client was closed - ignoring socket");
  215. socket._cleanup();
  216. return;
  217. }
  218. if (err) {
  219. debug("middleware error, sending CONNECT_ERROR packet to the client");
  220. socket._cleanup();
  221. if (client.conn.protocol === 3) {
  222. return socket._error(err.data || err.message);
  223. }
  224. else {
  225. return socket._error({
  226. message: err.message,
  227. data: err.data,
  228. });
  229. }
  230. }
  231. this._doConnect(socket, fn);
  232. });
  233. });
  234. }
  235. async _createSocket(client, auth) {
  236. const sessionId = auth.pid;
  237. const offset = auth.offset;
  238. if (
  239. // @ts-ignore
  240. this.server.opts.connectionStateRecovery &&
  241. typeof sessionId === "string" &&
  242. typeof offset === "string") {
  243. let session;
  244. try {
  245. session = await this.adapter.restoreSession(sessionId, offset);
  246. }
  247. catch (e) {
  248. debug("error while restoring session: %s", e);
  249. }
  250. if (session) {
  251. debug("connection state recovered for sid %s", session.sid);
  252. return new socket_1.Socket(this, client, auth, session);
  253. }
  254. }
  255. return new socket_1.Socket(this, client, auth);
  256. }
  257. _doConnect(socket, fn) {
  258. // track socket
  259. this.sockets.set(socket.id, socket);
  260. // it's paramount that the internal `onconnect` logic
  261. // fires before user-set events to prevent state order
  262. // violations (such as a disconnection before the connection
  263. // logic is complete)
  264. socket._onconnect();
  265. if (fn)
  266. fn(socket);
  267. // fire user-set events
  268. this.emitReserved("connect", socket);
  269. this.emitReserved("connection", socket);
  270. }
  271. /**
  272. * Removes a client. Called by each `Socket`.
  273. *
  274. * @private
  275. */
  276. _remove(socket) {
  277. if (this.sockets.has(socket.id)) {
  278. this.sockets.delete(socket.id);
  279. }
  280. else {
  281. debug("ignoring remove for %s", socket.id);
  282. }
  283. }
  284. /**
  285. * Emits to all connected clients.
  286. *
  287. * @example
  288. * const myNamespace = io.of("/my-namespace");
  289. *
  290. * myNamespace.emit("hello", "world");
  291. *
  292. * // all serializable datastructures are supported (no need to call JSON.stringify)
  293. * myNamespace.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
  294. *
  295. * // with an acknowledgement from the clients
  296. * myNamespace.timeout(1000).emit("some-event", (err, responses) => {
  297. * if (err) {
  298. * // some clients did not acknowledge the event in the given delay
  299. * } else {
  300. * console.log(responses); // one response per client
  301. * }
  302. * });
  303. *
  304. * @return Always true
  305. */
  306. emit(ev, ...args) {
  307. return new broadcast_operator_1.BroadcastOperator(this.adapter).emit(ev, ...args);
  308. }
  309. /**
  310. * Sends a `message` event to all clients.
  311. *
  312. * This method mimics the WebSocket.send() method.
  313. *
  314. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
  315. *
  316. * @example
  317. * const myNamespace = io.of("/my-namespace");
  318. *
  319. * myNamespace.send("hello");
  320. *
  321. * // this is equivalent to
  322. * myNamespace.emit("message", "hello");
  323. *
  324. * @return self
  325. */
  326. send(...args) {
  327. // This type-cast is needed because EmitEvents likely doesn't have `message` as a key.
  328. // if you specify the EmitEvents, the type of args will be never.
  329. this.emit("message", ...args);
  330. return this;
  331. }
  332. /**
  333. * Sends a `message` event to all clients. Sends a `message` event. Alias of {@link send}.
  334. *
  335. * @return self
  336. */
  337. write(...args) {
  338. // This type-cast is needed because EmitEvents likely doesn't have `message` as a key.
  339. // if you specify the EmitEvents, the type of args will be never.
  340. this.emit("message", ...args);
  341. return this;
  342. }
  343. /**
  344. * Sends a message to the other Socket.IO servers of the cluster.
  345. *
  346. * @example
  347. * const myNamespace = io.of("/my-namespace");
  348. *
  349. * myNamespace.serverSideEmit("hello", "world");
  350. *
  351. * myNamespace.on("hello", (arg1) => {
  352. * console.log(arg1); // prints "world"
  353. * });
  354. *
  355. * // acknowledgements (without binary content) are supported too:
  356. * myNamespace.serverSideEmit("ping", (err, responses) => {
  357. * if (err) {
  358. * // some servers did not acknowledge the event in the given delay
  359. * } else {
  360. * console.log(responses); // one response per server (except the current one)
  361. * }
  362. * });
  363. *
  364. * myNamespace.on("ping", (cb) => {
  365. * cb("pong");
  366. * });
  367. *
  368. * @param ev - the event name
  369. * @param args - an array of arguments, which may include an acknowledgement callback at the end
  370. */
  371. serverSideEmit(ev, ...args) {
  372. if (exports.RESERVED_EVENTS.has(ev)) {
  373. throw new Error(`"${String(ev)}" is a reserved event name`);
  374. }
  375. args.unshift(ev);
  376. this.adapter.serverSideEmit(args);
  377. return true;
  378. }
  379. /**
  380. * Sends a message and expect an acknowledgement from the other Socket.IO servers of the cluster.
  381. *
  382. * @example
  383. * const myNamespace = io.of("/my-namespace");
  384. *
  385. * try {
  386. * const responses = await myNamespace.serverSideEmitWithAck("ping");
  387. * console.log(responses); // one response per server (except the current one)
  388. * } catch (e) {
  389. * // some servers did not acknowledge the event in the given delay
  390. * }
  391. *
  392. * @param ev - the event name
  393. * @param args - an array of arguments
  394. *
  395. * @return a Promise that will be fulfilled when all servers have acknowledged the event
  396. */
  397. serverSideEmitWithAck(ev, ...args) {
  398. return new Promise((resolve, reject) => {
  399. args.push((err, responses) => {
  400. if (err) {
  401. err.responses = responses;
  402. return reject(err);
  403. }
  404. else {
  405. return resolve(responses);
  406. }
  407. });
  408. this.serverSideEmit(ev, ...args);
  409. });
  410. }
  411. /**
  412. * Called when a packet is received from another Socket.IO server
  413. *
  414. * @param args - an array of arguments, which may include an acknowledgement callback at the end
  415. *
  416. * @private
  417. */
  418. _onServerSideEmit(args) {
  419. super.emitUntyped.apply(this, args);
  420. }
  421. /**
  422. * Gets a list of clients.
  423. *
  424. * @deprecated this method will be removed in the next major release, please use {@link Namespace#serverSideEmit} or
  425. * {@link Namespace#fetchSockets} instead.
  426. */
  427. allSockets() {
  428. return new broadcast_operator_1.BroadcastOperator(this.adapter).allSockets();
  429. }
  430. /**
  431. * Sets the compress flag.
  432. *
  433. * @example
  434. * const myNamespace = io.of("/my-namespace");
  435. *
  436. * myNamespace.compress(false).emit("hello");
  437. *
  438. * @param compress - if `true`, compresses the sending data
  439. * @return self
  440. */
  441. compress(compress) {
  442. return new broadcast_operator_1.BroadcastOperator(this.adapter).compress(compress);
  443. }
  444. /**
  445. * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
  446. * receive messages (because of network slowness or other issues, or because they’re connected through long polling
  447. * and is in the middle of a request-response cycle).
  448. *
  449. * @example
  450. * const myNamespace = io.of("/my-namespace");
  451. *
  452. * myNamespace.volatile.emit("hello"); // the clients may or may not receive it
  453. *
  454. * @return self
  455. */
  456. get volatile() {
  457. return new broadcast_operator_1.BroadcastOperator(this.adapter).volatile;
  458. }
  459. /**
  460. * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
  461. *
  462. * @example
  463. * const myNamespace = io.of("/my-namespace");
  464. *
  465. * // the “foo” event will be broadcast to all connected clients on this node
  466. * myNamespace.local.emit("foo", "bar");
  467. *
  468. * @return a new {@link BroadcastOperator} instance for chaining
  469. */
  470. get local() {
  471. return new broadcast_operator_1.BroadcastOperator(this.adapter).local;
  472. }
  473. /**
  474. * Adds a timeout in milliseconds for the next operation.
  475. *
  476. * @example
  477. * const myNamespace = io.of("/my-namespace");
  478. *
  479. * myNamespace.timeout(1000).emit("some-event", (err, responses) => {
  480. * if (err) {
  481. * // some clients did not acknowledge the event in the given delay
  482. * } else {
  483. * console.log(responses); // one response per client
  484. * }
  485. * });
  486. *
  487. * @param timeout
  488. */
  489. timeout(timeout) {
  490. return new broadcast_operator_1.BroadcastOperator(this.adapter).timeout(timeout);
  491. }
  492. /**
  493. * Returns the matching socket instances.
  494. *
  495. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  496. *
  497. * @example
  498. * const myNamespace = io.of("/my-namespace");
  499. *
  500. * // return all Socket instances
  501. * const sockets = await myNamespace.fetchSockets();
  502. *
  503. * // return all Socket instances in the "room1" room
  504. * const sockets = await myNamespace.in("room1").fetchSockets();
  505. *
  506. * for (const socket of sockets) {
  507. * console.log(socket.id);
  508. * console.log(socket.handshake);
  509. * console.log(socket.rooms);
  510. * console.log(socket.data);
  511. *
  512. * socket.emit("hello");
  513. * socket.join("room1");
  514. * socket.leave("room2");
  515. * socket.disconnect();
  516. * }
  517. */
  518. fetchSockets() {
  519. return new broadcast_operator_1.BroadcastOperator(this.adapter).fetchSockets();
  520. }
  521. /**
  522. * Makes the matching socket instances join the specified rooms.
  523. *
  524. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  525. *
  526. * @example
  527. * const myNamespace = io.of("/my-namespace");
  528. *
  529. * // make all socket instances join the "room1" room
  530. * myNamespace.socketsJoin("room1");
  531. *
  532. * // make all socket instances in the "room1" room join the "room2" and "room3" rooms
  533. * myNamespace.in("room1").socketsJoin(["room2", "room3"]);
  534. *
  535. * @param room - a room, or an array of rooms
  536. */
  537. socketsJoin(room) {
  538. return new broadcast_operator_1.BroadcastOperator(this.adapter).socketsJoin(room);
  539. }
  540. /**
  541. * Makes the matching socket instances leave the specified rooms.
  542. *
  543. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  544. *
  545. * @example
  546. * const myNamespace = io.of("/my-namespace");
  547. *
  548. * // make all socket instances leave the "room1" room
  549. * myNamespace.socketsLeave("room1");
  550. *
  551. * // make all socket instances in the "room1" room leave the "room2" and "room3" rooms
  552. * myNamespace.in("room1").socketsLeave(["room2", "room3"]);
  553. *
  554. * @param room - a room, or an array of rooms
  555. */
  556. socketsLeave(room) {
  557. return new broadcast_operator_1.BroadcastOperator(this.adapter).socketsLeave(room);
  558. }
  559. /**
  560. * Makes the matching socket instances disconnect.
  561. *
  562. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  563. *
  564. * @example
  565. * const myNamespace = io.of("/my-namespace");
  566. *
  567. * // make all socket instances disconnect (the connections might be kept alive for other namespaces)
  568. * myNamespace.disconnectSockets();
  569. *
  570. * // make all socket instances in the "room1" room disconnect and close the underlying connections
  571. * myNamespace.in("room1").disconnectSockets(true);
  572. *
  573. * @param close - whether to close the underlying connection
  574. */
  575. disconnectSockets(close = false) {
  576. return new broadcast_operator_1.BroadcastOperator(this.adapter).disconnectSockets(close);
  577. }
  578. }
  579. exports.Namespace = Namespace;