react-native-nitro-sse 3.0.0 → 3.2.0-beta.1
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/NitroSse.podspec +0 -1
- package/README.md +16 -5
- package/android/build.gradle +0 -1
- package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +33 -10
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +366 -78
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +417 -94
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +20 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +9 -0
- package/ios/NitroSse.swift +302 -49
- package/ios/SseConnectionHandler.swift +647 -97
- package/ios/SseEventBuffer.swift +19 -1
- package/ios/SseReconnectStrategy.swift +26 -7
- package/lib/module/FetchSseDriver.js +845 -0
- package/lib/module/MockSseEngine.js +72 -3
- package/lib/module/NitroSseClient.js +43 -18
- package/lib/module/SseDriver.js +31 -15
- package/lib/module/SseEventParser.js +238 -0
- package/lib/module/createNitroSse.js +12 -5
- package/lib/module/createNitroSse.native.js +24 -0
- package/lib/module/createNitroSse.web.js +13 -0
- package/lib/module/index.js +2 -1
- package/lib/module/index.native.js +8 -0
- package/lib/module/index.web.js +9 -0
- package/lib/module/useNitroSse.js +1 -1
- package/lib/typescript/src/FetchSseDriver.d.ts +92 -0
- package/lib/typescript/src/MockSseEngine.d.ts +16 -0
- package/lib/typescript/src/NitroSseClient.d.ts +4 -1
- package/lib/typescript/src/SseDriver.d.ts +8 -4
- package/lib/typescript/src/SseEventParser.d.ts +42 -0
- package/lib/typescript/src/SseInterface.d.ts +46 -3
- package/lib/typescript/src/createNitroSse.d.ts +2 -2
- package/lib/typescript/src/createNitroSse.native.d.ts +9 -0
- package/lib/typescript/src/createNitroSse.web.d.ts +8 -0
- package/lib/typescript/src/index.d.ts +1 -0
- package/lib/typescript/src/index.native.d.ts +6 -0
- package/lib/typescript/src/index.web.d.ts +7 -0
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +4 -0
- package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +67 -0
- package/nitrogen/generated/android/c++/JSseStats.hpp +87 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +26 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +108 -3
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +18 -0
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +3 -0
- package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +3 -0
- package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +52 -0
- package/nitrogen/generated/ios/swift/SseStats.swift +217 -2
- package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +88 -0
- package/nitrogen/generated/shared/c++/SseStats.hpp +88 -2
- package/package.json +13 -2
|
@@ -0,0 +1,845 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
import { SseEventParser } from "./SseEventParser.js";
|
|
4
|
+
import { MockSseEngine } from "./MockSseEngine.js";
|
|
5
|
+
function getUtf8ByteCount(str) {
|
|
6
|
+
if (!str) return 0;
|
|
7
|
+
let bytes = 0;
|
|
8
|
+
for (let i = 0; i < str.length; i++) {
|
|
9
|
+
const code = str.charCodeAt(i);
|
|
10
|
+
if (code <= 0x7f) {
|
|
11
|
+
bytes += 1;
|
|
12
|
+
} else if (code <= 0x7ff) {
|
|
13
|
+
bytes += 2;
|
|
14
|
+
} else if (code >= 0xd800 && code <= 0xdbff) {
|
|
15
|
+
bytes += 4;
|
|
16
|
+
i++;
|
|
17
|
+
} else {
|
|
18
|
+
bytes += 3;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return bytes;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Calculates exponential backoff with full symmetric jitter matching iOS/Android.
|
|
26
|
+
*/
|
|
27
|
+
class SseReconnectStrategy {
|
|
28
|
+
_backoffCounter = 0;
|
|
29
|
+
_currentReconnectAttempts = 0;
|
|
30
|
+
_retryInterval = 1.0; // in seconds
|
|
31
|
+
_maxRetryInterval = 30.0;
|
|
32
|
+
_jitterFactor = 0.5;
|
|
33
|
+
_maxReconnectAttempts = -1;
|
|
34
|
+
configure(retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts) {
|
|
35
|
+
if (retryIntervalMs !== undefined && !Number.isNaN(retryIntervalMs) && retryIntervalMs >= 0) {
|
|
36
|
+
this._retryInterval = retryIntervalMs / 1000.0;
|
|
37
|
+
} else {
|
|
38
|
+
this._retryInterval = 1.0;
|
|
39
|
+
}
|
|
40
|
+
if (maxRetryIntervalMs !== undefined && !Number.isNaN(maxRetryIntervalMs) && maxRetryIntervalMs >= 0) {
|
|
41
|
+
this._maxRetryInterval = maxRetryIntervalMs / 1000.0;
|
|
42
|
+
} else {
|
|
43
|
+
this._maxRetryInterval = 30.0;
|
|
44
|
+
}
|
|
45
|
+
if (jitterFactor !== undefined && !Number.isNaN(jitterFactor)) {
|
|
46
|
+
this._jitterFactor = Math.min(Math.max(0.0, jitterFactor), 1.0);
|
|
47
|
+
} else {
|
|
48
|
+
this._jitterFactor = 0.5;
|
|
49
|
+
}
|
|
50
|
+
if (maxReconnectAttempts !== undefined && !Number.isNaN(maxReconnectAttempts) && maxReconnectAttempts >= 0) {
|
|
51
|
+
this._maxReconnectAttempts = maxReconnectAttempts;
|
|
52
|
+
} else {
|
|
53
|
+
this._maxReconnectAttempts = -1;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
hasReachedMaxAttempts() {
|
|
57
|
+
if (this._maxReconnectAttempts === -1) return false;
|
|
58
|
+
return this._currentReconnectAttempts >= this._maxReconnectAttempts;
|
|
59
|
+
}
|
|
60
|
+
recordAttempt() {
|
|
61
|
+
this._currentReconnectAttempts++;
|
|
62
|
+
}
|
|
63
|
+
nextDelayMs(isError) {
|
|
64
|
+
this._currentReconnectAttempts++;
|
|
65
|
+
let delay;
|
|
66
|
+
if (isError) {
|
|
67
|
+
const exponent = this._backoffCounter;
|
|
68
|
+
const base = Math.min(this._retryInterval * Math.pow(2.0, exponent), this._maxRetryInterval);
|
|
69
|
+
this._backoffCounter++;
|
|
70
|
+
const randomFactor = 1.0 - this._jitterFactor + Math.random() * (2 * this._jitterFactor);
|
|
71
|
+
delay = base * randomFactor;
|
|
72
|
+
} else {
|
|
73
|
+
const randomFactor = 1.0 - this._jitterFactor + Math.random() * (2 * this._jitterFactor);
|
|
74
|
+
delay = this._retryInterval * randomFactor;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Minimum floor of 1000ms enforced across all platforms
|
|
78
|
+
return Math.max(delay * 1000.0, 1000.0);
|
|
79
|
+
}
|
|
80
|
+
reset() {
|
|
81
|
+
this._backoffCounter = 0;
|
|
82
|
+
this._currentReconnectAttempts = 0;
|
|
83
|
+
}
|
|
84
|
+
updateRetryInterval(retryMs) {
|
|
85
|
+
if (!Number.isNaN(retryMs) && retryMs >= 0) {
|
|
86
|
+
this._retryInterval = retryMs / 1000.0;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Web SSE Driver executing server-sent events using WHATWG fetch(), ReadableStream, and TextDecoder.
|
|
93
|
+
*/
|
|
94
|
+
export class FetchSseDriver {
|
|
95
|
+
_state = 'idle';
|
|
96
|
+
_isRunning = false;
|
|
97
|
+
_isReconnecting = false;
|
|
98
|
+
_dynamicHeaders = {};
|
|
99
|
+
_consecutiveAuthErrors = 0;
|
|
100
|
+
_connectionAttemptVersion = 0;
|
|
101
|
+
_batchBuffer = [];
|
|
102
|
+
_wasRunningBeforeNetworkLoss = false;
|
|
103
|
+
_reconnectStrategy = new SseReconnectStrategy();
|
|
104
|
+
// === Stats tracking ===
|
|
105
|
+
_rawBytesReceived = 0;
|
|
106
|
+
_totalBytesReceived = 0;
|
|
107
|
+
_chunksReceived = 0;
|
|
108
|
+
_totalEventsReceived = 0;
|
|
109
|
+
_commentsReceived = 0;
|
|
110
|
+
_linesParsed = 0;
|
|
111
|
+
_parseErrors = 0;
|
|
112
|
+
_lastActivityTime = 0;
|
|
113
|
+
_maxEventGapMs = 0;
|
|
114
|
+
_peakBufferedEvents = 0;
|
|
115
|
+
_bufferFlushCount = 0;
|
|
116
|
+
_bufferOverflowCount = 0;
|
|
117
|
+
_connectionAttempts = 0;
|
|
118
|
+
_reconnectCount = 0;
|
|
119
|
+
constructor(dispatchEvents = () => {}) {
|
|
120
|
+
this._dispatchEvents = dispatchEvents;
|
|
121
|
+
}
|
|
122
|
+
setDispatchEvents(dispatchEvents) {
|
|
123
|
+
this._dispatchEvents = dispatchEvents;
|
|
124
|
+
}
|
|
125
|
+
setup(config, onBeforeRequest) {
|
|
126
|
+
this._config = config;
|
|
127
|
+
this._onBeforeRequest = onBeforeRequest;
|
|
128
|
+
this._dynamicHeaders = {};
|
|
129
|
+
this._wasRunningBeforeNetworkLoss = false;
|
|
130
|
+
if (this._lastProcessedId === undefined && config.headers) {
|
|
131
|
+
const headerEntry = Object.entries(config.headers).find(([k]) => k.toLowerCase() === 'last-event-id');
|
|
132
|
+
if (headerEntry) {
|
|
133
|
+
this._lastProcessedId = headerEntry[1];
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
this._reconnectStrategy.configure(config.retryIntervalMs, config.maxRetryIntervalMs, config.jitterFactor, config.maxReconnectAttempts);
|
|
137
|
+
if (config.monitorNetwork !== false) {
|
|
138
|
+
this._setupNetworkListeners();
|
|
139
|
+
} else {
|
|
140
|
+
this._teardownNetworkListeners();
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
start() {
|
|
144
|
+
if (!this._config) {
|
|
145
|
+
throw new Error('[FetchSseDriver] Cannot start: driver is not configured. Call setup() first.');
|
|
146
|
+
}
|
|
147
|
+
if (this._isRunning) {
|
|
148
|
+
// Immediate "Retry Now" if currently in reconnection backoff loop
|
|
149
|
+
if (this._state === 'reconnecting') {
|
|
150
|
+
if (this._reconnectTimer) {
|
|
151
|
+
clearTimeout(this._reconnectTimer);
|
|
152
|
+
this._reconnectTimer = undefined;
|
|
153
|
+
}
|
|
154
|
+
this._reconnectStrategy.reset();
|
|
155
|
+
this._consecutiveAuthErrors = 0;
|
|
156
|
+
this._connectionAttemptVersion++;
|
|
157
|
+
this._updateState('connecting');
|
|
158
|
+
this._establishConnection(this._connectionAttemptVersion);
|
|
159
|
+
}
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
this._isRunning = true;
|
|
163
|
+
this._isReconnecting = false;
|
|
164
|
+
this._wasRunningBeforeNetworkLoss = false;
|
|
165
|
+
this._consecutiveAuthErrors = 0;
|
|
166
|
+
this._reconnectStrategy.reset();
|
|
167
|
+
this._connectionAttemptVersion++;
|
|
168
|
+
this._establishConnection(this._connectionAttemptVersion);
|
|
169
|
+
}
|
|
170
|
+
stop() {
|
|
171
|
+
if (this._isRunning) {
|
|
172
|
+
this._disconnectReason = 'user_stop';
|
|
173
|
+
}
|
|
174
|
+
this._stopInternal(true);
|
|
175
|
+
}
|
|
176
|
+
restart() {
|
|
177
|
+
if (!this._config) {
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
this._connectedAt = undefined;
|
|
181
|
+
this._cleanupTimers();
|
|
182
|
+
this._cleanupTransport();
|
|
183
|
+
this._flushBatch();
|
|
184
|
+
this._isRunning = true;
|
|
185
|
+
this._connectionAttemptVersion++;
|
|
186
|
+
this._updateState('reconnecting');
|
|
187
|
+
this._establishConnection(this._connectionAttemptVersion);
|
|
188
|
+
}
|
|
189
|
+
flush() {
|
|
190
|
+
this._flushBatch();
|
|
191
|
+
}
|
|
192
|
+
isConnected() {
|
|
193
|
+
return this._isRunning;
|
|
194
|
+
}
|
|
195
|
+
getStats() {
|
|
196
|
+
return {
|
|
197
|
+
rawBytesReceived: this._rawBytesReceived,
|
|
198
|
+
decompressedBytesReceived: undefined,
|
|
199
|
+
totalBytesReceived: this._totalBytesReceived,
|
|
200
|
+
chunksReceived: this._chunksReceived,
|
|
201
|
+
lastStatusCode: this._lastStatusCode,
|
|
202
|
+
totalEventsReceived: this._totalEventsReceived,
|
|
203
|
+
commentsReceived: this._commentsReceived,
|
|
204
|
+
linesParsed: this._linesParsed,
|
|
205
|
+
parseErrors: this._parseErrors,
|
|
206
|
+
serverRetryDelayMs: this._serverRetryDelayMs,
|
|
207
|
+
connectedAt: this._connectedAt,
|
|
208
|
+
timeToFirstByteMs: this._timeToFirstByteMs,
|
|
209
|
+
lastEventTime: this._lastEventTime,
|
|
210
|
+
lastHeartbeatTime: this._lastHeartbeatTime,
|
|
211
|
+
maxEventGapMs: this._maxEventGapMs,
|
|
212
|
+
eventsBuffered: this._batchBuffer.length,
|
|
213
|
+
peakBufferedEvents: this._peakBufferedEvents,
|
|
214
|
+
bufferFlushCount: this._bufferFlushCount,
|
|
215
|
+
bufferOverflowCount: this._bufferOverflowCount,
|
|
216
|
+
connectionAttempts: this._connectionAttempts,
|
|
217
|
+
reconnectCount: this._reconnectCount,
|
|
218
|
+
lastReconnectDelayMs: this._lastReconnectDelayMs,
|
|
219
|
+
disconnectReason: this._disconnectReason,
|
|
220
|
+
lastErrorTime: this._lastErrorTime,
|
|
221
|
+
lastErrorCode: this._lastErrorCode
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
getState() {
|
|
225
|
+
return this._state;
|
|
226
|
+
}
|
|
227
|
+
updateHeaders(headers) {
|
|
228
|
+
this._dynamicHeaders = {
|
|
229
|
+
...this._dynamicHeaders,
|
|
230
|
+
...headers
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
setLastProcessedId(id) {
|
|
234
|
+
this._lastProcessedId = id;
|
|
235
|
+
}
|
|
236
|
+
injectMockEvent(event) {
|
|
237
|
+
const sseEvent = MockSseEngine.createSseEvent(event);
|
|
238
|
+
this._pushEvent(sseEvent);
|
|
239
|
+
}
|
|
240
|
+
dispose() {
|
|
241
|
+
this.stop();
|
|
242
|
+
this._teardownNetworkListeners();
|
|
243
|
+
this._batchBuffer = [];
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// =========================================================================
|
|
247
|
+
// Internal Connection Engine
|
|
248
|
+
// =========================================================================
|
|
249
|
+
|
|
250
|
+
async _establishConnection(attemptVersion) {
|
|
251
|
+
if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion || !this._config) {
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
this._updateState('connecting');
|
|
255
|
+
this._connectionAttempts++;
|
|
256
|
+
this._connectionAttemptStartTime = Date.now();
|
|
257
|
+
this._timeToFirstByteMs = undefined;
|
|
258
|
+
|
|
259
|
+
// 1. Prepare dynamic headers via interceptor if configured
|
|
260
|
+
let dynamicInterceptorHeaders = {};
|
|
261
|
+
if (this._onBeforeRequest) {
|
|
262
|
+
try {
|
|
263
|
+
const timeoutMs = this._config.connectionTimeoutMs ?? 15000;
|
|
264
|
+
let interceptorTimer;
|
|
265
|
+
try {
|
|
266
|
+
dynamicInterceptorHeaders = await Promise.race([this._onBeforeRequest(), new Promise((_, reject) => {
|
|
267
|
+
interceptorTimer = setTimeout(() => reject(new Error('onBeforeRequest interceptor timeout')), timeoutMs);
|
|
268
|
+
})]);
|
|
269
|
+
} finally {
|
|
270
|
+
if (interceptorTimer !== undefined) {
|
|
271
|
+
clearTimeout(interceptorTimer);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
} catch (err) {
|
|
275
|
+
if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
|
|
276
|
+
this._recordError('Interceptor Error', undefined);
|
|
277
|
+
this._failAndStop(`Interceptor Error: ${err instanceof Error ? err.message : String(err)}`, -1);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
|
|
282
|
+
|
|
283
|
+
// URL syntax and protocol validation matching Native (http/https only)
|
|
284
|
+
try {
|
|
285
|
+
const parsedUrl = new URL(this._config.url, typeof window !== 'undefined' && window.location ? window.location.href : 'http://localhost');
|
|
286
|
+
if (!['http:', 'https:'].includes(parsedUrl.protocol)) {
|
|
287
|
+
this._failAndStop(`Invalid URL: ${this._config.url}`, -1);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
} catch {
|
|
291
|
+
this._failAndStop(`Invalid URL: ${this._config.url}`, -1);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// 2. Build headers
|
|
296
|
+
const filteredHeaders = {};
|
|
297
|
+
for (const [k, v] of Object.entries({
|
|
298
|
+
...(this._config.headers ?? {}),
|
|
299
|
+
...this._dynamicHeaders,
|
|
300
|
+
...dynamicInterceptorHeaders
|
|
301
|
+
})) {
|
|
302
|
+
const lower = k.toLowerCase();
|
|
303
|
+
if (lower !== 'last-event-id' && lower !== 'accept-encoding') {
|
|
304
|
+
filteredHeaders[k] = v;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
const mergedHeaders = {
|
|
308
|
+
'Accept': 'text/event-stream',
|
|
309
|
+
'Cache-Control': 'no-cache',
|
|
310
|
+
...filteredHeaders
|
|
311
|
+
};
|
|
312
|
+
if (this._lastProcessedId && this._lastProcessedId.length > 0) {
|
|
313
|
+
mergedHeaders['Last-Event-ID'] = this._lastProcessedId;
|
|
314
|
+
}
|
|
315
|
+
const abortController = new AbortController();
|
|
316
|
+
this._abortController = abortController;
|
|
317
|
+
const connectionTimeoutMs = this._config.connectionTimeoutMs ?? 15000;
|
|
318
|
+
this._connectionTimer = setTimeout(() => {
|
|
319
|
+
if (attemptVersion === this._connectionAttemptVersion) {
|
|
320
|
+
this._disconnectReason = 'timeout';
|
|
321
|
+
abortController.abort();
|
|
322
|
+
}
|
|
323
|
+
}, connectionTimeoutMs);
|
|
324
|
+
const method = (this._config.method ?? 'get').toUpperCase();
|
|
325
|
+
const fetchOptions = {
|
|
326
|
+
method,
|
|
327
|
+
headers: mergedHeaders,
|
|
328
|
+
signal: abortController.signal,
|
|
329
|
+
mode: 'cors',
|
|
330
|
+
credentials: 'same-origin'
|
|
331
|
+
};
|
|
332
|
+
if (method === 'POST') {
|
|
333
|
+
const hasContentType = Object.keys(mergedHeaders).some(k => k.toLowerCase() === 'content-type');
|
|
334
|
+
if (!hasContentType && this._config.body) {
|
|
335
|
+
mergedHeaders['Content-Type'] = 'application/json';
|
|
336
|
+
}
|
|
337
|
+
if (this._config.body) {
|
|
338
|
+
fetchOptions.body = this._config.body;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
let response;
|
|
342
|
+
try {
|
|
343
|
+
response = await fetch(this._config.url, fetchOptions);
|
|
344
|
+
} catch (err) {
|
|
345
|
+
clearTimeout(this._connectionTimer);
|
|
346
|
+
if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
|
|
347
|
+
const isAborted = abortController.signal.aborted;
|
|
348
|
+
const errorMsg = isAborted ? 'Connection timeout' : err instanceof Error ? err.message : 'Failed to fetch';
|
|
349
|
+
this._disconnectReason = isAborted ? 'timeout' : 'network_error';
|
|
350
|
+
if (isAborted) {
|
|
351
|
+
this._updateState('stale');
|
|
352
|
+
}
|
|
353
|
+
this._recordError(errorMsg, undefined);
|
|
354
|
+
this._pushEvent({
|
|
355
|
+
type: 'error',
|
|
356
|
+
message: errorMsg
|
|
357
|
+
});
|
|
358
|
+
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
clearTimeout(this._connectionTimer);
|
|
362
|
+
if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
|
|
363
|
+
const statusCode = response.status;
|
|
364
|
+
this._lastStatusCode = statusCode;
|
|
365
|
+
let errorBody;
|
|
366
|
+
if (statusCode >= 400 || statusCode === 204) {
|
|
367
|
+
try {
|
|
368
|
+
errorBody = await response.text();
|
|
369
|
+
} catch {
|
|
370
|
+
// Ignore body reading error
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// 3. HTTP Validation Rules matching Native (WHATWG SSE Section 9.1)
|
|
375
|
+
// 3a. HTTP 200 OK: Content-Type MIME type MUST be text/event-stream
|
|
376
|
+
if (statusCode === 200) {
|
|
377
|
+
const contentType = response.headers.get('Content-Type') ?? '';
|
|
378
|
+
const mimeType = contentType.split(';')[0]?.trim().toLowerCase() ?? '';
|
|
379
|
+
if (mimeType !== 'text/event-stream') {
|
|
380
|
+
this._disconnectReason = 'server_error';
|
|
381
|
+
this._failAndStop(`Invalid Content-Type: expected text/event-stream but received '${contentType}'. Stopping.`, statusCode);
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
} else if (statusCode === 204) {
|
|
385
|
+
// 3b. HTTP 204 No Content is fatal per WHATWG SSE spec
|
|
386
|
+
this._disconnectReason = 'server_error';
|
|
387
|
+
this._failAndStop('Server sent HTTP 204 No Content. Stopping.', statusCode);
|
|
388
|
+
return;
|
|
389
|
+
} else if (statusCode === 401 || statusCode === 403) {
|
|
390
|
+
// 3c. HTTP 401/403 Auth errors
|
|
391
|
+
const maxAuthRetries = this._config.maxAuthRetries ?? 3;
|
|
392
|
+
if (!this._onBeforeRequest) {
|
|
393
|
+
this._disconnectReason = 'server_error';
|
|
394
|
+
this._failAndStop(`Auth Error (${statusCode}) - No interceptor provided. Stopping.`, statusCode);
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
this._consecutiveAuthErrors++;
|
|
398
|
+
if (this._consecutiveAuthErrors > maxAuthRetries) {
|
|
399
|
+
this._disconnectReason = 'server_error';
|
|
400
|
+
this._failAndStop(`Auth Error (${statusCode}) - Retry limit reached (${maxAuthRetries}). Stopping.`, statusCode);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
this._recordError(`Auth Error (${statusCode})`, String(statusCode));
|
|
404
|
+
this._pushEvent({
|
|
405
|
+
type: 'error',
|
|
406
|
+
statusCode,
|
|
407
|
+
message: `Auth Error (${statusCode}) - Retry ${this._consecutiveAuthErrors}/${maxAuthRetries}. Refreshing token...`
|
|
408
|
+
});
|
|
409
|
+
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
410
|
+
return;
|
|
411
|
+
} else if (statusCode === 408) {
|
|
412
|
+
// 3d. Request Timeout: Recoverable per WHATWG SSE and Native specs
|
|
413
|
+
this._disconnectReason = 'timeout';
|
|
414
|
+
this._updateState('stale');
|
|
415
|
+
this._recordError('HTTP 408', '408');
|
|
416
|
+
this._pushEvent({
|
|
417
|
+
type: 'error',
|
|
418
|
+
statusCode: 408,
|
|
419
|
+
message: 'HTTP 408'
|
|
420
|
+
});
|
|
421
|
+
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
422
|
+
return;
|
|
423
|
+
} else if (statusCode === 429 || statusCode === 503) {
|
|
424
|
+
// 3e. Rate limit / Service unavailable: Honor Retry-After
|
|
425
|
+
const retryAfterHeader = response.headers.get('Retry-After');
|
|
426
|
+
const rawRetryAfterMs = this._parseRetryAfterHeader(retryAfterHeader);
|
|
427
|
+
this._disconnectReason = 'server_error';
|
|
428
|
+
this._recordError(`HTTP ${statusCode}`, String(statusCode));
|
|
429
|
+
if (rawRetryAfterMs !== undefined) {
|
|
430
|
+
const maxIntervalMs = this._config.maxRetryIntervalMs ?? 30000;
|
|
431
|
+
const boundedRetryMs = Math.max(0, Math.min(rawRetryAfterMs, maxIntervalMs));
|
|
432
|
+
this._pushEvent({
|
|
433
|
+
type: 'error',
|
|
434
|
+
statusCode,
|
|
435
|
+
retry: boundedRetryMs,
|
|
436
|
+
message: `Retry-After received: ${Math.round(boundedRetryMs / 1000)}s`
|
|
437
|
+
});
|
|
438
|
+
this._scheduleReconnect(true, boundedRetryMs, attemptVersion);
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
if (statusCode === 429) {
|
|
442
|
+
this._pushEvent({
|
|
443
|
+
type: 'error',
|
|
444
|
+
statusCode: 429,
|
|
445
|
+
message: 'Rate Limited (429). Retrying with backoff...'
|
|
446
|
+
});
|
|
447
|
+
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
this._pushEvent({
|
|
451
|
+
type: 'error',
|
|
452
|
+
statusCode,
|
|
453
|
+
message: `HTTP ${statusCode}`
|
|
454
|
+
});
|
|
455
|
+
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
456
|
+
return;
|
|
457
|
+
} else if (statusCode >= 400 && statusCode <= 499) {
|
|
458
|
+
// 3f. Fatal client error (e.g. 400 Bad Request, 404 Not Found, 405 Method Not Allowed)
|
|
459
|
+
this._disconnectReason = 'server_error';
|
|
460
|
+
const bodyText = errorBody?.trim();
|
|
461
|
+
const fatalMessage = bodyText ? `Fatal Error (${statusCode}): ${bodyText}` : `Fatal Error (${statusCode}). Stopping.`;
|
|
462
|
+
this._failAndStop(fatalMessage, statusCode);
|
|
463
|
+
return;
|
|
464
|
+
} else if (statusCode >= 500) {
|
|
465
|
+
// 3g. Server error: Recoverable
|
|
466
|
+
this._disconnectReason = 'server_error';
|
|
467
|
+
this._recordError(`Server Error (${statusCode})`, String(statusCode));
|
|
468
|
+
const bodyText = errorBody?.trim();
|
|
469
|
+
const errorMsg = bodyText ? `Server Error (${statusCode}): ${bodyText}` : `Server Error (${statusCode})`;
|
|
470
|
+
this._pushEvent({
|
|
471
|
+
type: 'error',
|
|
472
|
+
statusCode,
|
|
473
|
+
message: errorMsg
|
|
474
|
+
});
|
|
475
|
+
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
476
|
+
return;
|
|
477
|
+
} else {
|
|
478
|
+
// Any other non-200 status code (e.g. 201 Created, 202, 3xx) is fatal per WHATWG SSE Section 9.1
|
|
479
|
+
this._disconnectReason = 'server_error';
|
|
480
|
+
this._failAndStop(`HTTP ${statusCode} is not a valid SSE response. Stopping.`, statusCode);
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
if (!response.body) {
|
|
484
|
+
this._failAndStop('Response body is null. ReadableStream is not supported.', statusCode);
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// 4. Connection established successfully
|
|
489
|
+
this._reconnectStrategy.reset();
|
|
490
|
+
this._consecutiveAuthErrors = 0;
|
|
491
|
+
if (this._isReconnecting || this._state === 'reconnecting') {
|
|
492
|
+
this._reconnectCount++;
|
|
493
|
+
this._isReconnecting = false;
|
|
494
|
+
}
|
|
495
|
+
this._connectedAt = Date.now();
|
|
496
|
+
this._updateState('open');
|
|
497
|
+
this._pushEvent({
|
|
498
|
+
type: 'open',
|
|
499
|
+
statusCode
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
// 5. Initialize streaming reader and parser
|
|
503
|
+
this._parser = new SseEventParser(this, this._lastProcessedId);
|
|
504
|
+
const reader = response.body.getReader();
|
|
505
|
+
this._activeReader = reader;
|
|
506
|
+
const decoder = new TextDecoder('utf-8');
|
|
507
|
+
|
|
508
|
+
// 6. Setup idle read timeout
|
|
509
|
+
this._resetReadTimeout(attemptVersion);
|
|
510
|
+
try {
|
|
511
|
+
while (this._isRunning && attemptVersion === this._connectionAttemptVersion) {
|
|
512
|
+
const {
|
|
513
|
+
value,
|
|
514
|
+
done
|
|
515
|
+
} = await reader.read();
|
|
516
|
+
if (done) {
|
|
517
|
+
decoder.decode(); // flush trailing bytes
|
|
518
|
+
this._parser?.endOfStream();
|
|
519
|
+
break;
|
|
520
|
+
}
|
|
521
|
+
if (value) {
|
|
522
|
+
if (this._timeToFirstByteMs === undefined && this._connectionAttemptStartTime) {
|
|
523
|
+
this._timeToFirstByteMs = Date.now() - this._connectionAttemptStartTime;
|
|
524
|
+
}
|
|
525
|
+
this._rawBytesReceived += value.byteLength;
|
|
526
|
+
this._chunksReceived++;
|
|
527
|
+
this._resetReadTimeout(attemptVersion);
|
|
528
|
+
const text = decoder.decode(value, {
|
|
529
|
+
stream: true
|
|
530
|
+
});
|
|
531
|
+
this._parser?.feed(text);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
} catch (readErr) {
|
|
535
|
+
if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
|
|
536
|
+
const isAborted = abortController.signal.aborted;
|
|
537
|
+
if (!isAborted) {
|
|
538
|
+
this._recordError(readErr instanceof Error ? readErr.message : 'Read error', undefined);
|
|
539
|
+
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
} finally {
|
|
543
|
+
this._clearReadTimeout();
|
|
544
|
+
}
|
|
545
|
+
if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
|
|
546
|
+
|
|
547
|
+
// Clean disconnect from server
|
|
548
|
+
this._scheduleReconnect(false, undefined, attemptVersion);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// =========================================================================
|
|
552
|
+
// Reconnect & Teardown Helpers
|
|
553
|
+
// =========================================================================
|
|
554
|
+
|
|
555
|
+
_scheduleReconnect(isError, fixedDelayMs, attemptVersion) {
|
|
556
|
+
if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
|
|
557
|
+
if (this._reconnectStrategy.hasReachedMaxAttempts()) {
|
|
558
|
+
const maxAttempts = this._config?.maxReconnectAttempts ?? -1;
|
|
559
|
+
this._failAndStop(`Max reconnection attempts reached (${maxAttempts}).`);
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
let delay;
|
|
563
|
+
if (fixedDelayMs !== undefined) {
|
|
564
|
+
this._reconnectStrategy.recordAttempt();
|
|
565
|
+
delay = fixedDelayMs;
|
|
566
|
+
} else {
|
|
567
|
+
delay = this._reconnectStrategy.nextDelayMs(isError);
|
|
568
|
+
}
|
|
569
|
+
this._lastReconnectDelayMs = delay;
|
|
570
|
+
this._connectionAttemptVersion++;
|
|
571
|
+
const newVersion = this._connectionAttemptVersion;
|
|
572
|
+
this._isReconnecting = true;
|
|
573
|
+
this._updateState('reconnecting');
|
|
574
|
+
this._cleanupTransport();
|
|
575
|
+
this._reconnectTimer = setTimeout(() => {
|
|
576
|
+
if (this._isRunning && newVersion === this._connectionAttemptVersion) {
|
|
577
|
+
this._establishConnection(newVersion);
|
|
578
|
+
}
|
|
579
|
+
}, delay);
|
|
580
|
+
}
|
|
581
|
+
_stopInternal(emitClosed) {
|
|
582
|
+
this._connectedAt = undefined;
|
|
583
|
+
this._isRunning = false;
|
|
584
|
+
this._isReconnecting = false;
|
|
585
|
+
this._connectionAttemptVersion++;
|
|
586
|
+
this._cleanupTimers();
|
|
587
|
+
this._cleanupTransport();
|
|
588
|
+
this._flushBatch();
|
|
589
|
+
if (emitClosed && this._state !== 'failed') {
|
|
590
|
+
this._updateState('closed');
|
|
591
|
+
this._flushBatch();
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
_failAndStop(message, statusCode) {
|
|
595
|
+
this._connectionAttemptVersion++;
|
|
596
|
+
this._recordError(message, statusCode !== undefined ? String(statusCode) : undefined);
|
|
597
|
+
this._pushEvent({
|
|
598
|
+
type: 'error',
|
|
599
|
+
message,
|
|
600
|
+
statusCode
|
|
601
|
+
});
|
|
602
|
+
this._updateState('failed');
|
|
603
|
+
this._stopInternal(false);
|
|
604
|
+
}
|
|
605
|
+
_cleanupTransport() {
|
|
606
|
+
if (this._activeReader) {
|
|
607
|
+
try {
|
|
608
|
+
this._activeReader.cancel().catch(() => {});
|
|
609
|
+
} catch {
|
|
610
|
+
// Ignore reader cancellation errors
|
|
611
|
+
}
|
|
612
|
+
this._activeReader = undefined;
|
|
613
|
+
}
|
|
614
|
+
if (this._abortController) {
|
|
615
|
+
try {
|
|
616
|
+
this._abortController.abort();
|
|
617
|
+
} catch {
|
|
618
|
+
// Ignore abort errors
|
|
619
|
+
}
|
|
620
|
+
this._abortController = undefined;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
_cleanupTimers() {
|
|
624
|
+
if (this._connectionTimer) {
|
|
625
|
+
clearTimeout(this._connectionTimer);
|
|
626
|
+
this._connectionTimer = undefined;
|
|
627
|
+
}
|
|
628
|
+
if (this._readTimeoutTimer) {
|
|
629
|
+
clearTimeout(this._readTimeoutTimer);
|
|
630
|
+
this._readTimeoutTimer = undefined;
|
|
631
|
+
}
|
|
632
|
+
if (this._reconnectTimer) {
|
|
633
|
+
clearTimeout(this._reconnectTimer);
|
|
634
|
+
this._reconnectTimer = undefined;
|
|
635
|
+
}
|
|
636
|
+
if (this._batchTimer) {
|
|
637
|
+
clearTimeout(this._batchTimer);
|
|
638
|
+
this._batchTimer = undefined;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
_resetReadTimeout(attemptVersion) {
|
|
642
|
+
this._clearReadTimeout();
|
|
643
|
+
const readTimeoutMs = this._config?.readTimeoutMs ?? 300000;
|
|
644
|
+
if (readTimeoutMs <= 0) return;
|
|
645
|
+
this._readTimeoutTimer = setTimeout(() => {
|
|
646
|
+
if (this._isRunning && attemptVersion === this._connectionAttemptVersion) {
|
|
647
|
+
this._disconnectReason = 'timeout';
|
|
648
|
+
this._updateState('stale');
|
|
649
|
+
this._cleanupTransport();
|
|
650
|
+
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
651
|
+
}
|
|
652
|
+
}, readTimeoutMs);
|
|
653
|
+
}
|
|
654
|
+
_clearReadTimeout() {
|
|
655
|
+
if (this._readTimeoutTimer) {
|
|
656
|
+
clearTimeout(this._readTimeoutTimer);
|
|
657
|
+
this._readTimeoutTimer = undefined;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
_updateState(newState) {
|
|
661
|
+
if (this._state === newState) return;
|
|
662
|
+
this._state = newState;
|
|
663
|
+
this._pushEvent({
|
|
664
|
+
type: 'state',
|
|
665
|
+
state: newState
|
|
666
|
+
});
|
|
667
|
+
this._flushBatch();
|
|
668
|
+
}
|
|
669
|
+
_recordError(message, code) {
|
|
670
|
+
this._lastErrorTime = Date.now();
|
|
671
|
+
this._lastErrorCode = code ?? message;
|
|
672
|
+
}
|
|
673
|
+
_parseRetryAfterHeader(value) {
|
|
674
|
+
if (!value) return undefined;
|
|
675
|
+
const trimmed = value.trim();
|
|
676
|
+
if (/^[0-9]+$/.test(trimmed)) {
|
|
677
|
+
const seconds = parseInt(trimmed, 10);
|
|
678
|
+
return seconds * 1000;
|
|
679
|
+
}
|
|
680
|
+
const timestamp = Date.parse(trimmed);
|
|
681
|
+
if (!Number.isNaN(timestamp)) {
|
|
682
|
+
const diff = timestamp - Date.now();
|
|
683
|
+
return Math.max(diff, 1000);
|
|
684
|
+
}
|
|
685
|
+
return undefined;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// =========================================================================
|
|
689
|
+
// Batching & Dispatching
|
|
690
|
+
// =========================================================================
|
|
691
|
+
|
|
692
|
+
_pushEvent(event) {
|
|
693
|
+
const batchingIntervalMs = this._config?.batchingIntervalMs ?? 0;
|
|
694
|
+
const maxBufferSize = this._config?.maxBufferSize ?? 1000;
|
|
695
|
+
this._batchBuffer.push(event);
|
|
696
|
+
if (this._batchBuffer.length > this._peakBufferedEvents) {
|
|
697
|
+
this._peakBufferedEvents = this._batchBuffer.length;
|
|
698
|
+
}
|
|
699
|
+
if (this._batchBuffer.length >= maxBufferSize && batchingIntervalMs > 0) {
|
|
700
|
+
this._bufferOverflowCount++;
|
|
701
|
+
this._cancelBatchTimer();
|
|
702
|
+
this._flushBatch();
|
|
703
|
+
} else if (this._batchBuffer.length >= maxBufferSize || batchingIntervalMs <= 0) {
|
|
704
|
+
this._cancelBatchTimer();
|
|
705
|
+
this._flushBatch();
|
|
706
|
+
} else if (!this._batchTimer) {
|
|
707
|
+
this._batchTimer = setTimeout(() => {
|
|
708
|
+
this._batchTimer = undefined;
|
|
709
|
+
this._flushBatch();
|
|
710
|
+
}, batchingIntervalMs);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
_flushBatch() {
|
|
714
|
+
this._cancelBatchTimer();
|
|
715
|
+
if (this._batchBuffer.length === 0) return;
|
|
716
|
+
this._bufferFlushCount++;
|
|
717
|
+
const batch = this._batchBuffer;
|
|
718
|
+
this._batchBuffer = [];
|
|
719
|
+
this._dispatchEvents(batch);
|
|
720
|
+
}
|
|
721
|
+
_cancelBatchTimer() {
|
|
722
|
+
if (this._batchTimer) {
|
|
723
|
+
clearTimeout(this._batchTimer);
|
|
724
|
+
this._batchTimer = undefined;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// =========================================================================
|
|
729
|
+
// SseEventParserDelegate Implementation
|
|
730
|
+
// =========================================================================
|
|
731
|
+
|
|
732
|
+
onEvent(id, type, data) {
|
|
733
|
+
const now = Date.now();
|
|
734
|
+
this._lastEventTime = now;
|
|
735
|
+
if (this._lastActivityTime > 0) {
|
|
736
|
+
const gap = now - this._lastActivityTime;
|
|
737
|
+
if (gap > this._maxEventGapMs) {
|
|
738
|
+
this._maxEventGapMs = gap;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
this._lastActivityTime = now;
|
|
742
|
+
const eventType = type ?? 'message';
|
|
743
|
+
const encodedDataSize = getUtf8ByteCount(data);
|
|
744
|
+
const eventTypeSize = eventType === 'message' ? 0 : getUtf8ByteCount(eventType);
|
|
745
|
+
this._totalBytesReceived += encodedDataSize + eventTypeSize;
|
|
746
|
+
if (id !== undefined && id !== this._lastProcessedId) {
|
|
747
|
+
this._totalBytesReceived += getUtf8ByteCount(id);
|
|
748
|
+
this._lastProcessedId = id;
|
|
749
|
+
}
|
|
750
|
+
this._totalEventsReceived++;
|
|
751
|
+
let parsedData;
|
|
752
|
+
if (this._config?.autoParseJSON && data.trimStart().startsWith('{')) {
|
|
753
|
+
try {
|
|
754
|
+
const obj = JSON.parse(data);
|
|
755
|
+
if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
|
|
756
|
+
parsedData = obj;
|
|
757
|
+
}
|
|
758
|
+
} catch {
|
|
759
|
+
// Ignore JSON parsing failures
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
this._pushEvent({
|
|
763
|
+
type: 'message',
|
|
764
|
+
data,
|
|
765
|
+
parsedData,
|
|
766
|
+
id: id ?? this._lastProcessedId,
|
|
767
|
+
event: type,
|
|
768
|
+
statusCode: 200
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
onComment(comment) {
|
|
772
|
+
const now = Date.now();
|
|
773
|
+
this._lastHeartbeatTime = now;
|
|
774
|
+
if (this._lastActivityTime > 0) {
|
|
775
|
+
const gap = now - this._lastActivityTime;
|
|
776
|
+
if (gap > this._maxEventGapMs) {
|
|
777
|
+
this._maxEventGapMs = gap;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
this._lastActivityTime = now;
|
|
781
|
+
this._totalBytesReceived += getUtf8ByteCount(comment);
|
|
782
|
+
this._commentsReceived++;
|
|
783
|
+
this._pushEvent({
|
|
784
|
+
type: 'heartbeat',
|
|
785
|
+
message: comment
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
onRetry(retryMs) {
|
|
789
|
+
this._serverRetryDelayMs = retryMs;
|
|
790
|
+
this._reconnectStrategy.updateRetryInterval(retryMs);
|
|
791
|
+
}
|
|
792
|
+
onIdUpdate(id) {
|
|
793
|
+
if (id !== undefined && id !== this._lastProcessedId) {
|
|
794
|
+
this._totalBytesReceived += getUtf8ByteCount(id);
|
|
795
|
+
}
|
|
796
|
+
this._lastProcessedId = id;
|
|
797
|
+
}
|
|
798
|
+
onParseError(error) {
|
|
799
|
+
this._parseErrors++;
|
|
800
|
+
this._disconnectReason = 'parser_error';
|
|
801
|
+
this._failAndStop(`SSE parser error: ${error.message}`);
|
|
802
|
+
}
|
|
803
|
+
onLinesParsed(count) {
|
|
804
|
+
this._linesParsed += count;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
// =========================================================================
|
|
808
|
+
// Network Monitoring
|
|
809
|
+
// =========================================================================
|
|
810
|
+
|
|
811
|
+
_setupNetworkListeners() {
|
|
812
|
+
if (typeof window === 'undefined' || typeof window.addEventListener !== 'function' || this._offlineListener !== undefined) return;
|
|
813
|
+
this._offlineListener = () => {
|
|
814
|
+
if (this._isRunning) {
|
|
815
|
+
this._wasRunningBeforeNetworkLoss = true;
|
|
816
|
+
this._disconnectReason = 'network_error';
|
|
817
|
+
this._connectionAttemptVersion++;
|
|
818
|
+
this._cleanupTimers();
|
|
819
|
+
this._cleanupTransport();
|
|
820
|
+
this._updateState('paused');
|
|
821
|
+
this._isRunning = false;
|
|
822
|
+
}
|
|
823
|
+
};
|
|
824
|
+
this._onlineListener = () => {
|
|
825
|
+
if (this._wasRunningBeforeNetworkLoss) {
|
|
826
|
+
this._wasRunningBeforeNetworkLoss = false;
|
|
827
|
+
this.start();
|
|
828
|
+
}
|
|
829
|
+
};
|
|
830
|
+
window.addEventListener('offline', this._offlineListener);
|
|
831
|
+
window.addEventListener('online', this._onlineListener);
|
|
832
|
+
}
|
|
833
|
+
_teardownNetworkListeners() {
|
|
834
|
+
if (typeof window === 'undefined' || typeof window.removeEventListener !== 'function') return;
|
|
835
|
+
if (this._offlineListener) {
|
|
836
|
+
window.removeEventListener('offline', this._offlineListener);
|
|
837
|
+
this._offlineListener = undefined;
|
|
838
|
+
}
|
|
839
|
+
if (this._onlineListener) {
|
|
840
|
+
window.removeEventListener('online', this._onlineListener);
|
|
841
|
+
this._onlineListener = undefined;
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
//# sourceMappingURL=FetchSseDriver.js.map
|