namespace.d.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import { Socket } from "./socket";
  2. import type { Server } from "./index";
  3. import { EventParams, EventNames, EventsMap, StrictEventEmitter, DefaultEventsMap, DecorateAcknowledgementsWithTimeoutAndMultipleResponses, AllButLast, Last, FirstArg, SecondArg } from "./typed-events";
  4. import type { Client } from "./client";
  5. import type { Adapter, Room, SocketId } from "socket.io-adapter";
  6. import { BroadcastOperator } from "./broadcast-operator";
  7. export interface ExtendedError extends Error {
  8. data?: any;
  9. }
  10. export interface NamespaceReservedEventsMap<ListenEvents extends EventsMap, EmitEvents extends EventsMap, ServerSideEvents extends EventsMap, SocketData> {
  11. connect: (socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>) => void;
  12. connection: (socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>) => void;
  13. }
  14. export interface ServerReservedEventsMap<ListenEvents extends EventsMap, EmitEvents extends EventsMap, ServerSideEvents extends EventsMap, SocketData> extends NamespaceReservedEventsMap<ListenEvents, EmitEvents, ServerSideEvents, SocketData> {
  15. new_namespace: (namespace: Namespace<ListenEvents, EmitEvents, ServerSideEvents, SocketData>) => void;
  16. }
  17. export declare const RESERVED_EVENTS: ReadonlySet<string | Symbol>;
  18. /**
  19. * A Namespace is a communication channel that allows you to split the logic of your application over a single shared
  20. * connection.
  21. *
  22. * Each namespace has its own:
  23. *
  24. * - event handlers
  25. *
  26. * ```
  27. * io.of("/orders").on("connection", (socket) => {
  28. * socket.on("order:list", () => {});
  29. * socket.on("order:create", () => {});
  30. * });
  31. *
  32. * io.of("/users").on("connection", (socket) => {
  33. * socket.on("user:list", () => {});
  34. * });
  35. * ```
  36. *
  37. * - rooms
  38. *
  39. * ```
  40. * const orderNamespace = io.of("/orders");
  41. *
  42. * orderNamespace.on("connection", (socket) => {
  43. * socket.join("room1");
  44. * orderNamespace.to("room1").emit("hello");
  45. * });
  46. *
  47. * const userNamespace = io.of("/users");
  48. *
  49. * userNamespace.on("connection", (socket) => {
  50. * socket.join("room1"); // distinct from the room in the "orders" namespace
  51. * userNamespace.to("room1").emit("holà");
  52. * });
  53. * ```
  54. *
  55. * - middlewares
  56. *
  57. * ```
  58. * const orderNamespace = io.of("/orders");
  59. *
  60. * orderNamespace.use((socket, next) => {
  61. * // ensure the socket has access to the "orders" namespace
  62. * });
  63. *
  64. * const userNamespace = io.of("/users");
  65. *
  66. * userNamespace.use((socket, next) => {
  67. * // ensure the socket has access to the "users" namespace
  68. * });
  69. * ```
  70. */
  71. export declare class Namespace<ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents, ServerSideEvents extends EventsMap = DefaultEventsMap, SocketData = any> extends StrictEventEmitter<ServerSideEvents, EmitEvents, NamespaceReservedEventsMap<ListenEvents, EmitEvents, ServerSideEvents, SocketData>> {
  72. readonly name: string;
  73. readonly sockets: Map<SocketId, Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>>;
  74. adapter: Adapter;
  75. /** @private */
  76. readonly server: Server<ListenEvents, EmitEvents, ServerSideEvents, SocketData>;
  77. /** @private */
  78. _fns: Array<(socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>, next: (err?: ExtendedError) => void) => void>;
  79. /** @private */
  80. _ids: number;
  81. /**
  82. * Namespace constructor.
  83. *
  84. * @param server instance
  85. * @param name
  86. */
  87. constructor(server: Server<ListenEvents, EmitEvents, ServerSideEvents, SocketData>, name: string);
  88. /**
  89. * Initializes the `Adapter` for this nsp.
  90. * Run upon changing adapter by `Server#adapter`
  91. * in addition to the constructor.
  92. *
  93. * @private
  94. */
  95. _initAdapter(): void;
  96. /**
  97. * Registers a middleware, which is a function that gets executed for every incoming {@link Socket}.
  98. *
  99. * @example
  100. * const myNamespace = io.of("/my-namespace");
  101. *
  102. * myNamespace.use((socket, next) => {
  103. * // ...
  104. * next();
  105. * });
  106. *
  107. * @param fn - the middleware function
  108. */
  109. use(fn: (socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>, next: (err?: ExtendedError) => void) => void): this;
  110. /**
  111. * Executes the middleware for an incoming client.
  112. *
  113. * @param socket - the socket that will get added
  114. * @param fn - last fn call in the middleware
  115. * @private
  116. */
  117. private run;
  118. /**
  119. * Targets a room when emitting.
  120. *
  121. * @example
  122. * const myNamespace = io.of("/my-namespace");
  123. *
  124. * // the “foo” event will be broadcast to all connected clients in the “room-101” room
  125. * myNamespace.to("room-101").emit("foo", "bar");
  126. *
  127. * // with an array of rooms (a client will be notified at most once)
  128. * myNamespace.to(["room-101", "room-102"]).emit("foo", "bar");
  129. *
  130. * // with multiple chained calls
  131. * myNamespace.to("room-101").to("room-102").emit("foo", "bar");
  132. *
  133. * @param room - a room, or an array of rooms
  134. * @return a new {@link BroadcastOperator} instance for chaining
  135. */
  136. to(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData>;
  137. /**
  138. * Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases:
  139. *
  140. * @example
  141. * const myNamespace = io.of("/my-namespace");
  142. *
  143. * // disconnect all clients in the "room-101" room
  144. * myNamespace.in("room-101").disconnectSockets();
  145. *
  146. * @param room - a room, or an array of rooms
  147. * @return a new {@link BroadcastOperator} instance for chaining
  148. */
  149. in(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData>;
  150. /**
  151. * Excludes a room when emitting.
  152. *
  153. * @example
  154. * const myNamespace = io.of("/my-namespace");
  155. *
  156. * // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room
  157. * myNamespace.except("room-101").emit("foo", "bar");
  158. *
  159. * // with an array of rooms
  160. * myNamespace.except(["room-101", "room-102"]).emit("foo", "bar");
  161. *
  162. * // with multiple chained calls
  163. * myNamespace.except("room-101").except("room-102").emit("foo", "bar");
  164. *
  165. * @param room - a room, or an array of rooms
  166. * @return a new {@link BroadcastOperator} instance for chaining
  167. */
  168. except(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData>;
  169. /**
  170. * Adds a new client.
  171. *
  172. * @return {Socket}
  173. * @private
  174. */
  175. _add(client: Client<ListenEvents, EmitEvents, ServerSideEvents>, auth: Record<string, unknown>, fn: (socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>) => void): any;
  176. private _createSocket;
  177. private _doConnect;
  178. /**
  179. * Removes a client. Called by each `Socket`.
  180. *
  181. * @private
  182. */
  183. _remove(socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>): void;
  184. /**
  185. * Emits to all connected clients.
  186. *
  187. * @example
  188. * const myNamespace = io.of("/my-namespace");
  189. *
  190. * myNamespace.emit("hello", "world");
  191. *
  192. * // all serializable datastructures are supported (no need to call JSON.stringify)
  193. * myNamespace.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
  194. *
  195. * // with an acknowledgement from the clients
  196. * myNamespace.timeout(1000).emit("some-event", (err, responses) => {
  197. * if (err) {
  198. * // some clients did not acknowledge the event in the given delay
  199. * } else {
  200. * console.log(responses); // one response per client
  201. * }
  202. * });
  203. *
  204. * @return Always true
  205. */
  206. emit<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: EventParams<EmitEvents, Ev>): boolean;
  207. /**
  208. * Emits an event and waits for an acknowledgement from all clients.
  209. *
  210. * @example
  211. * const myNamespace = io.of("/my-namespace");
  212. *
  213. * try {
  214. * const responses = await myNamespace.timeout(1000).emitWithAck("some-event");
  215. * console.log(responses); // one response per client
  216. * } catch (e) {
  217. * // some clients did not acknowledge the event in the given delay
  218. * }
  219. *
  220. * @return a Promise that will be fulfilled when all clients have acknowledged the event
  221. */
  222. emitWithAck<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: AllButLast<EventParams<EmitEvents, Ev>>): Promise<SecondArg<Last<EventParams<EmitEvents, Ev>>>>;
  223. /**
  224. * Sends a `message` event to all clients.
  225. *
  226. * This method mimics the WebSocket.send() method.
  227. *
  228. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
  229. *
  230. * @example
  231. * const myNamespace = io.of("/my-namespace");
  232. *
  233. * myNamespace.send("hello");
  234. *
  235. * // this is equivalent to
  236. * myNamespace.emit("message", "hello");
  237. *
  238. * @return self
  239. */
  240. send(...args: EventParams<EmitEvents, "message">): this;
  241. /**
  242. * Sends a `message` event to all clients. Sends a `message` event. Alias of {@link send}.
  243. *
  244. * @return self
  245. */
  246. write(...args: EventParams<EmitEvents, "message">): this;
  247. /**
  248. * Sends a message to the other Socket.IO servers of the cluster.
  249. *
  250. * @example
  251. * const myNamespace = io.of("/my-namespace");
  252. *
  253. * myNamespace.serverSideEmit("hello", "world");
  254. *
  255. * myNamespace.on("hello", (arg1) => {
  256. * console.log(arg1); // prints "world"
  257. * });
  258. *
  259. * // acknowledgements (without binary content) are supported too:
  260. * myNamespace.serverSideEmit("ping", (err, responses) => {
  261. * if (err) {
  262. * // some servers did not acknowledge the event in the given delay
  263. * } else {
  264. * console.log(responses); // one response per server (except the current one)
  265. * }
  266. * });
  267. *
  268. * myNamespace.on("ping", (cb) => {
  269. * cb("pong");
  270. * });
  271. *
  272. * @param ev - the event name
  273. * @param args - an array of arguments, which may include an acknowledgement callback at the end
  274. */
  275. serverSideEmit<Ev extends EventNames<ServerSideEvents>>(ev: Ev, ...args: EventParams<DecorateAcknowledgementsWithTimeoutAndMultipleResponses<ServerSideEvents>, Ev>): boolean;
  276. /**
  277. * Sends a message and expect an acknowledgement from the other Socket.IO servers of the cluster.
  278. *
  279. * @example
  280. * const myNamespace = io.of("/my-namespace");
  281. *
  282. * try {
  283. * const responses = await myNamespace.serverSideEmitWithAck("ping");
  284. * console.log(responses); // one response per server (except the current one)
  285. * } catch (e) {
  286. * // some servers did not acknowledge the event in the given delay
  287. * }
  288. *
  289. * @param ev - the event name
  290. * @param args - an array of arguments
  291. *
  292. * @return a Promise that will be fulfilled when all servers have acknowledged the event
  293. */
  294. serverSideEmitWithAck<Ev extends EventNames<ServerSideEvents>>(ev: Ev, ...args: AllButLast<EventParams<ServerSideEvents, Ev>>): Promise<FirstArg<Last<EventParams<ServerSideEvents, Ev>>>[]>;
  295. /**
  296. * Called when a packet is received from another Socket.IO server
  297. *
  298. * @param args - an array of arguments, which may include an acknowledgement callback at the end
  299. *
  300. * @private
  301. */
  302. _onServerSideEmit(args: [string, ...any[]]): void;
  303. /**
  304. * Gets a list of clients.
  305. *
  306. * @deprecated this method will be removed in the next major release, please use {@link Namespace#serverSideEmit} or
  307. * {@link Namespace#fetchSockets} instead.
  308. */
  309. allSockets(): Promise<Set<SocketId>>;
  310. /**
  311. * Sets the compress flag.
  312. *
  313. * @example
  314. * const myNamespace = io.of("/my-namespace");
  315. *
  316. * myNamespace.compress(false).emit("hello");
  317. *
  318. * @param compress - if `true`, compresses the sending data
  319. * @return self
  320. */
  321. compress(compress: boolean): BroadcastOperator<EmitEvents, SocketData>;
  322. /**
  323. * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
  324. * receive messages (because of network slowness or other issues, or because they’re connected through long polling
  325. * and is in the middle of a request-response cycle).
  326. *
  327. * @example
  328. * const myNamespace = io.of("/my-namespace");
  329. *
  330. * myNamespace.volatile.emit("hello"); // the clients may or may not receive it
  331. *
  332. * @return self
  333. */
  334. get volatile(): BroadcastOperator<EmitEvents, SocketData>;
  335. /**
  336. * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
  337. *
  338. * @example
  339. * const myNamespace = io.of("/my-namespace");
  340. *
  341. * // the “foo” event will be broadcast to all connected clients on this node
  342. * myNamespace.local.emit("foo", "bar");
  343. *
  344. * @return a new {@link BroadcastOperator} instance for chaining
  345. */
  346. get local(): BroadcastOperator<EmitEvents, SocketData>;
  347. /**
  348. * Adds a timeout in milliseconds for the next operation.
  349. *
  350. * @example
  351. * const myNamespace = io.of("/my-namespace");
  352. *
  353. * myNamespace.timeout(1000).emit("some-event", (err, responses) => {
  354. * if (err) {
  355. * // some clients did not acknowledge the event in the given delay
  356. * } else {
  357. * console.log(responses); // one response per client
  358. * }
  359. * });
  360. *
  361. * @param timeout
  362. */
  363. timeout(timeout: number): BroadcastOperator<DecorateAcknowledgementsWithTimeoutAndMultipleResponses<EmitEvents>, SocketData>;
  364. /**
  365. * Returns the matching socket instances.
  366. *
  367. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  368. *
  369. * @example
  370. * const myNamespace = io.of("/my-namespace");
  371. *
  372. * // return all Socket instances
  373. * const sockets = await myNamespace.fetchSockets();
  374. *
  375. * // return all Socket instances in the "room1" room
  376. * const sockets = await myNamespace.in("room1").fetchSockets();
  377. *
  378. * for (const socket of sockets) {
  379. * console.log(socket.id);
  380. * console.log(socket.handshake);
  381. * console.log(socket.rooms);
  382. * console.log(socket.data);
  383. *
  384. * socket.emit("hello");
  385. * socket.join("room1");
  386. * socket.leave("room2");
  387. * socket.disconnect();
  388. * }
  389. */
  390. fetchSockets(): Promise<import("./broadcast-operator").RemoteSocket<EmitEvents, SocketData>[]>;
  391. /**
  392. * Makes the matching socket instances join the specified rooms.
  393. *
  394. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  395. *
  396. * @example
  397. * const myNamespace = io.of("/my-namespace");
  398. *
  399. * // make all socket instances join the "room1" room
  400. * myNamespace.socketsJoin("room1");
  401. *
  402. * // make all socket instances in the "room1" room join the "room2" and "room3" rooms
  403. * myNamespace.in("room1").socketsJoin(["room2", "room3"]);
  404. *
  405. * @param room - a room, or an array of rooms
  406. */
  407. socketsJoin(room: Room | Room[]): void;
  408. /**
  409. * Makes the matching socket instances leave the specified rooms.
  410. *
  411. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  412. *
  413. * @example
  414. * const myNamespace = io.of("/my-namespace");
  415. *
  416. * // make all socket instances leave the "room1" room
  417. * myNamespace.socketsLeave("room1");
  418. *
  419. * // make all socket instances in the "room1" room leave the "room2" and "room3" rooms
  420. * myNamespace.in("room1").socketsLeave(["room2", "room3"]);
  421. *
  422. * @param room - a room, or an array of rooms
  423. */
  424. socketsLeave(room: Room | Room[]): void;
  425. /**
  426. * Makes the matching socket instances disconnect.
  427. *
  428. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  429. *
  430. * @example
  431. * const myNamespace = io.of("/my-namespace");
  432. *
  433. * // make all socket instances disconnect (the connections might be kept alive for other namespaces)
  434. * myNamespace.disconnectSockets();
  435. *
  436. * // make all socket instances in the "room1" room disconnect and close the underlying connections
  437. * myNamespace.in("room1").disconnectSockets(true);
  438. *
  439. * @param close - whether to close the underlying connection
  440. */
  441. disconnectSockets(close?: boolean): void;
  442. }