Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

namespace.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. _add(client, query, fn) {
  201. debug("adding socket to nsp %s", this.name);
  202. const socket = new socket_1.Socket(this, client, query);
  203. this.run(socket, (err) => {
  204. process.nextTick(() => {
  205. if ("open" !== client.conn.readyState) {
  206. debug("next called after client was closed - ignoring socket");
  207. socket._cleanup();
  208. return;
  209. }
  210. if (err) {
  211. debug("middleware error, sending CONNECT_ERROR packet to the client");
  212. socket._cleanup();
  213. if (client.conn.protocol === 3) {
  214. return socket._error(err.data || err.message);
  215. }
  216. else {
  217. return socket._error({
  218. message: err.message,
  219. data: err.data,
  220. });
  221. }
  222. }
  223. // track socket
  224. this.sockets.set(socket.id, socket);
  225. // it's paramount that the internal `onconnect` logic
  226. // fires before user-set events to prevent state order
  227. // violations (such as a disconnection before the connection
  228. // logic is complete)
  229. socket._onconnect();
  230. if (fn)
  231. fn();
  232. // fire user-set events
  233. this.emitReserved("connect", socket);
  234. this.emitReserved("connection", socket);
  235. });
  236. });
  237. return socket;
  238. }
  239. /**
  240. * Removes a client. Called by each `Socket`.
  241. *
  242. * @private
  243. */
  244. _remove(socket) {
  245. if (this.sockets.has(socket.id)) {
  246. this.sockets.delete(socket.id);
  247. }
  248. else {
  249. debug("ignoring remove for %s", socket.id);
  250. }
  251. }
  252. /**
  253. * Emits to all connected clients.
  254. *
  255. * @example
  256. * const myNamespace = io.of("/my-namespace");
  257. *
  258. * myNamespace.emit("hello", "world");
  259. *
  260. * // all serializable datastructures are supported (no need to call JSON.stringify)
  261. * myNamespace.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
  262. *
  263. * // with an acknowledgement from the clients
  264. * myNamespace.timeout(1000).emit("some-event", (err, responses) => {
  265. * if (err) {
  266. * // some clients did not acknowledge the event in the given delay
  267. * } else {
  268. * console.log(responses); // one response per client
  269. * }
  270. * });
  271. *
  272. * @return Always true
  273. */
  274. emit(ev, ...args) {
  275. return new broadcast_operator_1.BroadcastOperator(this.adapter).emit(ev, ...args);
  276. }
  277. /**
  278. * Sends a `message` event to all clients.
  279. *
  280. * This method mimics the WebSocket.send() method.
  281. *
  282. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
  283. *
  284. * @example
  285. * const myNamespace = io.of("/my-namespace");
  286. *
  287. * myNamespace.send("hello");
  288. *
  289. * // this is equivalent to
  290. * myNamespace.emit("message", "hello");
  291. *
  292. * @return self
  293. */
  294. send(...args) {
  295. this.emit("message", ...args);
  296. return this;
  297. }
  298. /**
  299. * Sends a `message` event to all clients. Sends a `message` event. Alias of {@link send}.
  300. *
  301. * @return self
  302. */
  303. write(...args) {
  304. this.emit("message", ...args);
  305. return this;
  306. }
  307. /**
  308. * Sends a message to the other Socket.IO servers of the cluster.
  309. *
  310. * @example
  311. * const myNamespace = io.of("/my-namespace");
  312. *
  313. * myNamespace.serverSideEmit("hello", "world");
  314. *
  315. * myNamespace.on("hello", (arg1) => {
  316. * console.log(arg1); // prints "world"
  317. * });
  318. *
  319. * // acknowledgements (without binary content) are supported too:
  320. * myNamespace.serverSideEmit("ping", (err, responses) => {
  321. * if (err) {
  322. * // some clients did not acknowledge the event in the given delay
  323. * } else {
  324. * console.log(responses); // one response per client
  325. * }
  326. * });
  327. *
  328. * myNamespace.on("ping", (cb) => {
  329. * cb("pong");
  330. * });
  331. *
  332. * @param ev - the event name
  333. * @param args - an array of arguments, which may include an acknowledgement callback at the end
  334. */
  335. serverSideEmit(ev, ...args) {
  336. if (exports.RESERVED_EVENTS.has(ev)) {
  337. throw new Error(`"${String(ev)}" is a reserved event name`);
  338. }
  339. args.unshift(ev);
  340. this.adapter.serverSideEmit(args);
  341. return true;
  342. }
  343. /**
  344. * Called when a packet is received from another Socket.IO server
  345. *
  346. * @param args - an array of arguments, which may include an acknowledgement callback at the end
  347. *
  348. * @private
  349. */
  350. _onServerSideEmit(args) {
  351. super.emitUntyped.apply(this, args);
  352. }
  353. /**
  354. * Gets a list of clients.
  355. *
  356. * @deprecated this method will be removed in the next major release, please use {@link Namespace#serverSideEmit} or
  357. * {@link Namespace#fetchSockets} instead.
  358. */
  359. allSockets() {
  360. return new broadcast_operator_1.BroadcastOperator(this.adapter).allSockets();
  361. }
  362. /**
  363. * Sets the compress flag.
  364. *
  365. * @example
  366. * const myNamespace = io.of("/my-namespace");
  367. *
  368. * myNamespace.compress(false).emit("hello");
  369. *
  370. * @param compress - if `true`, compresses the sending data
  371. * @return self
  372. */
  373. compress(compress) {
  374. return new broadcast_operator_1.BroadcastOperator(this.adapter).compress(compress);
  375. }
  376. /**
  377. * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
  378. * receive messages (because of network slowness or other issues, or because they’re connected through long polling
  379. * and is in the middle of a request-response cycle).
  380. *
  381. * @example
  382. * const myNamespace = io.of("/my-namespace");
  383. *
  384. * myNamespace.volatile.emit("hello"); // the clients may or may not receive it
  385. *
  386. * @return self
  387. */
  388. get volatile() {
  389. return new broadcast_operator_1.BroadcastOperator(this.adapter).volatile;
  390. }
  391. /**
  392. * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
  393. *
  394. * @example
  395. * const myNamespace = io.of("/my-namespace");
  396. *
  397. * // the “foo” event will be broadcast to all connected clients on this node
  398. * myNamespace.local.emit("foo", "bar");
  399. *
  400. * @return a new {@link BroadcastOperator} instance for chaining
  401. */
  402. get local() {
  403. return new broadcast_operator_1.BroadcastOperator(this.adapter).local;
  404. }
  405. /**
  406. * Adds a timeout in milliseconds for the next operation.
  407. *
  408. * @example
  409. * const myNamespace = io.of("/my-namespace");
  410. *
  411. * myNamespace.timeout(1000).emit("some-event", (err, responses) => {
  412. * if (err) {
  413. * // some clients did not acknowledge the event in the given delay
  414. * } else {
  415. * console.log(responses); // one response per client
  416. * }
  417. * });
  418. *
  419. * @param timeout
  420. */
  421. timeout(timeout) {
  422. return new broadcast_operator_1.BroadcastOperator(this.adapter).timeout(timeout);
  423. }
  424. /**
  425. * Returns the matching socket instances.
  426. *
  427. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  428. *
  429. * @example
  430. * const myNamespace = io.of("/my-namespace");
  431. *
  432. * // return all Socket instances
  433. * const sockets = await myNamespace.fetchSockets();
  434. *
  435. * // return all Socket instances in the "room1" room
  436. * const sockets = await myNamespace.in("room1").fetchSockets();
  437. *
  438. * for (const socket of sockets) {
  439. * console.log(socket.id);
  440. * console.log(socket.handshake);
  441. * console.log(socket.rooms);
  442. * console.log(socket.data);
  443. *
  444. * socket.emit("hello");
  445. * socket.join("room1");
  446. * socket.leave("room2");
  447. * socket.disconnect();
  448. * }
  449. */
  450. fetchSockets() {
  451. return new broadcast_operator_1.BroadcastOperator(this.adapter).fetchSockets();
  452. }
  453. /**
  454. * Makes the matching socket instances join the specified rooms.
  455. *
  456. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  457. *
  458. * @example
  459. * const myNamespace = io.of("/my-namespace");
  460. *
  461. * // make all socket instances join the "room1" room
  462. * myNamespace.socketsJoin("room1");
  463. *
  464. * // make all socket instances in the "room1" room join the "room2" and "room3" rooms
  465. * myNamespace.in("room1").socketsJoin(["room2", "room3"]);
  466. *
  467. * @param room - a room, or an array of rooms
  468. */
  469. socketsJoin(room) {
  470. return new broadcast_operator_1.BroadcastOperator(this.adapter).socketsJoin(room);
  471. }
  472. /**
  473. * Makes the matching socket instances leave the specified rooms.
  474. *
  475. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  476. *
  477. * @example
  478. * const myNamespace = io.of("/my-namespace");
  479. *
  480. * // make all socket instances leave the "room1" room
  481. * myNamespace.socketsLeave("room1");
  482. *
  483. * // make all socket instances in the "room1" room leave the "room2" and "room3" rooms
  484. * myNamespace.in("room1").socketsLeave(["room2", "room3"]);
  485. *
  486. * @param room - a room, or an array of rooms
  487. */
  488. socketsLeave(room) {
  489. return new broadcast_operator_1.BroadcastOperator(this.adapter).socketsLeave(room);
  490. }
  491. /**
  492. * Makes the matching socket instances disconnect.
  493. *
  494. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  495. *
  496. * @example
  497. * const myNamespace = io.of("/my-namespace");
  498. *
  499. * // make all socket instances disconnect (the connections might be kept alive for other namespaces)
  500. * myNamespace.disconnectSockets();
  501. *
  502. * // make all socket instances in the "room1" room disconnect and close the underlying connections
  503. * myNamespace.in("room1").disconnectSockets(true);
  504. *
  505. * @param close - whether to close the underlying connection
  506. */
  507. disconnectSockets(close = false) {
  508. return new broadcast_operator_1.BroadcastOperator(this.adapter).disconnectSockets(close);
  509. }
  510. }
  511. exports.Namespace = Namespace;