namespace.d.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. import { Socket } from "./socket";
  2. import type { Server } from "./index";
  3. import { EventParams, EventNames, EventsMap, StrictEventEmitter, DefaultEventsMap, DecorateAcknowledgementsWithTimeoutAndMultipleResponses, AllButLast, Last, DecorateAcknowledgementsWithMultipleResponses, DecorateAcknowledgements, RemoveAcknowledgements, EventNamesWithAck, FirstNonErrorArg, EventNamesWithoutAck } 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, RemoveAcknowledgements<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<DecorateAcknowledgementsWithMultipleResponses<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<DecorateAcknowledgementsWithMultipleResponses<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<DecorateAcknowledgementsWithMultipleResponses<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 EventNamesWithoutAck<EmitEvents>>(ev: Ev, ...args: EventParams<EmitEvents, Ev>): boolean;
  207. /**
  208. * Sends a `message` event to all clients.
  209. *
  210. * This method mimics the WebSocket.send() method.
  211. *
  212. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
  213. *
  214. * @example
  215. * const myNamespace = io.of("/my-namespace");
  216. *
  217. * myNamespace.send("hello");
  218. *
  219. * // this is equivalent to
  220. * myNamespace.emit("message", "hello");
  221. *
  222. * @return self
  223. */
  224. send(...args: EventParams<EmitEvents, "message">): this;
  225. /**
  226. * Sends a `message` event to all clients. Sends a `message` event. Alias of {@link send}.
  227. *
  228. * @return self
  229. */
  230. write(...args: EventParams<EmitEvents, "message">): this;
  231. /**
  232. * Sends a message to the other Socket.IO servers of the cluster.
  233. *
  234. * @example
  235. * const myNamespace = io.of("/my-namespace");
  236. *
  237. * myNamespace.serverSideEmit("hello", "world");
  238. *
  239. * myNamespace.on("hello", (arg1) => {
  240. * console.log(arg1); // prints "world"
  241. * });
  242. *
  243. * // acknowledgements (without binary content) are supported too:
  244. * myNamespace.serverSideEmit("ping", (err, responses) => {
  245. * if (err) {
  246. * // some servers did not acknowledge the event in the given delay
  247. * } else {
  248. * console.log(responses); // one response per server (except the current one)
  249. * }
  250. * });
  251. *
  252. * myNamespace.on("ping", (cb) => {
  253. * cb("pong");
  254. * });
  255. *
  256. * @param ev - the event name
  257. * @param args - an array of arguments, which may include an acknowledgement callback at the end
  258. */
  259. serverSideEmit<Ev extends EventNames<ServerSideEvents>>(ev: Ev, ...args: EventParams<DecorateAcknowledgementsWithTimeoutAndMultipleResponses<ServerSideEvents>, Ev>): boolean;
  260. /**
  261. * Sends a message and expect an acknowledgement from the other Socket.IO servers of the cluster.
  262. *
  263. * @example
  264. * const myNamespace = io.of("/my-namespace");
  265. *
  266. * try {
  267. * const responses = await myNamespace.serverSideEmitWithAck("ping");
  268. * console.log(responses); // one response per server (except the current one)
  269. * } catch (e) {
  270. * // some servers did not acknowledge the event in the given delay
  271. * }
  272. *
  273. * @param ev - the event name
  274. * @param args - an array of arguments
  275. *
  276. * @return a Promise that will be fulfilled when all servers have acknowledged the event
  277. */
  278. serverSideEmitWithAck<Ev extends EventNamesWithAck<ServerSideEvents>>(ev: Ev, ...args: AllButLast<EventParams<ServerSideEvents, Ev>>): Promise<FirstNonErrorArg<Last<EventParams<ServerSideEvents, Ev>>>[]>;
  279. /**
  280. * Called when a packet is received from another Socket.IO server
  281. *
  282. * @param args - an array of arguments, which may include an acknowledgement callback at the end
  283. *
  284. * @private
  285. */
  286. _onServerSideEmit(args: [string, ...any[]]): void;
  287. /**
  288. * Gets a list of clients.
  289. *
  290. * @deprecated this method will be removed in the next major release, please use {@link Namespace#serverSideEmit} or
  291. * {@link Namespace#fetchSockets} instead.
  292. */
  293. allSockets(): Promise<Set<SocketId>>;
  294. /**
  295. * Sets the compress flag.
  296. *
  297. * @example
  298. * const myNamespace = io.of("/my-namespace");
  299. *
  300. * myNamespace.compress(false).emit("hello");
  301. *
  302. * @param compress - if `true`, compresses the sending data
  303. * @return self
  304. */
  305. compress(compress: boolean): BroadcastOperator<DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
  306. /**
  307. * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
  308. * receive messages (because of network slowness or other issues, or because they’re connected through long polling
  309. * and is in the middle of a request-response cycle).
  310. *
  311. * @example
  312. * const myNamespace = io.of("/my-namespace");
  313. *
  314. * myNamespace.volatile.emit("hello"); // the clients may or may not receive it
  315. *
  316. * @return self
  317. */
  318. get volatile(): BroadcastOperator<DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
  319. /**
  320. * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
  321. *
  322. * @example
  323. * const myNamespace = io.of("/my-namespace");
  324. *
  325. * // the “foo” event will be broadcast to all connected clients on this node
  326. * myNamespace.local.emit("foo", "bar");
  327. *
  328. * @return a new {@link BroadcastOperator} instance for chaining
  329. */
  330. get local(): BroadcastOperator<DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
  331. /**
  332. * Adds a timeout in milliseconds for the next operation.
  333. *
  334. * @example
  335. * const myNamespace = io.of("/my-namespace");
  336. *
  337. * myNamespace.timeout(1000).emit("some-event", (err, responses) => {
  338. * if (err) {
  339. * // some clients did not acknowledge the event in the given delay
  340. * } else {
  341. * console.log(responses); // one response per client
  342. * }
  343. * });
  344. *
  345. * @param timeout
  346. */
  347. timeout(timeout: number): BroadcastOperator<DecorateAcknowledgements<DecorateAcknowledgementsWithMultipleResponses<EmitEvents>>, SocketData>;
  348. /**
  349. * Returns the matching socket instances.
  350. *
  351. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  352. *
  353. * @example
  354. * const myNamespace = io.of("/my-namespace");
  355. *
  356. * // return all Socket instances
  357. * const sockets = await myNamespace.fetchSockets();
  358. *
  359. * // return all Socket instances in the "room1" room
  360. * const sockets = await myNamespace.in("room1").fetchSockets();
  361. *
  362. * for (const socket of sockets) {
  363. * console.log(socket.id);
  364. * console.log(socket.handshake);
  365. * console.log(socket.rooms);
  366. * console.log(socket.data);
  367. *
  368. * socket.emit("hello");
  369. * socket.join("room1");
  370. * socket.leave("room2");
  371. * socket.disconnect();
  372. * }
  373. */
  374. fetchSockets(): Promise<import("./broadcast-operator").RemoteSocket<EmitEvents, SocketData>[]>;
  375. /**
  376. * Makes the matching socket instances join the specified rooms.
  377. *
  378. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  379. *
  380. * @example
  381. * const myNamespace = io.of("/my-namespace");
  382. *
  383. * // make all socket instances join the "room1" room
  384. * myNamespace.socketsJoin("room1");
  385. *
  386. * // make all socket instances in the "room1" room join the "room2" and "room3" rooms
  387. * myNamespace.in("room1").socketsJoin(["room2", "room3"]);
  388. *
  389. * @param room - a room, or an array of rooms
  390. */
  391. socketsJoin(room: Room | Room[]): void;
  392. /**
  393. * Makes the matching socket instances leave the specified rooms.
  394. *
  395. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  396. *
  397. * @example
  398. * const myNamespace = io.of("/my-namespace");
  399. *
  400. * // make all socket instances leave the "room1" room
  401. * myNamespace.socketsLeave("room1");
  402. *
  403. * // make all socket instances in the "room1" room leave the "room2" and "room3" rooms
  404. * myNamespace.in("room1").socketsLeave(["room2", "room3"]);
  405. *
  406. * @param room - a room, or an array of rooms
  407. */
  408. socketsLeave(room: Room | Room[]): void;
  409. /**
  410. * Makes the matching socket instances disconnect.
  411. *
  412. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  413. *
  414. * @example
  415. * const myNamespace = io.of("/my-namespace");
  416. *
  417. * // make all socket instances disconnect (the connections might be kept alive for other namespaces)
  418. * myNamespace.disconnectSockets();
  419. *
  420. * // make all socket instances in the "room1" room disconnect and close the underlying connections
  421. * myNamespace.in("room1").disconnectSockets(true);
  422. *
  423. * @param close - whether to close the underlying connection
  424. */
  425. disconnectSockets(close?: boolean): void;
  426. }