@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.
Files changed (39) hide show
  1. package/__tests__/e2e/e2e.lifecycle.spec.ts +258 -0
  2. package/__tests__/features/adapter/adapter.connection.spec.ts +27 -6
  3. package/__tests__/features/adapter/adapter.sse.lifecycle.spec.ts +514 -0
  4. package/__tests__/features/adapter/adapter.sse.spec.ts +20 -6
  5. package/__tests__/features/adapter/adapter.websocket.heartbeat.timers.spec.ts +337 -0
  6. package/__tests__/features/adapter/adapter.websocket.lifecycle.spec.ts +528 -0
  7. package/__tests__/features/adapter/adapter.websocket.reconnection.spec.ts +669 -0
  8. package/__tests__/features/delivery/delivery.backpressure.spec.ts +382 -0
  9. package/__tests__/features/emitter/emitter.sending.spec.ts +493 -0
  10. package/__tests__/features/emitter/emitter.typescript.spec.ts +153 -0
  11. package/__tests__/features/listener/listener.dispatch.spec.ts +427 -0
  12. package/__tests__/features/listener/listener.params.spec.ts +192 -0
  13. package/__tests__/features/socket/socket.app-manager.spec.ts +24 -2
  14. package/__tests__/features/socket/socket.interceptors.spec.ts +430 -0
  15. package/__tests__/utils/controlled-event-source.ts +149 -0
  16. package/__tests__/utils/controlled-websocket.ts +213 -0
  17. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  18. package/dist/adapter/adapter.d.ts.map +1 -1
  19. package/dist/adapter-sse/sse-adapter.d.ts.map +1 -1
  20. package/dist/adapter-websockets/websocket-adapter.d.ts.map +1 -1
  21. package/dist/emitter/emitter.d.ts.map +1 -1
  22. package/dist/index.mjs +284 -105
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/listener/listener.d.ts +2 -0
  25. package/dist/listener/listener.d.ts.map +1 -1
  26. package/dist/socket/socket.d.ts +1 -1
  27. package/dist/socket/socket.utils.d.ts +11 -3
  28. package/dist/socket/socket.utils.d.ts.map +1 -1
  29. package/dist/utils/topic.utils.d.ts +10 -0
  30. package/dist/utils/topic.utils.d.ts.map +1 -0
  31. package/package.json +1 -1
  32. package/src/adapter/adapter.bindings.ts +44 -20
  33. package/src/adapter/adapter.ts +29 -10
  34. package/src/adapter-sse/sse-adapter.ts +95 -15
  35. package/src/adapter-websockets/websocket-adapter.ts +124 -41
  36. package/src/emitter/emitter.ts +16 -9
  37. package/src/listener/listener.ts +7 -8
  38. package/src/socket/socket.utils.ts +20 -6
  39. package/src/utils/topic.utils.ts +26 -0
@@ -22,6 +22,8 @@ export declare class Listener<Response, Topic extends string, Socket extends Soc
22
22
  delivery?: ListenerDeliveryType<any, ExtractSocketAdapterType<Socket>>;
23
23
  /** Stored with an `any` response for the same covariance reason as `delivery`. */
24
24
  readonly listenerOptions: ListenerOptionsType<Topic, ExtractSocketAdapterType<Socket>>;
25
+ /** Topic as it was declared (e.g. `chat/:roomId`) - clones keep it, so params can be set again */
26
+ private topicTemplate;
25
27
  constructor(socket: Socket, listenerOptions: ListenerOptionsType<Topic, ExtractSocketAdapterType<Socket>, Response>);
26
28
  /** Set adapter-specific listener options. */
27
29
  setOptions(options: ExtractAdapterListenerOptionsType<ExtractSocketAdapterType<Socket>>): Listener<Response, Topic, Socket, HasParams, Delivered>;
@@ -1 +1 @@
1
- {"version":3,"file":"listener.d.ts","sourceRoot":"","sources":["../../src/listener/listener.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,KAAK,EAA+B,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAExG,OAAO,KAAK,EAAE,UAAU,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAC3F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,KAAK,EAAE,iCAAiC,EAAE,wBAAwB,EAAE,MAAM,OAAO,CAAC;AAEzF;;;;;;GAMG;AACH,qBAAa,QAAQ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K,EAAE,wBAAwB,CAAC,MAAM,CAAC,EAAE,QAAQ,CAAC;IAczF,6CAA6C;IAC7C,UAAU,CAAC,OAAO,EAAE,iCAAiC,CAAC,wBAAwB,CAAC,MAAM,CAAC,CAAC;IAIvF,sEAAsE;IACtE,SAAS,CAAC,MAAM,EAAE,gBAAgB,CAAC,KAAK,CAAC;IAIzC;;;OAGG;IACH,WAAW,CAAC,WAAW,SAAS,oBAAoB,CAAC,QAAQ,EAAE,wBAAwB,CAAC,MAAM,CAAC,CAAC,GAAG,SAAS,EAC1G,QAAQ,EAAE,WAAW;IAKvB,4EAA4E;IAC5E,KAAK,CAAC,YAAY,SAAS,IAAI,GAAG,KAAK,GAAG,SAAS,EAAE,YAAY,GAAG,SAAS,EAC3E,OAAO,CAAC,EAAE,yBAAyB,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC;IAYvF,+FAA+F;IAC/F,MAAM,EAAE,UAAU,CAAC,QAAQ,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,CAAC,EAAE,MAAM,CAAC,CAoBjF;IAEF,OAAO,CAAC,YAAY,CAElB;CACH"}
@@ -206,7 +206,7 @@ export declare class Socket<Adapter extends SocketAdapterInstance = WebsocketAda
206
206
  extra: ExtractAdapterExtraType<Adapter>;
207
207
  }) => {
208
208
  data: any;
209
- extra: any;
209
+ extra: ExtractAdapterExtraType<Adapter>;
210
210
  };
211
211
  /**
212
212
  * ********************
@@ -15,13 +15,21 @@ export declare const getListenerRemoveByTopicKey: (event: string) => string;
15
15
  export declare const getListenerEventByTopicKey: (event: string) => string;
16
16
  export declare const getEmitterStartEventByTopicKey: (event: string) => string;
17
17
  export declare const getEmitterErrorByTopicKey: (event: string) => string;
18
- export declare const interceptListener: (interceptors: MessageCallbackType<any>[], event: {
18
+ /**
19
+ * Runs the `onMessage` interceptors over the data of an incoming message. Every interceptor receives the data
20
+ * returned by the previous one - the adapter `extra` is never touched.
21
+ */
22
+ export declare const interceptListener: <Extra = any>(interceptors: MessageCallbackType<any>[], event: {
19
23
  data: any;
20
- extra: any;
24
+ extra: Extra;
21
25
  }) => {
22
26
  data: any;
23
- extra: any;
27
+ extra: Extra;
24
28
  };
29
+ /**
30
+ * Runs the `onSend` interceptors over an emitter. Every interceptor receives the emitter
31
+ * returned by the previous one.
32
+ */
25
33
  export declare const interceptEmitter: <EmitterType extends EmitterInstance>(interceptors: SendCallbackType<EmitterType>[], emitter: EmitterType) => EmitterType;
26
34
  export declare const interceptConnection: <Adapter extends SocketAdapterInstance>(interceptors: ConnectCallbackType<Adapter>[], data: {
27
35
  connection: SocketConnectionType<Adapter>;
@@ -1 +1 @@
1
- {"version":3,"file":"socket.utils.d.ts","sourceRoot":"","sources":["../../src/socket/socket.utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAEvH,eAAO,MAAM,WAAW,cAAuB,CAAC;AAChD,eAAO,MAAM,UAAU,cAAsB,CAAC;AAC9C,eAAO,MAAM,WAAW,cAAuB,CAAC;AAChD,eAAO,MAAM,gBAAgB,cAA4B,CAAC;AAC1D,eAAO,MAAM,kBAAkB,cAA8B,CAAC;AAC9D,eAAO,MAAM,wBAAwB,cAAmC,CAAC;AACzE,eAAO,MAAM,mBAAmB,cAAyB,CAAC;AAC1D,eAAO,MAAM,oBAAoB,cAA0B,CAAC;AAC5D,eAAO,MAAM,uBAAuB,cAA8B,CAAC;AACnE,eAAO,MAAM,kBAAkB,cAAwB,CAAC;AACxD,eAAO,MAAM,2BAA2B,GAAI,OAAO,MAAM,WAA+B,CAAC;AACzF,eAAO,MAAM,0BAA0B,GA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wB,cAAmC,CAAC;AACzE,eAAO,MAAM,mBAAmB,cAAyB,CAAC;AAC1D,eAAO,MAAM,oBAAoB,cAA0B,CAAC;AAC5D,eAAO,MAAM,uBAAuB,cAA8B,CAAC;AACnE,eAAO,MAAM,kBAAkB,cAAwB,CAAC;AACxD,eAAO,MAAM,2BAA2B,GAAI,OAAO,MAAM,WAA+B,CAAC;AACzF,eAAO,MAAM,0BAA0B,GAAI,OAAO,MAAM,WAA8B,CAAC;AACvF,eAAO,MAAM,8BAA8B,GAAI,OAAO,MAAM,WAAmC,CAAC;AAChG,eAAO,MAAM,yBAAyB,GAAI,OAAO,MAAM,WAA6B,CAAC;AAErF;;;GAGG;AACH,eAAO,MAAM,iBAAiB,GAAI,KAAK,GAAG,GAAG,EAC3C,cAAc,mBAAmB,CAAC,GAAG,CAAC,EAAE,EACxC,OAAO;IAAE,IAAI,EAAE,GAAG,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAAE,KACjC;IAAE,IAAI,EAAE,GAAG,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAc3B,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,GAAI,WAAW,SAAS,eAAe,EAClE,cAAc,gBAAgB,CAAC,WAAW,CAAC,EAAE,EAC7C,SAAS,WAAW,gBAWrB,CAAC;AAEF,eAAO,MAAM,mBAAmB,GAAU,OAAO,SAAS,qBAAqB,EAC7E,cAAc,mBAAmB,CAAC,OAAO,CAAC,EAAE,EAC5C,MAAM;IAAE,UAAU,EAAE,oBAAoB,CAAC,OAAO,CAAC,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,KACnE,OAAO,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAYvC,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { ParamsType } from '@hyper-fetch/core';
2
+ /**
3
+ * Fills the `:param` segments of a topic template, e.g. `chat/:roomId` + `{ roomId: 1 }` gives `chat/1`.
4
+ *
5
+ * Every `:` segment is replaced once, with the longest matching name. This way `:id` does not eat the beginning
6
+ * of `:idx`, and a value is never parsed again - neither as another param nor as a replacement pattern like `$&`.
7
+ * Segments without a matching param are left untouched.
8
+ */
9
+ export declare const mapTopicParams: (topic: string, params: ParamsType | null | undefined) => string;
10
+ //# sourceMappingURL=topic.utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"topic.utils.d.ts","sourceRoot":"","sources":["../../src/utils/topic.utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,MAAM,EAAE,QAAQ,UAAU,GAAG,IAAI,GAAG,SAAS,KAAG,MAgBrF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyper-fetch/sockets",
3
- "version": "9.6.1",
3
+ "version": "9.6.2",
4
4
  "description": "Sockets connection for hyper-fetch",
5
5
  "author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
6
6
  "homepage": "https://hyperfetch.bettertyped.com/",
@@ -64,9 +64,10 @@ export const getAdapterBindings = <T extends SocketAdapterInstance>(socket: Sock
64
64
  connectionId += 1;
65
65
  const currentConnectionId = connectionId;
66
66
 
67
+ // The attempts counter is kept on purpose - it is reset only by a successful connection (onConnected)
68
+ // or a disconnect, so attempts that never open (e.g. a hanging handshake) still count towards the limit
67
69
  socket.adapter.setForceClosed(false);
68
70
  socket.adapter.setConnecting(true);
69
- socket.adapter.setReconnectionAttempts(0);
70
71
  socket.events.emitConnecting({ connecting: true });
71
72
 
72
73
  const defaults: SocketConnectionType<T> = {
@@ -133,10 +134,6 @@ export const getAdapterBindings = <T extends SocketAdapterInstance>(socket: Sock
133
134
  extra: { reconnectionAttempts: nextAttempts },
134
135
  });
135
136
  await connect();
136
- // Restore only if the connection didn't succeed — onConnected resets to 0 on success
137
- if (!adapter.connected) {
138
- socket.adapter.setReconnectionAttempts(nextAttempts);
139
- }
140
137
  return true;
141
138
  }
142
139
 
@@ -175,25 +172,40 @@ export const getAdapterBindings = <T extends SocketAdapterInstance>(socket: Sock
175
172
 
176
173
  // Emitters
177
174
 
175
+ const onEmitError = <ErrorType extends Error>({ emitter, error }: { emitter: EmitterInstance; error: ErrorType }) => {
176
+ socket.events.emitEmitterError({ error, emitter });
177
+ };
178
+
179
+ /**
180
+ * Prepares an emitter for sending - maps the payload and runs the `onSend` interceptors.
181
+ * Returns `null` when the message cannot be sent; the reason is reported with the emitter error event
182
+ * (and to the `onError` callbacks when the payload mapper or an interceptor failed), it never rejects.
183
+ */
178
184
  const onEmit = async ({ emitter }: { emitter: EmitterInstance }): Promise<EmitterInstance | null> => {
179
185
  if (adapter.connecting || !adapter.connected) {
180
- logger.error({ title: "Cannot emit event when connection is not open", type: "system", extra: {} });
186
+ const error = new Error("Cannot emit event when connection is not open");
187
+ logger.error({ title: error.message, type: "system", extra: {} });
188
+ onEmitError({ emitter, error });
181
189
  return null;
182
190
  }
183
191
 
184
- // eslint-disable-next-line no-param-reassign
185
- emitter.payload = emitter.unstable_payloadMapper
186
- ? emitter.unstable_payloadMapper(emitter.payload)
187
- : emitter.payload;
192
+ try {
193
+ // eslint-disable-next-line no-param-reassign
194
+ emitter.payload = emitter.unstable_payloadMapper
195
+ ? await emitter.unstable_payloadMapper(emitter.payload)
196
+ : emitter.payload;
188
197
 
189
- const emitterInstance = await socket.unstable__modifySend(emitter);
190
- socket.events.emitEmitterStartEvent({ emitter: emitterInstance });
198
+ const emitterInstance = await socket.unstable__modifySend(emitter);
199
+ socket.events.emitEmitterStartEvent({ emitter: emitterInstance });
191
200
 
192
- return emitterInstance;
193
- };
194
-
195
- const onEmitError = <ErrorType extends Error>({ emitter, error }: { emitter: EmitterInstance; error: ErrorType }) => {
196
- socket.events.emitEmitterError({ error, emitter });
201
+ return emitterInstance;
202
+ } catch (error) {
203
+ const emitError = error instanceof Error ? error : new Error(String(error));
204
+ logger.error({ title: "Cannot prepare event to emit", type: "system", extra: { error: emitError } });
205
+ onEmitError({ emitter, error: emitError });
206
+ onError({ error: emitError });
207
+ return null;
208
+ }
197
209
  };
198
210
 
199
211
  // Lifecycle
@@ -224,9 +236,21 @@ export const getAdapterBindings = <T extends SocketAdapterInstance>(socket: Sock
224
236
  const onEvent = ({ topic, data, extra }: { topic: string; data: any; extra: ExtractAdapterExtraType<T> }) => {
225
237
  logger.info({ title: "New event message", type: "system", extra: { topic, data, extra } });
226
238
 
227
- const { data: modifiedData, extra: modifiedExtra } = socket.unstable__modifyResponse({ data, extra });
228
- socket.adapter.triggerListeners({ topic, data: modifiedData, extra: modifiedExtra });
229
- socket.events.emitListenerEvent({ topic, data: modifiedData, extra: modifiedExtra });
239
+ let message: { data: any; extra: ExtractAdapterExtraType<T> };
240
+ try {
241
+ message = socket.unstable__modifyResponse({ data, extra });
242
+ } catch (error) {
243
+ // A failing `onMessage` interceptor must not break the transport - skip the message and report it
244
+ onError({ error: error instanceof Error ? error : new Error(String(error)) });
245
+ return;
246
+ }
247
+
248
+ try {
249
+ socket.adapter.triggerListeners({ topic, data: message.data, extra: message.extra });
250
+ } finally {
251
+ // Devtools and global subscriptions receive the message even when a listener callback throws
252
+ socket.events.emitListenerEvent({ topic, data: message.data, extra: message.extra });
253
+ }
230
254
  };
231
255
 
232
256
  /** Maps query params to the format required by the adapter (defaults to the adapter's stored query params) */
@@ -169,14 +169,15 @@ export class SocketAdapter<
169
169
  >;
170
170
  }): boolean => {
171
171
  const listenerGroup = this.listeners.get(topic);
172
- if (listenerGroup) {
173
- const unmount = listenerGroup.get(callback);
174
- this.socket.events.emitListenerRemoveEvent({ topic });
175
- listenerGroup.delete(callback);
176
- unmount?.();
177
- return true;
172
+ // Removing a callback that is not registered (anymore) is a no-op - the remove event fires once per listener
173
+ if (!listenerGroup?.has(callback)) {
174
+ return false;
178
175
  }
179
- return false;
176
+ const unmount = listenerGroup.get(callback);
177
+ listenerGroup.delete(callback);
178
+ this.socket.events.emitListenerRemoveEvent({ topic });
179
+ unmount?.();
180
+ return true;
180
181
  };
181
182
 
182
183
  public triggerListeners = ({
@@ -191,10 +192,28 @@ export class SocketAdapter<
191
192
  >;
192
193
  }) => {
193
194
  const listenerGroup = this.listeners.get(topic);
194
- if (listenerGroup) {
195
- listenerGroup.forEach((_, action) => {
195
+ if (!listenerGroup?.size) {
196
+ return;
197
+ }
198
+
199
+ // Dispatch to the listeners registered when the message arrived: the ones added by a callback wait for the
200
+ // next message, the ones removed by a callback are skipped.
201
+ const callbacks = [...listenerGroup.keys()];
202
+ const errors: unknown[] = [];
203
+ callbacks.forEach((action) => {
204
+ if (!listenerGroup.has(action)) {
205
+ return;
206
+ }
207
+ try {
196
208
  action({ data, extra: extra as ExtractAdapterExtraType<this> });
197
- });
209
+ } catch (error) {
210
+ // One failing callback must not starve the other listeners of the topic
211
+ errors.push(error);
212
+ }
213
+ });
214
+
215
+ if (errors.length > 0) {
216
+ throw errors[0];
198
217
  }
199
218
  };
200
219
 
@@ -53,8 +53,11 @@ export const ServerSentEventsAdapter = (): ServerSentEventsAdapterType =>
53
53
  onError,
54
54
  onEvent,
55
55
  }) => {
56
+ // The transport in use. Events of any other instance (replaced or closed on purpose) are ignored.
56
57
  let sse: ReturnType<typeof getServerSentEventsAdapter> | undefined;
57
- // Reconnects when the current attempt does not open in time, `disconnect` cancels it
58
+ // Connection attempt in progress - concurrent `connect()` calls join it
59
+ let pendingConnection: Promise<boolean> | undefined;
60
+ // Connection timeout while connecting, reconnection delay after the connection was lost
58
61
  let timeout: ReturnType<typeof setTimeout> | undefined;
59
62
 
60
63
  const autoConnect =
@@ -79,7 +82,14 @@ export const ServerSentEventsAdapter = (): ServerSentEventsAdapterType =>
79
82
  }
80
83
  };
81
84
 
82
- const connect = async (): Promise<boolean> => {
85
+ const scheduleReconnect = () => {
86
+ clearTimeout(timeout);
87
+ timeout = setTimeout(() => {
88
+ reconnect();
89
+ }, socket.reconnectTime);
90
+ };
91
+
92
+ const openConnection = async (): Promise<boolean> => {
83
93
  const connection = await onConnect();
84
94
  if (!connection) {
85
95
  return socket.adapter.connected;
@@ -91,34 +101,56 @@ export const ServerSentEventsAdapter = (): ServerSentEventsAdapterType =>
91
101
 
92
102
  const url = getSocketUrl(connection.url, getQueryParams(connection.queryParams));
93
103
  const eventSource = createEventSource(url, connection.adapterOptions);
94
- sse = eventSource;
104
+ sse = eventSource ?? undefined;
95
105
 
96
106
  if (!eventSource) {
97
107
  return false;
98
108
  }
99
109
 
100
- // Reconnection timeout
101
- timeout = setTimeout(() => {
102
- reconnect();
103
- }, socket.reconnectTime);
110
+ const isCurrent = () => sse === eventSource;
111
+
112
+ // Connection timeout - when the server does not answer in time, start over
113
+ scheduleReconnect();
104
114
 
105
115
  /**
106
116
  * Mount listeners
107
117
  */
108
118
 
109
119
  eventSource.addEventListener("open", () => {
120
+ if (!isCurrent()) {
121
+ return;
122
+ }
110
123
  clearTimeout(timeout);
111
124
  onConnected();
112
125
  });
113
126
 
114
127
  eventSource.addEventListener("error", (event) => {
128
+ if (!isCurrent()) {
129
+ return;
130
+ }
115
131
  const error = getSocketError(event);
116
132
 
117
133
  onError({ error: new Error(error) });
134
+
135
+ // An open stream broke. The browser either retries on its own (CONNECTING) or gives up (CLOSED) -
136
+ // in both cases the socket is not connected anymore. The timeout takes over when the stream
137
+ // does not come back in time, the same way it guards the initial connection.
138
+ const isLost = adapter.connected && eventSource.readyState !== EventSource.OPEN;
139
+ if (isLost) {
140
+ onDisconnected();
141
+ if (eventSource.readyState === EventSource.CONNECTING) {
142
+ adapter.setConnecting(true);
143
+ socket.events.emitConnecting({ connecting: true });
144
+ }
145
+ scheduleReconnect();
146
+ }
118
147
  });
119
148
 
120
149
  const { decode } = connection.adapterOptions || {};
121
150
  eventSource.addEventListener("message", (newEvent: MessageEvent<SocketData>) => {
151
+ if (!isCurrent()) {
152
+ return;
153
+ }
122
154
  const message = decodeMessage(newEvent, decode);
123
155
  if (message) {
124
156
  onEvent({ topic: message.topic, data: message.data, extra: newEvent });
@@ -150,28 +182,73 @@ export const ServerSentEventsAdapter = (): ServerSentEventsAdapterType =>
150
182
  });
151
183
  };
152
184
 
153
- const disconnect = async (): Promise<boolean> => {
154
- // Manual disconnect cancels a pending attempt's automatic reconnect
185
+ const connect = (): Promise<boolean> => {
186
+ // Another attempt is already on its way (e.g. the automatic one) - resolve together with it
187
+ if (adapter.connecting && pendingConnection) {
188
+ return pendingConnection;
189
+ }
190
+
191
+ const connection = openConnection();
192
+ pendingConnection = connection;
193
+ const release = () => {
194
+ if (pendingConnection === connection) {
195
+ pendingConnection = undefined;
196
+ }
197
+ };
198
+ connection.then(release, release);
199
+
200
+ return connection;
201
+ };
202
+
203
+ /**
204
+ * Closes the transport and resets the connection state. From this point the closed transport is detached -
205
+ * whatever it reports later does not reach the socket anymore.
206
+ */
207
+ const closeConnection = async ({ manual }: { manual: boolean }): Promise<boolean> => {
155
208
  clearTimeout(timeout);
156
209
 
157
210
  const currentSse = sse;
211
+ sse = undefined;
158
212
  const hasTransport = currentSse && currentSse.readyState !== EventSource.CLOSED;
159
213
 
160
214
  // When there is nothing to close, only a connection attempt may still be preparing (onConnect) - cancel it
161
- const wasConnecting = adapter.connecting;
215
+ const wasActive = adapter.connected || adapter.connecting;
162
216
  onDisconnect();
217
+ if (!manual) {
218
+ // Closing the previous transport is a part of reconnecting - only `disconnect()` keeps the socket closed
219
+ adapter.setForceClosed(false);
220
+ }
163
221
  if (hasTransport) {
222
+ currentSse.clearListeners();
164
223
  currentSse.close();
165
224
  }
166
- if (hasTransport || wasConnecting) {
225
+ if (hasTransport || wasActive) {
167
226
  onDisconnected();
168
227
  }
169
228
 
170
229
  return true;
171
230
  };
172
231
 
173
- const reconnect = () => {
174
- onReconnect({ disconnect, connect });
232
+ /** Manual disconnect - the socket stays closed until `connect()` or `reconnect()` is called */
233
+ const disconnect = (): Promise<boolean> => {
234
+ return closeConnection({ manual: true });
235
+ };
236
+
237
+ const reconnect = async () => {
238
+ // Reconnecting is a request to be connected, also after a manual disconnect
239
+ adapter.setForceClosed(false);
240
+
241
+ await onReconnect({
242
+ disconnect: () => closeConnection({ manual: false }),
243
+ connect: async () => {
244
+ // `disconnect()` called in the meantime wins over the reconnection
245
+ if (adapter.forceClosed) {
246
+ adapter.setReconnectionAttempts(0);
247
+ return false;
248
+ }
249
+ return connect();
250
+ },
251
+ });
175
252
  };
176
253
 
177
254
  /** Creates the transport, reporting a failed attempt when the environment or the connection details are invalid */
@@ -195,7 +272,9 @@ export const ServerSentEventsAdapter = (): ServerSentEventsAdapterType =>
195
272
  return onListen({ listener, callback });
196
273
  };
197
274
 
198
- const emit = async () => {
275
+ // Server-Sent Events are receive-only. Throwing synchronously makes `emitter.emit()` fail right at the
276
+ // call site instead of leaving a rejected promise nobody awaits.
277
+ const emit = () => {
199
278
  throw new Error("Cannot emit events in SSE adapter");
200
279
  };
201
280
 
@@ -205,7 +284,8 @@ export const ServerSentEventsAdapter = (): ServerSentEventsAdapterType =>
205
284
  }
206
285
 
207
286
  socket.appManager.events.onOnline(() => {
208
- if (autoConnect && !adapter.connected) {
287
+ // A socket disconnected on purpose stays closed until `connect()` or `reconnect()` is called
288
+ if (autoConnect && !adapter.connected && !adapter.forceClosed) {
209
289
  connect();
210
290
  }
211
291
  });