namespace.js 19 KB

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