@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
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
import { Socket } from "socket";
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
ControlledWebSocket,
|
|
5
|
+
flushPromises,
|
|
6
|
+
installControlledWebSocket,
|
|
7
|
+
openWebSocket,
|
|
8
|
+
uninstallControlledWebSocket,
|
|
9
|
+
} from "../../utils/controlled-websocket";
|
|
10
|
+
|
|
11
|
+
type Message = { value: number; seenBy?: string[] };
|
|
12
|
+
|
|
13
|
+
describe("Socket [ Interceptors ]", () => {
|
|
14
|
+
let socket: Socket;
|
|
15
|
+
|
|
16
|
+
const connect = async () => {
|
|
17
|
+
socket = new Socket({ url: "ws://interceptors" });
|
|
18
|
+
return openWebSocket();
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
beforeEach(() => {
|
|
22
|
+
installControlledWebSocket();
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
afterEach(async () => {
|
|
26
|
+
await socket?.disconnect();
|
|
27
|
+
uninstallControlledWebSocket();
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
describe("When intercepting incoming messages with onMessage", () => {
|
|
31
|
+
it("should deliver the data returned by the interceptor to the listeners", async () => {
|
|
32
|
+
const websocket = await connect();
|
|
33
|
+
socket.onMessage<Message>(({ event }) => ({ ...event, value: event.value * 2 }));
|
|
34
|
+
const spy = vi.fn();
|
|
35
|
+
socket
|
|
36
|
+
.createListener<Message>()({ topic: "numbers" })
|
|
37
|
+
.listen(({ data }) => spy(data));
|
|
38
|
+
|
|
39
|
+
websocket.serverEmit("numbers", { value: 21 });
|
|
40
|
+
|
|
41
|
+
expect(spy).toHaveBeenCalledTimes(1);
|
|
42
|
+
expect(spy).toHaveBeenCalledWith({ value: 42 });
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it("should keep the message untouched when the interceptor returns it as is", async () => {
|
|
46
|
+
const websocket = await connect();
|
|
47
|
+
socket.onMessage(({ event }) => event);
|
|
48
|
+
const spy = vi.fn();
|
|
49
|
+
socket
|
|
50
|
+
.createListener<Message>()({ topic: "numbers" })
|
|
51
|
+
.listen(({ data }) => spy(data));
|
|
52
|
+
|
|
53
|
+
websocket.serverEmit("numbers", { value: 1 });
|
|
54
|
+
|
|
55
|
+
expect(spy).toHaveBeenCalledWith({ value: 1 });
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("should keep the original MessageEvent as extra", async () => {
|
|
59
|
+
const websocket = await connect();
|
|
60
|
+
socket.onMessage(({ event }) => event);
|
|
61
|
+
const extras: MessageEvent[] = [];
|
|
62
|
+
socket
|
|
63
|
+
.createListener<Message>()({ topic: "numbers" })
|
|
64
|
+
.listen(({ extra }) => extras.push(extra));
|
|
65
|
+
|
|
66
|
+
websocket.serverEmit("numbers", { value: 1 });
|
|
67
|
+
|
|
68
|
+
expect(extras).toHaveLength(1);
|
|
69
|
+
expect(extras[0]).toBeInstanceOf(MessageEvent);
|
|
70
|
+
expect(JSON.parse(extras[0].data)).toStrictEqual({ topic: "numbers", data: { value: 1 } });
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("should pass the result of every interceptor to the next one", async () => {
|
|
74
|
+
const websocket = await connect();
|
|
75
|
+
socket
|
|
76
|
+
.onMessage<Message>(({ event }) => ({ ...event, seenBy: [...(event.seenBy ?? []), "first"] }))
|
|
77
|
+
.onMessage<Message>(({ event }) => ({ ...event, seenBy: [...(event.seenBy ?? []), "second"] }))
|
|
78
|
+
.onMessage<Message>(({ event }) => ({ ...event, seenBy: [...(event.seenBy ?? []), "third"] }));
|
|
79
|
+
const spy = vi.fn();
|
|
80
|
+
socket
|
|
81
|
+
.createListener<Message>()({ topic: "numbers" })
|
|
82
|
+
.listen(({ data }) => spy(data));
|
|
83
|
+
|
|
84
|
+
websocket.serverEmit("numbers", { value: 1 });
|
|
85
|
+
|
|
86
|
+
expect(spy).toHaveBeenCalledWith({ value: 1, seenBy: ["first", "second", "third"] });
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("should run the interceptors once per message, not once per listener", async () => {
|
|
90
|
+
const websocket = await connect();
|
|
91
|
+
const interceptor = vi.fn(({ event }) => event);
|
|
92
|
+
socket.onMessage(interceptor);
|
|
93
|
+
const listener = socket.createListener<Message>()({ topic: "numbers" });
|
|
94
|
+
listener.listen(() => null);
|
|
95
|
+
listener.listen(() => null);
|
|
96
|
+
listener.listen(() => null);
|
|
97
|
+
|
|
98
|
+
websocket.serverEmit("numbers", { value: 1 });
|
|
99
|
+
|
|
100
|
+
expect(interceptor).toHaveBeenCalledTimes(1);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it("should run the interceptors for messages without any listener", async () => {
|
|
104
|
+
const websocket = await connect();
|
|
105
|
+
const interceptor = vi.fn(({ event }) => event);
|
|
106
|
+
socket.onMessage(interceptor);
|
|
107
|
+
|
|
108
|
+
websocket.serverEmit("nobody-listens", { value: 1 });
|
|
109
|
+
|
|
110
|
+
expect(interceptor).toHaveBeenCalledWith({ event: { value: 1 } });
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("should pass the intercepted data to the socket events", async () => {
|
|
114
|
+
const websocket = await connect();
|
|
115
|
+
socket.onMessage<Message>(({ event }) => ({ ...event, value: event.value + 1 }));
|
|
116
|
+
const global = vi.fn();
|
|
117
|
+
const byTopic = vi.fn();
|
|
118
|
+
const listener = socket.createListener<Message>()({ topic: "numbers" });
|
|
119
|
+
socket.events.onListenerEvent(global);
|
|
120
|
+
socket.events.onListenerEventByTopic(listener, byTopic);
|
|
121
|
+
|
|
122
|
+
websocket.serverEmit("numbers", { value: 1 });
|
|
123
|
+
|
|
124
|
+
expect(global).toHaveBeenCalledWith(expect.objectContaining({ topic: "numbers", data: { value: 2 } }));
|
|
125
|
+
expect(byTopic).toHaveBeenCalledWith(expect.objectContaining({ topic: "numbers", data: { value: 2 } }));
|
|
126
|
+
expect(global.mock.calls[0][0].extra).toBeInstanceOf(MessageEvent);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it.each([
|
|
130
|
+
{ name: "zero", data: 0 },
|
|
131
|
+
{ name: "an empty string", data: "" },
|
|
132
|
+
{ name: "false", data: false },
|
|
133
|
+
{ name: "null", data: null },
|
|
134
|
+
])("should deliver $name passed through an interceptor", async ({ data }) => {
|
|
135
|
+
const websocket = await connect();
|
|
136
|
+
socket.onMessage(({ event }) => event);
|
|
137
|
+
const spy = vi.fn();
|
|
138
|
+
socket
|
|
139
|
+
.createListener<unknown>()({ topic: "falsy" })
|
|
140
|
+
.listen(({ data: received }) => spy(received));
|
|
141
|
+
|
|
142
|
+
websocket.serverEmit("falsy", data);
|
|
143
|
+
|
|
144
|
+
expect(spy).toHaveBeenCalledTimes(1);
|
|
145
|
+
expect(spy).toHaveBeenCalledWith(data);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("should report an interceptor that drops the data and skip the message", async () => {
|
|
149
|
+
const websocket = await connect();
|
|
150
|
+
const errors: Error[] = [];
|
|
151
|
+
socket.onError<Error>(({ error }) => errors.push(error));
|
|
152
|
+
socket.onMessage(() => undefined as any);
|
|
153
|
+
const spy = vi.fn();
|
|
154
|
+
socket.createListener<Message>()({ topic: "numbers" }).listen(spy);
|
|
155
|
+
|
|
156
|
+
websocket.serverEmit("numbers", { value: 1 });
|
|
157
|
+
|
|
158
|
+
expect(spy).not.toHaveBeenCalled();
|
|
159
|
+
expect(errors.map((error) => error.message)).toStrictEqual(["Listener modifier must return data"]);
|
|
160
|
+
expect(socket.adapter.connected).toBeTrue();
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it("should report a throwing interceptor and keep receiving the next messages", async () => {
|
|
164
|
+
const websocket = await connect();
|
|
165
|
+
const errors: Error[] = [];
|
|
166
|
+
socket.onError<Error>(({ error }) => errors.push(error));
|
|
167
|
+
socket.onMessage<Message>(({ event }) => {
|
|
168
|
+
if (event.value === 1) {
|
|
169
|
+
throw new Error("Cannot map the message");
|
|
170
|
+
}
|
|
171
|
+
return event;
|
|
172
|
+
});
|
|
173
|
+
const spy = vi.fn();
|
|
174
|
+
socket
|
|
175
|
+
.createListener<Message>()({ topic: "numbers" })
|
|
176
|
+
.listen(({ data }) => spy(data));
|
|
177
|
+
|
|
178
|
+
websocket.serverEmit("numbers", { value: 1 });
|
|
179
|
+
websocket.serverEmit("numbers", { value: 2 });
|
|
180
|
+
|
|
181
|
+
expect(errors.map((error) => error.message)).toStrictEqual(["Cannot map the message"]);
|
|
182
|
+
expect(spy).toHaveBeenCalledTimes(1);
|
|
183
|
+
expect(spy).toHaveBeenCalledWith({ value: 2 });
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it("should not share interceptors between sockets", async () => {
|
|
187
|
+
const websocket = await connect();
|
|
188
|
+
const other = new Socket({ url: "ws://other" });
|
|
189
|
+
const otherWebsocket = await openWebSocket(2);
|
|
190
|
+
socket.onMessage<Message>(({ event }) => ({ ...event, value: 100 }));
|
|
191
|
+
const spy = vi.fn();
|
|
192
|
+
const otherSpy = vi.fn();
|
|
193
|
+
socket
|
|
194
|
+
.createListener<Message>()({ topic: "numbers" })
|
|
195
|
+
.listen(({ data }) => spy(data));
|
|
196
|
+
other
|
|
197
|
+
.createListener<Message>()({ topic: "numbers" })
|
|
198
|
+
.listen(({ data }) => otherSpy(data));
|
|
199
|
+
|
|
200
|
+
websocket.serverEmit("numbers", { value: 1 });
|
|
201
|
+
otherWebsocket.serverEmit("numbers", { value: 1 });
|
|
202
|
+
|
|
203
|
+
expect(spy).toHaveBeenCalledWith({ value: 100 });
|
|
204
|
+
expect(otherSpy).toHaveBeenCalledWith({ value: 1 });
|
|
205
|
+
await other.disconnect();
|
|
206
|
+
});
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
describe("When intercepting outgoing messages with onSend", () => {
|
|
210
|
+
it("should send the emitter returned by the interceptor", async () => {
|
|
211
|
+
const websocket = await connect();
|
|
212
|
+
socket.onSend(({ emitter }) => emitter.setPayload({ ...emitter.payload, token: "secret" }));
|
|
213
|
+
|
|
214
|
+
socket
|
|
215
|
+
.createEmitter<{ text: string }>()({ topic: "chat" })
|
|
216
|
+
.emit({ payload: { text: "hi" } });
|
|
217
|
+
await flushPromises();
|
|
218
|
+
|
|
219
|
+
expect(websocket.sentMessages).toStrictEqual([{ topic: "chat", data: { text: "hi", token: "secret" } }]);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it("should pass the result of every interceptor to the next one", async () => {
|
|
223
|
+
const websocket = await connect();
|
|
224
|
+
socket
|
|
225
|
+
.onSend(({ emitter }) => emitter.setPayload({ ...emitter.payload, first: true }))
|
|
226
|
+
.onSend(({ emitter }) => emitter.setPayload({ ...emitter.payload, second: true }))
|
|
227
|
+
.onSend(({ emitter }) => emitter.setPayload({ ...emitter.payload, third: true }));
|
|
228
|
+
|
|
229
|
+
socket
|
|
230
|
+
.createEmitter<{ text: string }>()({ topic: "chat" })
|
|
231
|
+
.emit({ payload: { text: "hi" } });
|
|
232
|
+
await flushPromises();
|
|
233
|
+
|
|
234
|
+
expect(websocket.sentMessages).toStrictEqual([
|
|
235
|
+
{ topic: "chat", data: { text: "hi", first: true, second: true, third: true } },
|
|
236
|
+
]);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it("should run the payload mapper before the interceptors", async () => {
|
|
240
|
+
const websocket = await connect();
|
|
241
|
+
const seen = vi.fn();
|
|
242
|
+
socket.onSend(({ emitter }) => {
|
|
243
|
+
seen(emitter.payload);
|
|
244
|
+
return emitter;
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
socket
|
|
248
|
+
.createEmitter<{ text: string }>()({ topic: "chat" })
|
|
249
|
+
.setPayloadMapper((payload) => ({ ...payload, mapped: true }))
|
|
250
|
+
.emit({ payload: { text: "hi" } });
|
|
251
|
+
await flushPromises();
|
|
252
|
+
|
|
253
|
+
expect(seen).toHaveBeenCalledWith({ text: "hi", mapped: true });
|
|
254
|
+
expect(websocket.sentMessages).toStrictEqual([{ topic: "chat", data: { text: "hi", mapped: true } }]);
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
it("should announce the intercepted emitter in the emitter start event", async () => {
|
|
258
|
+
await connect();
|
|
259
|
+
socket.onSend(({ emitter }) => emitter.setPayload({ ...emitter.payload, token: "secret" }));
|
|
260
|
+
const started = vi.fn();
|
|
261
|
+
socket.events.onEmitterStartEvent(({ emitter }) => started(emitter.payload));
|
|
262
|
+
|
|
263
|
+
socket
|
|
264
|
+
.createEmitter<{ text: string }>()({ topic: "chat" })
|
|
265
|
+
.emit({ payload: { text: "hi" } });
|
|
266
|
+
await flushPromises();
|
|
267
|
+
|
|
268
|
+
expect(started).toHaveBeenCalledWith({ text: "hi", token: "secret" });
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
it("should not leak interceptor changes into the emitter template", async () => {
|
|
272
|
+
await connect();
|
|
273
|
+
socket.onSend(({ emitter }) => emitter.setPayload({ ...emitter.payload, token: "secret" }));
|
|
274
|
+
const emitter = socket.createEmitter<{ text: string }>()({ topic: "chat" }).setPayload({ text: "hi" });
|
|
275
|
+
|
|
276
|
+
emitter.emit();
|
|
277
|
+
emitter.emit();
|
|
278
|
+
await flushPromises();
|
|
279
|
+
|
|
280
|
+
expect(emitter.payload).toStrictEqual({ text: "hi" });
|
|
281
|
+
expect(ControlledWebSocket.last.sentMessages).toStrictEqual([
|
|
282
|
+
{ topic: "chat", data: { text: "hi", token: "secret" } },
|
|
283
|
+
{ topic: "chat", data: { text: "hi", token: "secret" } },
|
|
284
|
+
]);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
it("should report a throwing interceptor instead of leaving an unhandled rejection", async () => {
|
|
288
|
+
const websocket = await connect();
|
|
289
|
+
const errors: Error[] = [];
|
|
290
|
+
const emitterErrors = vi.fn();
|
|
291
|
+
socket.onError<Error>(({ error }) => errors.push(error));
|
|
292
|
+
socket.events.onEmitterError(({ error, emitter }) => emitterErrors(error.message, emitter.topic));
|
|
293
|
+
socket.onSend(() => {
|
|
294
|
+
throw new Error("Cannot sign the message");
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
expect(() =>
|
|
298
|
+
socket
|
|
299
|
+
.createEmitter<{ text: string }>()({ topic: "chat" })
|
|
300
|
+
.emit({ payload: { text: "hi" } }),
|
|
301
|
+
).not.toThrow();
|
|
302
|
+
await flushPromises();
|
|
303
|
+
|
|
304
|
+
expect(websocket.sent).toStrictEqual([]);
|
|
305
|
+
expect(errors.map((error) => error.message)).toStrictEqual(["Cannot sign the message"]);
|
|
306
|
+
expect(emitterErrors).toHaveBeenCalledTimes(1);
|
|
307
|
+
expect(emitterErrors).toHaveBeenCalledWith("Cannot sign the message", "chat");
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
it("should report an interceptor that does not return the emitter", async () => {
|
|
311
|
+
const websocket = await connect();
|
|
312
|
+
const errors: Error[] = [];
|
|
313
|
+
socket.onError<Error>(({ error }) => errors.push(error));
|
|
314
|
+
socket.onSend(() => undefined as any);
|
|
315
|
+
|
|
316
|
+
socket
|
|
317
|
+
.createEmitter<{ text: string }>()({ topic: "chat" })
|
|
318
|
+
.emit({ payload: { text: "hi" } });
|
|
319
|
+
await flushPromises();
|
|
320
|
+
|
|
321
|
+
expect(websocket.sent).toStrictEqual([]);
|
|
322
|
+
expect(errors.map((error) => error.message)).toStrictEqual(["Send modifier must return emitter"]);
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
it("should keep sending after an interceptor failure", async () => {
|
|
326
|
+
const websocket = await connect();
|
|
327
|
+
socket.onError(() => null);
|
|
328
|
+
socket.onSend(({ emitter }) => {
|
|
329
|
+
if (emitter.payload.fail) {
|
|
330
|
+
throw new Error("Cannot sign the message");
|
|
331
|
+
}
|
|
332
|
+
return emitter;
|
|
333
|
+
});
|
|
334
|
+
const emitter = socket.createEmitter<{ fail: boolean }>()({ topic: "chat" });
|
|
335
|
+
|
|
336
|
+
emitter.emit({ payload: { fail: true } });
|
|
337
|
+
emitter.emit({ payload: { fail: false } });
|
|
338
|
+
await flushPromises();
|
|
339
|
+
|
|
340
|
+
expect(websocket.sentMessages).toStrictEqual([{ topic: "chat", data: { fail: false } }]);
|
|
341
|
+
});
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
describe("When intercepting connections with onConnect", () => {
|
|
345
|
+
it("should apply the interceptors chained on the constructor to the automatic first connection", async () => {
|
|
346
|
+
socket = new Socket({ url: "ws://interceptors" }).onConnect(({ connection }) => ({
|
|
347
|
+
...connection,
|
|
348
|
+
queryParams: { token: "abc" },
|
|
349
|
+
}));
|
|
350
|
+
|
|
351
|
+
const websocket = await openWebSocket();
|
|
352
|
+
|
|
353
|
+
expect(websocket.url).toBe("ws://interceptors?token=abc");
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
it("should wait for async interceptors before creating the transport", async () => {
|
|
357
|
+
let resolveToken: (token: string) => void = () => null;
|
|
358
|
+
socket = new Socket({ url: "ws://interceptors" }).onConnect(async ({ connection }) => {
|
|
359
|
+
const token = await new Promise<string>((resolve) => {
|
|
360
|
+
resolveToken = resolve;
|
|
361
|
+
});
|
|
362
|
+
return { ...connection, queryParams: { token } };
|
|
363
|
+
});
|
|
364
|
+
await flushPromises();
|
|
365
|
+
|
|
366
|
+
expect(ControlledWebSocket.instances).toHaveLength(0);
|
|
367
|
+
expect(socket.adapter.connecting).toBeTrue();
|
|
368
|
+
|
|
369
|
+
resolveToken("late");
|
|
370
|
+
const websocket = await openWebSocket();
|
|
371
|
+
|
|
372
|
+
expect(websocket.url).toBe("ws://interceptors?token=late");
|
|
373
|
+
expect(socket.adapter.connected).toBeTrue();
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
it("should let an interceptor replace the url and the protocols", async () => {
|
|
377
|
+
socket = new Socket({ url: "ws://interceptors", adapterOptions: { protocols: "v1" } }).onConnect(
|
|
378
|
+
({ connection }) => ({
|
|
379
|
+
...connection,
|
|
380
|
+
url: "ws://other-region",
|
|
381
|
+
adapterOptions: { ...connection.adapterOptions, protocols: ["v2", "auth-token"] },
|
|
382
|
+
}),
|
|
383
|
+
);
|
|
384
|
+
|
|
385
|
+
const websocket = await openWebSocket();
|
|
386
|
+
|
|
387
|
+
expect(websocket.url).toBe("ws://other-region");
|
|
388
|
+
expect(websocket.protocols).toStrictEqual(["v2", "auth-token"]);
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
it("should not change the socket defaults when an interceptor changes the connection", async () => {
|
|
392
|
+
socket = new Socket({ url: "ws://interceptors", queryParams: { a: 1 } }).onConnect(({ connection }) => ({
|
|
393
|
+
...connection,
|
|
394
|
+
url: "ws://other-region",
|
|
395
|
+
queryParams: { b: 2 },
|
|
396
|
+
}));
|
|
397
|
+
|
|
398
|
+
await openWebSocket();
|
|
399
|
+
|
|
400
|
+
expect(socket.url).toBe("ws://interceptors");
|
|
401
|
+
expect(socket.adapter.queryParams).toStrictEqual({ a: 1 });
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
it("should report a throwing interceptor and leave the socket ready for another attempt", async () => {
|
|
405
|
+
let shouldFail = true;
|
|
406
|
+
const errors: Error[] = [];
|
|
407
|
+
socket = new Socket({ url: "ws://interceptors", adapterOptions: { autoConnect: false } })
|
|
408
|
+
.onError<Error>(({ error }) => errors.push(error))
|
|
409
|
+
.onConnect(({ connection }) => {
|
|
410
|
+
if (shouldFail) {
|
|
411
|
+
throw new Error("No token");
|
|
412
|
+
}
|
|
413
|
+
return connection;
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
await socket.connect();
|
|
417
|
+
|
|
418
|
+
expect(errors.map((error) => error.message)).toStrictEqual(["No token"]);
|
|
419
|
+
expect(ControlledWebSocket.instances).toHaveLength(0);
|
|
420
|
+
expect(socket.adapter.connecting).toBeFalse();
|
|
421
|
+
|
|
422
|
+
shouldFail = false;
|
|
423
|
+
const connecting = socket.connect();
|
|
424
|
+
await openWebSocket();
|
|
425
|
+
await connecting;
|
|
426
|
+
|
|
427
|
+
expect(socket.adapter.connected).toBeTrue();
|
|
428
|
+
});
|
|
429
|
+
});
|
|
430
|
+
});
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An EventSource stand-in driven entirely by the test - no network and no timers inside.
|
|
3
|
+
*
|
|
4
|
+
* It follows the browser behaviour that matters for the adapter:
|
|
5
|
+
* - events are dispatched to `addEventListener` listeners (the way a real EventSource does)
|
|
6
|
+
* - a dropped connection fires `error` with `readyState` CONNECTING (the browser retries on its own)
|
|
7
|
+
* - a fatal failure (bad status, wrong content type) fires `error` with `readyState` CLOSED (no retry)
|
|
8
|
+
* - `close()` is silent - it fires no event
|
|
9
|
+
*/
|
|
10
|
+
export class ControlledEventSource extends EventTarget {
|
|
11
|
+
static readonly CONNECTING = 0;
|
|
12
|
+
static readonly OPEN = 1;
|
|
13
|
+
static readonly CLOSED = 2;
|
|
14
|
+
|
|
15
|
+
/** Every instance created since the last `reset()`, in creation order */
|
|
16
|
+
static instances: ControlledEventSource[] = [];
|
|
17
|
+
/** When set, the next constructor call throws it - like an invalid url does in the browser */
|
|
18
|
+
static constructorError: Error | null = null;
|
|
19
|
+
|
|
20
|
+
static reset() {
|
|
21
|
+
ControlledEventSource.instances = [];
|
|
22
|
+
ControlledEventSource.constructorError = null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
static get last(): ControlledEventSource {
|
|
26
|
+
const instance = ControlledEventSource.instances.at(-1);
|
|
27
|
+
if (!instance) {
|
|
28
|
+
throw new Error("[ControlledEventSource] No EventSource was created");
|
|
29
|
+
}
|
|
30
|
+
return instance;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Instances that are connecting or open - "how many live connections does the client hold" */
|
|
34
|
+
static get active(): ControlledEventSource[] {
|
|
35
|
+
return ControlledEventSource.instances.filter((instance) => instance.readyState !== ControlledEventSource.CLOSED);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
readonly CONNECTING = 0;
|
|
39
|
+
readonly OPEN = 1;
|
|
40
|
+
readonly CLOSED = 2;
|
|
41
|
+
|
|
42
|
+
readyState: number = ControlledEventSource.CONNECTING;
|
|
43
|
+
withCredentials: boolean;
|
|
44
|
+
closeCalls = 0;
|
|
45
|
+
|
|
46
|
+
constructor(
|
|
47
|
+
public url: string,
|
|
48
|
+
public eventSourceInit?: EventSourceInit,
|
|
49
|
+
) {
|
|
50
|
+
super();
|
|
51
|
+
if (ControlledEventSource.constructorError) {
|
|
52
|
+
const error = ControlledEventSource.constructorError;
|
|
53
|
+
ControlledEventSource.constructorError = null;
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
this.withCredentials = Boolean(eventSourceInit?.withCredentials);
|
|
57
|
+
ControlledEventSource.instances.push(this);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
close() {
|
|
61
|
+
this.closeCalls += 1;
|
|
62
|
+
this.readyState = ControlledEventSource.CLOSED;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Server side - driven by the test
|
|
66
|
+
|
|
67
|
+
/** The server accepts the stream */
|
|
68
|
+
serverOpen() {
|
|
69
|
+
this.readyState = ControlledEventSource.OPEN;
|
|
70
|
+
this.dispatchEvent(new Event("open"));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The server sends an unnamed message with raw `data` */
|
|
74
|
+
serverSend(data: unknown, init: { lastEventId?: string; origin?: string } = {}) {
|
|
75
|
+
this.dispatchEvent(new MessageEvent("message", { data, ...init }));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The server sends a `{ topic, data }` message in the default wire format */
|
|
79
|
+
serverEmit(topic: string, data: unknown, init: { lastEventId?: string } = {}) {
|
|
80
|
+
this.serverSend(JSON.stringify({ topic, data }), init);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The connection drops - the browser keeps the source and retries on its own */
|
|
84
|
+
serverDrop() {
|
|
85
|
+
this.readyState = ControlledEventSource.CONNECTING;
|
|
86
|
+
this.dispatchEvent(new Event("error"));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The connection fails for good (e.g. HTTP 500) - the browser gives up */
|
|
90
|
+
serverFail() {
|
|
91
|
+
this.readyState = ControlledEventSource.CLOSED;
|
|
92
|
+
this.dispatchEvent(new Event("error"));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
let originalEventSource: typeof EventSource | undefined;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Replaces the global EventSource with {@link ControlledEventSource} for the current test.
|
|
100
|
+
* Call `uninstallControlledEventSource` in `afterEach`.
|
|
101
|
+
*/
|
|
102
|
+
export const installControlledEventSource = () => {
|
|
103
|
+
ControlledEventSource.reset();
|
|
104
|
+
originalEventSource ??= window.EventSource;
|
|
105
|
+
window.EventSource = ControlledEventSource as unknown as typeof EventSource;
|
|
106
|
+
return ControlledEventSource;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
export const uninstallControlledEventSource = () => {
|
|
110
|
+
if (originalEventSource) {
|
|
111
|
+
window.EventSource = originalEventSource;
|
|
112
|
+
originalEventSource = undefined;
|
|
113
|
+
}
|
|
114
|
+
ControlledEventSource.reset();
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
/** Lets pending promise callbacks run - the adapter prepares every connection attempt asynchronously */
|
|
118
|
+
const flush = async (rounds = 10) => {
|
|
119
|
+
for (let i = 0; i < rounds; i += 1) {
|
|
120
|
+
// eslint-disable-next-line no-await-in-loop
|
|
121
|
+
await Promise.resolve();
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Waits (promise ticks only) until the client created its `count`-th EventSource and returns it.
|
|
127
|
+
* Defaults to "the next one that is not created yet".
|
|
128
|
+
*/
|
|
129
|
+
export const waitForEventSource = async (count = ControlledEventSource.instances.length + 1) => {
|
|
130
|
+
for (let i = 0; i < 100 && ControlledEventSource.instances.length < count; i += 1) {
|
|
131
|
+
// eslint-disable-next-line no-await-in-loop
|
|
132
|
+
await Promise.resolve();
|
|
133
|
+
}
|
|
134
|
+
const instance = ControlledEventSource.instances[count - 1];
|
|
135
|
+
if (!instance) {
|
|
136
|
+
throw new Error(
|
|
137
|
+
`[ControlledEventSource] Expected ${count} EventSource(s), got ${ControlledEventSource.instances.length}`,
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
return instance;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
/** Waits for the EventSource of a socket that is connecting right now and accepts it on the server side */
|
|
144
|
+
export const openEventSource = async (count = Math.max(ControlledEventSource.instances.length, 1)) => {
|
|
145
|
+
const instance = await waitForEventSource(count);
|
|
146
|
+
instance.serverOpen();
|
|
147
|
+
await flush();
|
|
148
|
+
return instance;
|
|
149
|
+
};
|