@hyper-fetch/sockets 9.6.1 → 9.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/e2e/e2e.lifecycle.spec.ts +258 -0
- package/__tests__/features/adapter/adapter.connection.spec.ts +27 -6
- package/__tests__/features/adapter/adapter.sse.lifecycle.spec.ts +514 -0
- package/__tests__/features/adapter/adapter.sse.spec.ts +20 -6
- package/__tests__/features/adapter/adapter.websocket.heartbeat.timers.spec.ts +337 -0
- package/__tests__/features/adapter/adapter.websocket.lifecycle.spec.ts +528 -0
- package/__tests__/features/adapter/adapter.websocket.reconnection.spec.ts +669 -0
- package/__tests__/features/delivery/delivery.backpressure.spec.ts +382 -0
- package/__tests__/features/emitter/emitter.sending.spec.ts +493 -0
- package/__tests__/features/emitter/emitter.typescript.spec.ts +153 -0
- package/__tests__/features/listener/listener.dispatch.spec.ts +427 -0
- package/__tests__/features/listener/listener.params.spec.ts +192 -0
- package/__tests__/features/socket/socket.app-manager.spec.ts +24 -2
- package/__tests__/features/socket/socket.interceptors.spec.ts +430 -0
- package/__tests__/utils/controlled-event-source.ts +149 -0
- package/__tests__/utils/controlled-websocket.ts +213 -0
- package/dist/adapter/adapter.bindings.d.ts.map +1 -1
- package/dist/adapter/adapter.d.ts.map +1 -1
- package/dist/adapter-sse/sse-adapter.d.ts.map +1 -1
- package/dist/adapter-websockets/websocket-adapter.d.ts.map +1 -1
- package/dist/emitter/emitter.d.ts.map +1 -1
- package/dist/index.mjs +284 -105
- package/dist/index.mjs.map +1 -1
- package/dist/listener/listener.d.ts +2 -0
- package/dist/listener/listener.d.ts.map +1 -1
- package/dist/socket/socket.d.ts +1 -1
- package/dist/socket/socket.utils.d.ts +11 -3
- package/dist/socket/socket.utils.d.ts.map +1 -1
- package/dist/utils/topic.utils.d.ts +10 -0
- package/dist/utils/topic.utils.d.ts.map +1 -0
- package/package.json +1 -1
- package/src/adapter/adapter.bindings.ts +44 -20
- package/src/adapter/adapter.ts +29 -10
- package/src/adapter-sse/sse-adapter.ts +95 -15
- package/src/adapter-websockets/websocket-adapter.ts +124 -41
- package/src/emitter/emitter.ts +16 -9
- package/src/listener/listener.ts +7 -8
- package/src/socket/socket.utils.ts +20 -6
- package/src/utils/topic.utils.ts +26 -0
|
@@ -49,6 +49,7 @@ export const WebsocketAdapter = (): WebsocketAdapterType =>
|
|
|
49
49
|
onDisconnect,
|
|
50
50
|
onListen,
|
|
51
51
|
onEmit,
|
|
52
|
+
onEmitError,
|
|
52
53
|
onConnected,
|
|
53
54
|
onDisconnected,
|
|
54
55
|
onError,
|
|
@@ -59,15 +60,26 @@ export const WebsocketAdapter = (): WebsocketAdapterType =>
|
|
|
59
60
|
? socket.adapter.adapterOptions?.autoConnect
|
|
60
61
|
: true;
|
|
61
62
|
|
|
63
|
+
// The transport in use. Events of any other instance (replaced or closed on purpose) are ignored.
|
|
62
64
|
let websocket: ReturnType<typeof getWebsocketAdapter> | undefined;
|
|
63
65
|
// Options of the current connection attempt (after onConnect interceptors)
|
|
64
66
|
let options: WebsocketAdapterOptionsType | EmptyTypes = socket.adapter.adapterOptions;
|
|
67
|
+
// Connection attempt in progress - concurrent `connect()` calls join it
|
|
68
|
+
let pendingConnection: Promise<boolean> | undefined;
|
|
65
69
|
|
|
66
70
|
let pingTimer: ReturnType<typeof setTimeout> | undefined;
|
|
67
71
|
let pongTimer: ReturnType<typeof setTimeout> | undefined;
|
|
72
|
+
// Connection timeout while connecting, reconnection delay after the connection was lost
|
|
68
73
|
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
69
74
|
|
|
70
|
-
const
|
|
75
|
+
const scheduleReconnect = () => {
|
|
76
|
+
clearTimeout(timeout);
|
|
77
|
+
timeout = setTimeout(() => {
|
|
78
|
+
reconnect();
|
|
79
|
+
}, socket.reconnectTime);
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const openConnection = async (): Promise<boolean> => {
|
|
71
83
|
const connection = await onConnect();
|
|
72
84
|
if (!connection) {
|
|
73
85
|
return socket.adapter.connected;
|
|
@@ -80,46 +92,50 @@ export const WebsocketAdapter = (): WebsocketAdapterType =>
|
|
|
80
92
|
options = connection.adapterOptions;
|
|
81
93
|
const url = getSocketUrl(connection.url, getQueryParams(connection.queryParams));
|
|
82
94
|
const newWebsocket = createWebsocket(url, options);
|
|
83
|
-
websocket = newWebsocket;
|
|
95
|
+
websocket = newWebsocket ?? undefined;
|
|
84
96
|
|
|
85
97
|
if (!newWebsocket) {
|
|
86
98
|
return false;
|
|
87
99
|
}
|
|
88
100
|
|
|
89
|
-
|
|
90
|
-
newWebsocket.clearListeners();
|
|
101
|
+
const isCurrent = () => websocket === newWebsocket;
|
|
91
102
|
|
|
92
|
-
//
|
|
93
|
-
|
|
94
|
-
reconnect();
|
|
95
|
-
}, socket.reconnectTime);
|
|
103
|
+
// Connection timeout - when the server does not answer in time, start over
|
|
104
|
+
scheduleReconnect();
|
|
96
105
|
|
|
97
106
|
/**
|
|
98
107
|
* Mount listeners
|
|
99
108
|
*/
|
|
100
109
|
|
|
101
110
|
newWebsocket.addEventListener("open", () => {
|
|
111
|
+
if (!isCurrent()) {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
102
114
|
clearTimeout(timeout);
|
|
103
115
|
onConnected();
|
|
104
116
|
onHeartbeat();
|
|
105
117
|
});
|
|
106
118
|
|
|
107
119
|
newWebsocket.addEventListener("close", (event) => {
|
|
120
|
+
if (!isCurrent()) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
108
123
|
clearTimeout(timeout);
|
|
109
|
-
onDisconnected();
|
|
110
124
|
clearTimers();
|
|
125
|
+
onDisconnected();
|
|
111
126
|
const error = getSocketError(event);
|
|
112
127
|
onError({ error: new Error(error) });
|
|
113
128
|
|
|
114
|
-
//
|
|
129
|
+
// The connection was lost or closed by the server with an error - try to get it back
|
|
115
130
|
if (event.code !== 1000) {
|
|
116
|
-
|
|
117
|
-
reconnect();
|
|
118
|
-
}, socket.reconnectTime);
|
|
131
|
+
scheduleReconnect();
|
|
119
132
|
}
|
|
120
133
|
});
|
|
121
134
|
|
|
122
135
|
newWebsocket.addEventListener("message", (newEvent: MessageEvent<SocketData>) => {
|
|
136
|
+
if (!isCurrent()) {
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
123
139
|
// Any frame proves the connection is alive, even the ones ignored by the decoder
|
|
124
140
|
onHeartbeat();
|
|
125
141
|
|
|
@@ -159,40 +175,80 @@ export const WebsocketAdapter = (): WebsocketAdapterType =>
|
|
|
159
175
|
});
|
|
160
176
|
};
|
|
161
177
|
|
|
162
|
-
const
|
|
163
|
-
//
|
|
178
|
+
const connect = (): Promise<boolean> => {
|
|
179
|
+
// Another attempt is already on its way (e.g. the automatic one) - resolve together with it
|
|
180
|
+
if (socket.adapter.connecting && pendingConnection) {
|
|
181
|
+
return pendingConnection;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const connection = openConnection();
|
|
185
|
+
pendingConnection = connection;
|
|
186
|
+
const release = () => {
|
|
187
|
+
if (pendingConnection === connection) {
|
|
188
|
+
pendingConnection = undefined;
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
connection.then(release, release);
|
|
192
|
+
|
|
193
|
+
return connection;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Closes the transport and resets the connection state. From this point the closed transport is detached -
|
|
198
|
+
* whatever it reports later (close code, errors, late frames) does not reach the socket anymore,
|
|
199
|
+
* so closing on purpose is never treated as a lost connection.
|
|
200
|
+
*/
|
|
201
|
+
const closeConnection = async ({ manual }: { manual: boolean }): Promise<boolean> => {
|
|
164
202
|
clearTimeout(timeout);
|
|
203
|
+
clearTimers();
|
|
165
204
|
|
|
166
205
|
const currentWebsocket = websocket;
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
206
|
+
websocket = undefined;
|
|
207
|
+
|
|
208
|
+
const wasActive = socket.adapter.connected || socket.adapter.connecting;
|
|
209
|
+
onDisconnect();
|
|
210
|
+
if (!manual) {
|
|
211
|
+
// Closing the previous transport is a part of reconnecting - only `disconnect()` keeps the socket closed
|
|
212
|
+
socket.adapter.setForceClosed(false);
|
|
213
|
+
}
|
|
214
|
+
if (wasActive) {
|
|
215
|
+
onDisconnected();
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (!currentWebsocket || currentWebsocket.readyState === WebSocket.CLOSED) {
|
|
176
219
|
return true;
|
|
177
220
|
}
|
|
178
221
|
|
|
179
|
-
|
|
222
|
+
return new Promise<boolean>((resolve) => {
|
|
180
223
|
const resolveDisconnected = () => {
|
|
181
224
|
resolve(true);
|
|
182
225
|
currentWebsocket.removeEventListener("close", resolveDisconnected);
|
|
183
226
|
};
|
|
184
227
|
currentWebsocket.addEventListener("close", resolveDisconnected, { disableCleanup: true });
|
|
228
|
+
currentWebsocket.close(1000);
|
|
185
229
|
});
|
|
230
|
+
};
|
|
186
231
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
return promise;
|
|
232
|
+
/** Manual disconnect - the socket stays closed until `connect()` or `reconnect()` is called */
|
|
233
|
+
const disconnect = (): Promise<boolean> => {
|
|
234
|
+
return closeConnection({ manual: true });
|
|
192
235
|
};
|
|
193
236
|
|
|
194
237
|
const reconnect = async () => {
|
|
195
|
-
|
|
238
|
+
// Reconnecting is a request to be connected, also after a manual disconnect
|
|
239
|
+
socket.adapter.setForceClosed(false);
|
|
240
|
+
|
|
241
|
+
await onReconnect({
|
|
242
|
+
disconnect: () => closeConnection({ manual: false }),
|
|
243
|
+
connect: async () => {
|
|
244
|
+
// `disconnect()` called while the previous transport was closing wins over the reconnection
|
|
245
|
+
if (socket.adapter.forceClosed) {
|
|
246
|
+
socket.adapter.setReconnectionAttempts(0);
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
return connect();
|
|
250
|
+
},
|
|
251
|
+
});
|
|
196
252
|
};
|
|
197
253
|
|
|
198
254
|
/** Creates the transport, reporting a failed attempt when the environment or the connection details are invalid */
|
|
@@ -228,19 +284,19 @@ export const WebsocketAdapter = (): WebsocketAdapterType =>
|
|
|
228
284
|
}
|
|
229
285
|
};
|
|
230
286
|
|
|
231
|
-
|
|
287
|
+
/** Encodes and sends a message. Returns the error instead of throwing, so callers decide how to report it. */
|
|
288
|
+
const sendEventMessage = ({ topic, payload }: Pick<EmitterInstance, "topic" | "payload">): Error | null => {
|
|
232
289
|
if (!websocket) {
|
|
233
|
-
return
|
|
290
|
+
return new Error("Cannot send event when connection is not open");
|
|
234
291
|
}
|
|
235
292
|
try {
|
|
236
293
|
const frame = options?.encode
|
|
237
294
|
? options.encode({ topic, payload })
|
|
238
295
|
: JSON.stringify({ topic, data: payload });
|
|
239
296
|
websocket.send(frame);
|
|
240
|
-
return
|
|
297
|
+
return null;
|
|
241
298
|
} catch (error) {
|
|
242
|
-
|
|
243
|
-
return false;
|
|
299
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
244
300
|
}
|
|
245
301
|
};
|
|
246
302
|
|
|
@@ -259,14 +315,34 @@ export const WebsocketAdapter = (): WebsocketAdapterType =>
|
|
|
259
315
|
}
|
|
260
316
|
clearTimers();
|
|
261
317
|
pingTimer = setTimeout(() => {
|
|
262
|
-
sendEventMessage({ topic: "heartbeat", payload: heartbeatMessage });
|
|
318
|
+
const error = sendEventMessage({ topic: "heartbeat", payload: heartbeatMessage });
|
|
319
|
+
if (error) {
|
|
320
|
+
onError({ error });
|
|
321
|
+
}
|
|
263
322
|
pongTimer = setTimeout(() => {
|
|
264
|
-
|
|
265
|
-
websocket?.close();
|
|
323
|
+
onHeartbeatTimeout();
|
|
266
324
|
}, pongTimeout);
|
|
267
325
|
}, pingTimeout);
|
|
268
326
|
};
|
|
269
327
|
|
|
328
|
+
/**
|
|
329
|
+
* The server did not answer the ping - the connection is dead. On a dead connection the closing handshake
|
|
330
|
+
* may take very long (or never finish), so the socket is marked as disconnected right away instead of
|
|
331
|
+
* waiting for the `close` event of the transport.
|
|
332
|
+
*/
|
|
333
|
+
const onHeartbeatTimeout = () => {
|
|
334
|
+
const deadWebsocket = websocket;
|
|
335
|
+
if (!deadWebsocket) {
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
websocket = undefined;
|
|
339
|
+
clearTimers();
|
|
340
|
+
deadWebsocket.close();
|
|
341
|
+
onDisconnected();
|
|
342
|
+
onError({ error: new Error("Heartbeat timeout - the server did not respond to the ping in time") });
|
|
343
|
+
scheduleReconnect();
|
|
344
|
+
};
|
|
345
|
+
|
|
270
346
|
const listen = (
|
|
271
347
|
listener: ListenerOfAdapter<WebsocketAdapterType>,
|
|
272
348
|
callback: ListenerCallbackType<WebsocketAdapterType, any>,
|
|
@@ -280,7 +356,13 @@ export const WebsocketAdapter = (): WebsocketAdapterType =>
|
|
|
280
356
|
return;
|
|
281
357
|
}
|
|
282
358
|
|
|
283
|
-
|
|
359
|
+
const error = sendEventMessage(mappedEmitter);
|
|
360
|
+
if (error) {
|
|
361
|
+
onEmitError({ emitter: mappedEmitter, error });
|
|
362
|
+
onError({ error });
|
|
363
|
+
return false;
|
|
364
|
+
}
|
|
365
|
+
return true;
|
|
284
366
|
};
|
|
285
367
|
|
|
286
368
|
// Initialize
|
|
@@ -289,7 +371,8 @@ export const WebsocketAdapter = (): WebsocketAdapterType =>
|
|
|
289
371
|
}
|
|
290
372
|
|
|
291
373
|
socket.appManager.events.onOnline(() => {
|
|
292
|
-
|
|
374
|
+
// A socket disconnected on purpose stays closed until `connect()` or `reconnect()` is called
|
|
375
|
+
if (autoConnect && !socket.adapter.connected && !socket.adapter.forceClosed) {
|
|
293
376
|
connect();
|
|
294
377
|
}
|
|
295
378
|
});
|
package/src/emitter/emitter.ts
CHANGED
|
@@ -3,6 +3,8 @@ import type { EmitMethodOptionsType, EmitterCloneOptionsType, EmitterOptionsType
|
|
|
3
3
|
import type { SocketInstance } from "socket";
|
|
4
4
|
import type { ExtractAdapterEmitterOptionsType, ExtractSocketAdapterType } from "types";
|
|
5
5
|
|
|
6
|
+
import { mapTopicParams } from "../utils/topic.utils";
|
|
7
|
+
|
|
6
8
|
/**
|
|
7
9
|
* Represents a socket message emitter bound to a specific topic. Use it to send typed payloads
|
|
8
10
|
* over WebSocket or Server-Sent Events connections via the socket adapter.
|
|
@@ -65,14 +67,7 @@ export class Emitter<
|
|
|
65
67
|
}
|
|
66
68
|
|
|
67
69
|
private paramsMapper = (params: ParamsType | null | undefined): Topic => {
|
|
68
|
-
|
|
69
|
-
if (params) {
|
|
70
|
-
Object.entries(params).forEach(([key, value]) => {
|
|
71
|
-
topic = topic.replaceAll(new RegExp(`:${key}`, "g"), String(value));
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
return topic as Topic;
|
|
70
|
+
return mapTopicParams(this.emitterOptions.topic, params) as Topic;
|
|
76
71
|
};
|
|
77
72
|
|
|
78
73
|
/** Create a new emitter instance with optional configuration overrides. */
|
|
@@ -107,6 +102,18 @@ export class Emitter<
|
|
|
107
102
|
const typedOptions = options as EmitMethodOptionsType<Emitter<Payload, Topic, Socket, HasPayload, HasParams>>;
|
|
108
103
|
const instance = this.clone<Payload, HasPayload, HasParams>(typedOptions);
|
|
109
104
|
|
|
110
|
-
|
|
105
|
+
// Adapters may reject asynchronously (e.g. the ones that cannot emit at all). Nobody awaits `emit`,
|
|
106
|
+
// so the failure is reported through the socket instead of becoming an unhandled promise rejection.
|
|
107
|
+
const result = this.socket.adapter.emit(instance) as unknown;
|
|
108
|
+
if (result instanceof Promise) {
|
|
109
|
+
result.catch((error: unknown) => {
|
|
110
|
+
const emitError = error instanceof Error ? error : new Error(String(error));
|
|
111
|
+
this.socket.events.emitEmitterError({ error: emitError, emitter: instance });
|
|
112
|
+
this.socket.unstable_onErrorCallbacks.forEach((callback) => {
|
|
113
|
+
callback({ error: emitError });
|
|
114
|
+
});
|
|
115
|
+
this.socket.events.emitError({ error: emitError });
|
|
116
|
+
});
|
|
117
|
+
}
|
|
111
118
|
};
|
|
112
119
|
}
|
package/src/listener/listener.ts
CHANGED
|
@@ -5,6 +5,8 @@ import type { ListenType, ListenerConfigurationType, ListenerOptionsType } from
|
|
|
5
5
|
import type { SocketInstance } from "socket";
|
|
6
6
|
import type { ExtractAdapterListenerOptionsType, ExtractSocketAdapterType } from "types";
|
|
7
7
|
|
|
8
|
+
import { mapTopicParams } from "../utils/topic.utils";
|
|
9
|
+
|
|
8
10
|
/**
|
|
9
11
|
* Represents a socket message listener bound to a specific topic. Use it to subscribe to
|
|
10
12
|
* typed messages from WebSocket or Server-Sent Events connections via the socket adapter.
|
|
@@ -29,6 +31,8 @@ export class Listener<
|
|
|
29
31
|
delivery?: ListenerDeliveryType<any, ExtractSocketAdapterType<Socket>> = undefined;
|
|
30
32
|
/** Stored with an `any` response for the same covariance reason as `delivery`. */
|
|
31
33
|
readonly listenerOptions: ListenerOptionsType<Topic, ExtractSocketAdapterType<Socket>>;
|
|
34
|
+
/** Topic as it was declared (e.g. `chat/:roomId`) - clones keep it, so params can be set again */
|
|
35
|
+
private topicTemplate: string;
|
|
32
36
|
|
|
33
37
|
constructor(
|
|
34
38
|
readonly socket: Socket,
|
|
@@ -37,6 +41,7 @@ export class Listener<
|
|
|
37
41
|
this.listenerOptions = listenerOptions;
|
|
38
42
|
const { topic, options, delivery, params } = listenerOptions as typeof listenerOptions & { params?: ParamsType };
|
|
39
43
|
this.topic = topic;
|
|
44
|
+
this.topicTemplate = topic;
|
|
40
45
|
this.options = options;
|
|
41
46
|
this.params = params;
|
|
42
47
|
this.delivery = delivery;
|
|
@@ -74,6 +79,7 @@ export class Listener<
|
|
|
74
79
|
...options,
|
|
75
80
|
topic: this.paramsMapper(options?.params || this.params),
|
|
76
81
|
});
|
|
82
|
+
newInstance.topicTemplate = this.topicTemplate;
|
|
77
83
|
|
|
78
84
|
return newInstance;
|
|
79
85
|
}
|
|
@@ -102,13 +108,6 @@ export class Listener<
|
|
|
102
108
|
};
|
|
103
109
|
|
|
104
110
|
private paramsMapper = (params: ParamsType | null | undefined): Topic => {
|
|
105
|
-
|
|
106
|
-
if (params) {
|
|
107
|
-
Object.entries(params).forEach(([key, value]) => {
|
|
108
|
-
topic = topic.replaceAll(new RegExp(`:${key}`, "g"), String(value));
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
return topic as Topic;
|
|
111
|
+
return mapTopicParams(this.topicTemplate, params) as Topic;
|
|
113
112
|
};
|
|
114
113
|
}
|
|
@@ -18,19 +18,33 @@ export const getListenerEventByTopicKey = (event: string) => `${event}_listener_
|
|
|
18
18
|
export const getEmitterStartEventByTopicKey = (event: string) => `${event}_emitter_start_event`;
|
|
19
19
|
export const getEmitterErrorByTopicKey = (event: string) => `${event}_emitter_error`;
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
/**
|
|
22
|
+
* Runs the `onMessage` interceptors over the data of an incoming message. Every interceptor receives the data
|
|
23
|
+
* returned by the previous one - the adapter `extra` is never touched.
|
|
24
|
+
*/
|
|
25
|
+
export const interceptListener = <Extra = any>(
|
|
26
|
+
interceptors: MessageCallbackType<any>[],
|
|
27
|
+
event: { data: any; extra: Extra },
|
|
28
|
+
): { data: any; extra: Extra } => {
|
|
29
|
+
let { data } = event;
|
|
23
30
|
// eslint-disable-next-line no-restricted-syntax
|
|
24
31
|
for (const interceptor of interceptors) {
|
|
25
|
-
|
|
26
|
-
|
|
32
|
+
const newData = interceptor({ event: data });
|
|
33
|
+
// Falsy values like `0`, `""` or `false` are valid message data - only a dropped value is an error
|
|
34
|
+
const isDropped = newData === undefined || (newData === null && data !== null);
|
|
35
|
+
if (isDropped && data !== undefined) {
|
|
27
36
|
throw new Error("Listener modifier must return data");
|
|
28
37
|
}
|
|
38
|
+
data = newData;
|
|
29
39
|
}
|
|
30
40
|
|
|
31
|
-
return
|
|
41
|
+
return { data, extra: event.extra };
|
|
32
42
|
};
|
|
33
43
|
|
|
44
|
+
/**
|
|
45
|
+
* Runs the `onSend` interceptors over an emitter. Every interceptor receives the emitter
|
|
46
|
+
* returned by the previous one.
|
|
47
|
+
*/
|
|
34
48
|
export const interceptEmitter = <EmitterType extends EmitterInstance>(
|
|
35
49
|
interceptors: SendCallbackType<EmitterType>[],
|
|
36
50
|
emitter: EmitterType,
|
|
@@ -38,7 +52,7 @@ export const interceptEmitter = <EmitterType extends EmitterInstance>(
|
|
|
38
52
|
let newEmitter = emitter;
|
|
39
53
|
// eslint-disable-next-line no-restricted-syntax
|
|
40
54
|
for (const interceptor of interceptors) {
|
|
41
|
-
newEmitter = interceptor({ emitter }) as EmitterType;
|
|
55
|
+
newEmitter = interceptor({ emitter: newEmitter }) as EmitterType;
|
|
42
56
|
if (!newEmitter) {
|
|
43
57
|
throw new Error("Send modifier must return emitter");
|
|
44
58
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ParamsType } from "@hyper-fetch/core";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Fills the `:param` segments of a topic template, e.g. `chat/:roomId` + `{ roomId: 1 }` gives `chat/1`.
|
|
5
|
+
*
|
|
6
|
+
* Every `:` segment is replaced once, with the longest matching name. This way `:id` does not eat the beginning
|
|
7
|
+
* of `:idx`, and a value is never parsed again - neither as another param nor as a replacement pattern like `$&`.
|
|
8
|
+
* Segments without a matching param are left untouched.
|
|
9
|
+
*/
|
|
10
|
+
export const mapTopicParams = (topic: string, params: ParamsType | null | undefined): string => {
|
|
11
|
+
const names = params ? Object.keys(params) : [];
|
|
12
|
+
if (!params || names.length === 0) {
|
|
13
|
+
return topic;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const [start, ...segments] = topic.split(":");
|
|
17
|
+
const mapped = segments.map((segment) => {
|
|
18
|
+
const name = names.reduce(
|
|
19
|
+
(longest, current) => (segment.startsWith(current) && current.length > longest.length ? current : longest),
|
|
20
|
+
"",
|
|
21
|
+
);
|
|
22
|
+
return name ? `${params[name]}${segment.slice(name.length)}` : `:${segment}`;
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
return [start, ...mapped].join("");
|
|
26
|
+
};
|