UNPKG

10 kBTypeScriptView Raw
1import { EventEmitter } from "events";
2/**
3 * An events map is an interface that maps event names to their value, which
4 * represents the type of the `on` listener.
5 */
6export interface EventsMap {
7 [event: string]: any;
8}
9/**
10 * The default events map, used if no EventsMap is given. Using this EventsMap
11 * is equivalent to accepting all event names, and any data.
12 */
13export interface DefaultEventsMap {
14 [event: string]: (...args: any[]) => void;
15}
16/**
17 * Returns a union type containing all the keys of an event map.
18 */
19export type EventNames<Map extends EventsMap> = keyof Map & (string | symbol);
20/**
21 * Returns a union type containing all the keys of an event map that have an acknowledgement callback.
22 *
23 * That also have *some* data coming in.
24 */
25export type EventNamesWithAck<Map extends EventsMap, K extends EventNames<Map> = EventNames<Map>> = IfAny<Last<Parameters<Map[K]>> | Map[K], K, K extends (Last<Parameters<Map[K]>> extends (...args: any[]) => any ? FirstNonErrorArg<Last<Parameters<Map[K]>>> extends void ? never : K : never) ? K : never>;
26/**
27 * Returns a union type containing all the keys of an event map that have an acknowledgement callback.
28 *
29 * That also have *some* data coming in.
30 */
31export type EventNamesWithoutAck<Map extends EventsMap, K extends EventNames<Map> = EventNames<Map>> = IfAny<Last<Parameters<Map[K]>> | Map[K], K, K extends (Parameters<Map[K]> extends never[] ? K : never) ? K : K extends (Last<Parameters<Map[K]>> extends (...args: any[]) => any ? never : K) ? K : never>;
32export type RemoveAcknowledgements<E extends EventsMap> = {
33 [K in EventNamesWithoutAck<E>]: E[K];
34};
35export type EventNamesWithError<Map extends EventsMap, K extends EventNamesWithAck<Map> = EventNamesWithAck<Map>> = IfAny<Last<Parameters<Map[K]>> | Map[K], K, K extends (LooseParameters<Last<Parameters<Map[K]>>>[0] extends Error ? K : never) ? K : never>;
36/** The tuple type representing the parameters of an event listener */
37export type EventParams<Map extends EventsMap, Ev extends EventNames<Map>> = Parameters<Map[Ev]>;
38/**
39 * The event names that are either in ReservedEvents or in UserEvents
40 */
41export type ReservedOrUserEventNames<ReservedEventsMap extends EventsMap, UserEvents extends EventsMap> = EventNames<ReservedEventsMap> | EventNames<UserEvents>;
42/**
43 * Type of a listener of a user event or a reserved event. If `Ev` is in
44 * `ReservedEvents`, the reserved event listener is returned.
45 */
46export type ReservedOrUserListener<ReservedEvents extends EventsMap, UserEvents extends EventsMap, Ev extends ReservedOrUserEventNames<ReservedEvents, UserEvents>> = FallbackToUntypedListener<Ev extends EventNames<ReservedEvents> ? ReservedEvents[Ev] : Ev extends EventNames<UserEvents> ? UserEvents[Ev] : never>;
47/**
48 * Returns an untyped listener type if `T` is `never`; otherwise, returns `T`.
49 *
50 * This is a hack to mitigate https://github.com/socketio/socket.io/issues/3833.
51 * Needed because of https://github.com/microsoft/TypeScript/issues/41778
52 */
53type FallbackToUntypedListener<T> = [T] extends [never] ? (...args: any[]) => void | Promise<void> : T;
54/**
55 * Interface for classes that aren't `EventEmitter`s, but still expose a
56 * strictly typed `emit` method.
57 */
58export interface TypedEventBroadcaster<EmitEvents extends EventsMap> {
59 emit<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: EventParams<EmitEvents, Ev>): boolean;
60}
61/**
62 * Strictly typed version of an `EventEmitter`. A `TypedEventEmitter` takes type
63 * parameters for mappings of event names to event data types, and strictly
64 * types method calls to the `EventEmitter` according to these event maps.
65 *
66 * @typeParam ListenEvents - `EventsMap` of user-defined events that can be
67 * listened to with `on` or `once`
68 * @typeParam EmitEvents - `EventsMap` of user-defined events that can be
69 * emitted with `emit`
70 * @typeParam ReservedEvents - `EventsMap` of reserved events, that can be
71 * emitted by socket.io with `emitReserved`, and can be listened to with
72 * `listen`.
73 */
74export declare abstract class StrictEventEmitter<ListenEvents extends EventsMap, EmitEvents extends EventsMap, ReservedEvents extends EventsMap = {}> extends EventEmitter implements TypedEventBroadcaster<EmitEvents> {
75 /**
76 * Adds the `listener` function as an event listener for `ev`.
77 *
78 * @param ev Name of the event
79 * @param listener Callback function
80 */
81 on<Ev extends ReservedOrUserEventNames<ReservedEvents, ListenEvents>>(ev: Ev, listener: ReservedOrUserListener<ReservedEvents, ListenEvents, Ev>): this;
82 /**
83 * Adds a one-time `listener` function as an event listener for `ev`.
84 *
85 * @param ev Name of the event
86 * @param listener Callback function
87 */
88 once<Ev extends ReservedOrUserEventNames<ReservedEvents, ListenEvents>>(ev: Ev, listener: ReservedOrUserListener<ReservedEvents, ListenEvents, Ev>): this;
89 /**
90 * Emits an event.
91 *
92 * @param ev Name of the event
93 * @param args Values to send to listeners of this event
94 */
95 emit<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: EventParams<EmitEvents, Ev>): boolean;
96 /**
97 * Emits a reserved event.
98 *
99 * This method is `protected`, so that only a class extending
100 * `StrictEventEmitter` can emit its own reserved events.
101 *
102 * @param ev Reserved event name
103 * @param args Arguments to emit along with the event
104 */
105 protected emitReserved<Ev extends EventNames<ReservedEvents>>(ev: Ev, ...args: EventParams<ReservedEvents, Ev>): boolean;
106 /**
107 * Emits an event.
108 *
109 * This method is `protected`, so that only a class extending
110 * `StrictEventEmitter` can get around the strict typing. This is useful for
111 * calling `emit.apply`, which can be called as `emitUntyped.apply`.
112 *
113 * @param ev Event name
114 * @param args Arguments to emit along with the event
115 */
116 protected emitUntyped(ev: string, ...args: any[]): boolean;
117 /**
118 * Returns the listeners listening to an event.
119 *
120 * @param event Event name
121 * @returns Array of listeners subscribed to `event`
122 */
123 listeners<Ev extends ReservedOrUserEventNames<ReservedEvents, ListenEvents>>(event: Ev): ReservedOrUserListener<ReservedEvents, ListenEvents, Ev>[];
124}
125/**
126 * Returns a boolean for whether the given type is `any`.
127 *
128 * @link https://stackoverflow.com/a/49928360/1490091
129 *
130 * Useful in type utilities, such as disallowing `any`s to be passed to a function.
131 *
132 * @author sindresorhus
133 * @link https://github.com/sindresorhus/type-fest
134 */
135type IsAny<T> = 0 extends 1 & T ? true : false;
136/**
137 * An if-else-like type that resolves depending on whether the given type is `any`.
138 *
139 * @see {@link IsAny}
140 *
141 * @author sindresorhus
142 * @link https://github.com/sindresorhus/type-fest
143 */
144type IfAny<T, TypeIfAny = true, TypeIfNotAny = false> = IsAny<T> extends true ? TypeIfAny : TypeIfNotAny;
145/**
146 * Extracts the type of the last element of an array.
147 *
148 * Use-case: Defining the return type of functions that extract the last element of an array, for example [`lodash.last`](https://lodash.com/docs/4.17.15#last).
149 *
150 * @author sindresorhus
151 * @link https://github.com/sindresorhus/type-fest
152 */
153export type Last<ValueType extends readonly unknown[]> = ValueType extends readonly [infer ElementType] ? ElementType : ValueType extends readonly [infer _, ...infer Tail] ? Last<Tail> : ValueType extends ReadonlyArray<infer ElementType> ? ElementType : never;
154export type FirstNonErrorTuple<T extends unknown[]> = T[0] extends Error ? T[1] : T[0];
155export type AllButLast<T extends any[]> = T extends [...infer H, infer L] ? H : any[];
156/**
157 * Like `Parameters<T>`, but doesn't require `T` to be a function ahead of time.
158 */
159type LooseParameters<T> = T extends (...args: infer P) => any ? P : never;
160export type FirstNonErrorArg<T> = T extends (...args: infer Params) => any ? FirstNonErrorTuple<Params> : any;
161type PrependTimeoutError<T extends any[]> = {
162 [K in keyof T]: T[K] extends (...args: infer Params) => infer Result ? Params[0] extends Error ? T[K] : (err: Error, ...args: Params) => Result : T[K];
163};
164export type MultiplyArray<T extends unknown[]> = {
165 [K in keyof T]: T[K][];
166};
167type InferFirstAndPreserveLabel<T extends any[]> = T extends [any, ...infer R] ? T extends [...infer H, ...R] ? H : never : never;
168/**
169 * Utility type to decorate the acknowledgement callbacks multiple values
170 * on the first non error element while removing any elements after
171 */
172type ExpectMultipleResponses<T extends any[]> = {
173 [K in keyof T]: T[K] extends (...args: infer Params) => infer Result ? Params extends [Error] ? (err: Error) => Result : Params extends [Error, ...infer Rest] ? (err: Error, ...args: InferFirstAndPreserveLabel<MultiplyArray<Rest>>) => Result : Params extends [] ? () => Result : (...args: InferFirstAndPreserveLabel<MultiplyArray<Params>>) => Result : T[K];
174};
175/**
176 * Utility type to decorate the acknowledgement callbacks with a timeout error.
177 *
178 * This is needed because the timeout() flag breaks the symmetry between the sender and the receiver:
179 *
180 * @example
181 * interface Events {
182 * "my-event": (val: string) => void;
183 * }
184 *
185 * socket.on("my-event", (cb) => {
186 * cb("123"); // one single argument here
187 * });
188 *
189 * socket.timeout(1000).emit("my-event", (err, val) => {
190 * // two arguments there (the "err" argument is not properly typed)
191 * });
192 *
193 */
194export type DecorateAcknowledgements<E> = {
195 [K in keyof E]: E[K] extends (...args: infer Params) => infer Result ? (...args: PrependTimeoutError<Params>) => Result : E[K];
196};
197export type DecorateAcknowledgementsWithTimeoutAndMultipleResponses<E> = {
198 [K in keyof E]: E[K] extends (...args: infer Params) => infer Result ? (...args: ExpectMultipleResponses<PrependTimeoutError<Params>>) => Result : E[K];
199};
200export type DecorateAcknowledgementsWithMultipleResponses<E> = {
201 [K in keyof E]: E[K] extends (...args: infer Params) => infer Result ? (...args: ExpectMultipleResponses<Params>) => Result : E[K];
202};
203export {};