react-native-nitro-sse 3.2.0 → 3.3.0

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 (109) hide show
  1. package/README.md +50 -27
  2. package/android/build.gradle +4 -2
  3. package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +8 -32
  4. package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +124 -6
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +439 -510
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +137 -316
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +18 -8
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventReader.kt +231 -0
  9. package/android/src/main/java/com/margelo/nitro/nitrosse/SseFailureClassifier.kt +245 -0
  10. package/android/src/main/java/com/margelo/nitro/nitrosse/SseMetrics.kt +237 -0
  11. package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +13 -6
  12. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +48 -22
  13. package/ios/NitroSse.swift +402 -484
  14. package/ios/SseConfig+CopyWith.swift +0 -2
  15. package/ios/SseConnectionHandler.swift +238 -446
  16. package/ios/SseDispatchQueueDispatcher.swift +7 -7
  17. package/ios/SseDispatcher.swift +5 -4
  18. package/ios/SseEventBuffer.swift +24 -23
  19. package/ios/SseEventParser.swift +360 -0
  20. package/ios/SseFailureClassifier.swift +249 -0
  21. package/ios/SseLifecycleManager.swift +19 -14
  22. package/ios/SseMetrics.swift +188 -0
  23. package/ios/SseNetworkMonitor.swift +18 -14
  24. package/ios/SseReconnectStrategy.swift +28 -30
  25. package/lib/module/FetchSseDriver.js +385 -169
  26. package/lib/module/MockSseEngine.js +15 -17
  27. package/lib/module/NitroSseClient.js +70 -56
  28. package/lib/module/SseConsoleLogger.js +64 -0
  29. package/lib/module/SseEventParser.js +173 -115
  30. package/lib/module/createNitroSse.js +7 -14
  31. package/lib/module/createNitroSse.native.js +2 -1
  32. package/lib/module/useNitroSse.js +103 -90
  33. package/lib/typescript/src/FetchSseDriver.d.ts +11 -4
  34. package/lib/typescript/src/MockSseEngine.d.ts +2 -2
  35. package/lib/typescript/src/NitroSse.nitro.d.ts +9 -1
  36. package/lib/typescript/src/NitroSseClient.d.ts +4 -1
  37. package/lib/typescript/src/SseConsoleLogger.d.ts +28 -0
  38. package/lib/typescript/src/SseEventParser.d.ts +18 -2
  39. package/lib/typescript/src/SseInterface.d.ts +21 -4
  40. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.hpp +1 -1
  41. package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +1 -1
  42. package/nitrogen/generated/android/c++/JHttpMethod.hpp +1 -1
  43. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +1 -1
  44. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -1
  45. package/nitrogen/generated/android/c++/JSseConfig.hpp +1 -1
  46. package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +1 -1
  47. package/nitrogen/generated/android/c++/JSseEvent.hpp +1 -1
  48. package/nitrogen/generated/android/c++/JSseEventType.hpp +1 -1
  49. package/nitrogen/generated/android/c++/JSseMockConfig.hpp +1 -1
  50. package/nitrogen/generated/android/c++/JSseMockEvent.hpp +1 -1
  51. package/nitrogen/generated/android/c++/JSseMockMode.hpp +1 -1
  52. package/nitrogen/generated/android/c++/JSseState.hpp +1 -1
  53. package/nitrogen/generated/android/c++/JSseStats.hpp +1 -1
  54. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.kt +1 -1
  55. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_void_std__vector_SseEvent_.kt +1 -1
  56. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HttpMethod.kt +1 -1
  57. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +1 -1
  58. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +1 -1
  59. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +1 -1
  60. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +1 -1
  61. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEventType.kt +1 -1
  62. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockConfig.kt +1 -1
  63. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockEvent.kt +1 -1
  64. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockMode.kt +1 -1
  65. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseState.kt +1 -1
  66. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +1 -1
  67. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/nitrosseOnLoad.kt +1 -1
  68. package/nitrogen/generated/android/nitrosse+autolinking.cmake +1 -1
  69. package/nitrogen/generated/android/nitrosse+autolinking.gradle +1 -1
  70. package/nitrogen/generated/android/nitrosseOnLoad.cpp +1 -1
  71. package/nitrogen/generated/android/nitrosseOnLoad.hpp +1 -1
  72. package/nitrogen/generated/ios/NitroSse+autolinking.rb +1 -1
  73. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +1 -1
  74. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +1 -1
  75. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +1 -1
  76. package/nitrogen/generated/ios/NitroSseAutolinking.mm +1 -1
  77. package/nitrogen/generated/ios/NitroSseAutolinking.swift +1 -5
  78. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.cpp +1 -1
  79. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +1 -1
  80. package/nitrogen/generated/ios/swift/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.swift +1 -1
  81. package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +1 -1
  82. package/nitrogen/generated/ios/swift/Func_void_std__shared_ptr_Promise_std__unordered_map_std__string__std__string___.swift +1 -1
  83. package/nitrogen/generated/ios/swift/Func_void_std__unordered_map_std__string__std__string_.swift +1 -1
  84. package/nitrogen/generated/ios/swift/Func_void_std__vector_SseEvent_.swift +1 -1
  85. package/nitrogen/generated/ios/swift/HttpMethod.swift +1 -1
  86. package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -1
  87. package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +3 -3
  88. package/nitrogen/generated/ios/swift/SseConfig.swift +1 -1
  89. package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +1 -1
  90. package/nitrogen/generated/ios/swift/SseEvent.swift +1 -1
  91. package/nitrogen/generated/ios/swift/SseEventType.swift +1 -1
  92. package/nitrogen/generated/ios/swift/SseMockConfig.swift +1 -1
  93. package/nitrogen/generated/ios/swift/SseMockEvent.swift +1 -1
  94. package/nitrogen/generated/ios/swift/SseMockMode.swift +1 -1
  95. package/nitrogen/generated/ios/swift/SseState.swift +1 -1
  96. package/nitrogen/generated/ios/swift/SseStats.swift +1 -1
  97. package/nitrogen/generated/shared/c++/HttpMethod.hpp +1 -1
  98. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.cpp +1 -1
  99. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +1 -1
  100. package/nitrogen/generated/shared/c++/SseConfig.hpp +1 -1
  101. package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +1 -1
  102. package/nitrogen/generated/shared/c++/SseEvent.hpp +1 -1
  103. package/nitrogen/generated/shared/c++/SseEventType.hpp +1 -1
  104. package/nitrogen/generated/shared/c++/SseMockConfig.hpp +1 -1
  105. package/nitrogen/generated/shared/c++/SseMockEvent.hpp +1 -1
  106. package/nitrogen/generated/shared/c++/SseMockMode.hpp +1 -1
  107. package/nitrogen/generated/shared/c++/SseState.hpp +1 -1
  108. package/nitrogen/generated/shared/c++/SseStats.hpp +1 -1
  109. package/package.json +12 -4
@@ -3,7 +3,6 @@
3
3
  import { SseEventParser } from "./SseEventParser.js";
4
4
  import { MockSseEngine } from "./MockSseEngine.js";
5
5
  function getUtf8ByteCount(str) {
6
- if (!str) return 0;
7
6
  let bytes = 0;
8
7
  for (let i = 0; i < str.length; i++) {
9
8
  const code = str.charCodeAt(i);
@@ -11,7 +10,7 @@ function getUtf8ByteCount(str) {
11
10
  bytes += 1;
12
11
  } else if (code <= 0x7ff) {
13
12
  bytes += 2;
14
- } else if (code >= 0xd800 && code <= 0xdbff) {
13
+ } else if (code >= 0xd800 && code <= 0xdbff && i + 1 < str.length && str.charCodeAt(i + 1) >= 0xdc00 && str.charCodeAt(i + 1) <= 0xdfff) {
15
14
  bytes += 4;
16
15
  i++;
17
16
  } else {
@@ -20,6 +19,24 @@ function getUtf8ByteCount(str) {
20
19
  }
21
20
  return bytes;
22
21
  }
22
+ function isValidNonNegative(val) {
23
+ return typeof val === 'number' && Number.isFinite(val) && val >= 0;
24
+ }
25
+ const DEFAULT_MAX_BUFFER_SIZE = 1000;
26
+ /** Hard upper bound on buffered events, matching SseEventBuffer on Android (Kotlin) and iOS (Swift). */
27
+ const HARD_MAX_BUFFER_SIZE = 10_000;
28
+ /** Maximum UTF-8 bytes to read from HTTP error responses, matching native 8KB cap. */
29
+ const MAX_ERROR_BODY_BYTES = 8192;
30
+ /** Maximum characters of error body preview included in `event.message` (`event.data` retains the full 8KB body). */
31
+ const MAX_ERROR_MESSAGE_BODY_CHARS = 256;
32
+ function formatErrorBodyPreview(errorBody) {
33
+ const trimmed = errorBody?.trim();
34
+ if (!trimmed) return undefined;
35
+ return trimmed.length > MAX_ERROR_MESSAGE_BODY_CHARS ? `${trimmed.slice(0, MAX_ERROR_MESSAGE_BODY_CHARS)}…` : trimmed;
36
+ }
37
+ function resolveMaxBufferSize(val) {
38
+ return typeof val === 'number' && Number.isFinite(val) && val > 0 ? Math.min(Math.floor(val), HARD_MAX_BUFFER_SIZE) : DEFAULT_MAX_BUFFER_SIZE;
39
+ }
23
40
 
24
41
  /**
25
42
  * Calculates exponential backoff with full symmetric jitter matching iOS/Android.
@@ -32,27 +49,30 @@ class SseReconnectStrategy {
32
49
  _jitterFactor = 0.5;
33
50
  _maxReconnectAttempts = -1;
34
51
  configure(retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts) {
35
- if (retryIntervalMs !== undefined && !Number.isNaN(retryIntervalMs) && retryIntervalMs >= 0) {
52
+ if (isValidNonNegative(retryIntervalMs)) {
36
53
  this._retryInterval = retryIntervalMs / 1000.0;
37
54
  } else {
38
55
  this._retryInterval = 1.0;
39
56
  }
40
- if (maxRetryIntervalMs !== undefined && !Number.isNaN(maxRetryIntervalMs) && maxRetryIntervalMs >= 0) {
57
+ if (isValidNonNegative(maxRetryIntervalMs)) {
41
58
  this._maxRetryInterval = maxRetryIntervalMs / 1000.0;
42
59
  } else {
43
60
  this._maxRetryInterval = 30.0;
44
61
  }
45
- if (jitterFactor !== undefined && !Number.isNaN(jitterFactor)) {
62
+ if (typeof jitterFactor === 'number' && Number.isFinite(jitterFactor)) {
46
63
  this._jitterFactor = Math.min(Math.max(0.0, jitterFactor), 1.0);
47
64
  } else {
48
65
  this._jitterFactor = 0.5;
49
66
  }
50
- if (maxReconnectAttempts !== undefined && !Number.isNaN(maxReconnectAttempts) && maxReconnectAttempts >= 0) {
67
+ if (isValidNonNegative(maxReconnectAttempts)) {
51
68
  this._maxReconnectAttempts = maxReconnectAttempts;
52
69
  } else {
53
70
  this._maxReconnectAttempts = -1;
54
71
  }
55
72
  }
73
+ get maxReconnectAttempts() {
74
+ return this._maxReconnectAttempts;
75
+ }
56
76
  hasReachedMaxAttempts() {
57
77
  if (this._maxReconnectAttempts === -1) return false;
58
78
  return this._currentReconnectAttempts >= this._maxReconnectAttempts;
@@ -62,27 +82,21 @@ class SseReconnectStrategy {
62
82
  }
63
83
  nextDelayMs(isError) {
64
84
  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
- }
85
+ const base = isError ? Math.min(this._retryInterval * Math.pow(2.0, this._backoffCounter++), this._maxRetryInterval) : Math.min(this._retryInterval, this._maxRetryInterval);
86
+ const randomFactor = 1.0 - this._jitterFactor + Math.random() * (2 * this._jitterFactor);
87
+ const delay = base * randomFactor;
76
88
 
77
- // Minimum floor of 1000ms enforced across all platforms
78
- return Math.max(delay * 1000.0, 1000.0);
89
+ // Minimum floor of 1000ms enforced across all platforms, capped at max 32-bit signed int for timer safety
90
+ const MAX_TIMER_MS = 2_147_483_647;
91
+ const ms = Number.isFinite(delay) ? delay * 1000.0 : MAX_TIMER_MS;
92
+ return Math.min(Math.max(ms, 1000.0), MAX_TIMER_MS);
79
93
  }
80
94
  reset() {
81
95
  this._backoffCounter = 0;
82
96
  this._currentReconnectAttempts = 0;
83
97
  }
84
98
  updateRetryInterval(retryMs) {
85
- if (!Number.isNaN(retryMs) && retryMs >= 0) {
99
+ if (isValidNonNegative(retryMs)) {
86
100
  this._retryInterval = retryMs / 1000.0;
87
101
  }
88
102
  }
@@ -101,6 +115,7 @@ export class FetchSseDriver {
101
115
  _batchBuffer = [];
102
116
  _wasRunningBeforeNetworkLoss = false;
103
117
  _reconnectStrategy = new SseReconnectStrategy();
118
+
104
119
  // === Stats tracking ===
105
120
  _rawBytesReceived = 0;
106
121
  _totalBytesReceived = 0;
@@ -155,7 +170,7 @@ export class FetchSseDriver {
155
170
  this._consecutiveAuthErrors = 0;
156
171
  this._connectionAttemptVersion++;
157
172
  this._updateState('connecting');
158
- this._establishConnection(this._connectionAttemptVersion);
173
+ this._establishConnection(this._connectionAttemptVersion, this._config);
159
174
  }
160
175
  return;
161
176
  }
@@ -165,12 +180,13 @@ export class FetchSseDriver {
165
180
  this._consecutiveAuthErrors = 0;
166
181
  this._reconnectStrategy.reset();
167
182
  this._connectionAttemptVersion++;
168
- this._establishConnection(this._connectionAttemptVersion);
183
+ this._establishConnection(this._connectionAttemptVersion, this._config);
169
184
  }
170
185
  stop() {
171
- if (this._isRunning) {
186
+ if (this._isRunning || this._wasRunningBeforeNetworkLoss) {
172
187
  this._disconnectReason = 'user_stop';
173
188
  }
189
+ this._wasRunningBeforeNetworkLoss = false;
174
190
  this._stopInternal(true);
175
191
  }
176
192
  restart() {
@@ -178,13 +194,14 @@ export class FetchSseDriver {
178
194
  return;
179
195
  }
180
196
  this._connectedAt = undefined;
181
- this._cleanupTimers();
182
- this._cleanupTransport();
183
- this._flushBatch();
197
+ this._teardownConnection();
184
198
  this._isRunning = true;
199
+ this._isReconnecting = true;
200
+ this._consecutiveAuthErrors = 0;
201
+ this._reconnectStrategy.reset();
185
202
  this._connectionAttemptVersion++;
186
203
  this._updateState('reconnecting');
187
- this._establishConnection(this._connectionAttemptVersion);
204
+ this._establishConnection(this._connectionAttemptVersion, this._config);
188
205
  }
189
206
  flush() {
190
207
  this._flushBatch();
@@ -240,27 +257,33 @@ export class FetchSseDriver {
240
257
  dispose() {
241
258
  this.stop();
242
259
  this._teardownNetworkListeners();
243
- this._batchBuffer = [];
244
260
  }
245
261
 
246
262
  // =========================================================================
247
263
  // Internal Connection Engine
248
264
  // =========================================================================
249
265
 
250
- async _establishConnection(attemptVersion) {
251
- if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion || !this._config) {
266
+ /**
267
+ * A connection attempt is stale when the driver has been stopped, or when a
268
+ * newer attempt (reconnect / restart / stop) has superseded it.
269
+ */
270
+ _isStale(attemptVersion) {
271
+ return !this._isRunning || attemptVersion !== this._connectionAttemptVersion;
272
+ }
273
+ async _establishConnection(attemptVersion, config) {
274
+ if (this._isStale(attemptVersion)) {
252
275
  return;
253
276
  }
254
277
  this._updateState('connecting');
255
278
  this._connectionAttempts++;
256
- this._connectionAttemptStartTime = Date.now();
279
+ const attemptStartTime = Date.now();
257
280
  this._timeToFirstByteMs = undefined;
258
281
 
259
282
  // 1. Prepare dynamic headers via interceptor if configured
260
283
  let dynamicInterceptorHeaders = {};
261
284
  if (this._onBeforeRequest) {
262
285
  try {
263
- const timeoutMs = this._config.connectionTimeoutMs ?? 15000;
286
+ const timeoutMs = config.connectionTimeoutMs ?? 15000;
264
287
  let interceptorTimer;
265
288
  try {
266
289
  dynamicInterceptorHeaders = await Promise.race([this._onBeforeRequest(), new Promise((_, reject) => {
@@ -272,30 +295,43 @@ export class FetchSseDriver {
272
295
  }
273
296
  }
274
297
  } catch (err) {
275
- if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
298
+ if (this._isStale(attemptVersion)) return;
276
299
  this._recordError('Interceptor Error', undefined);
277
- this._failAndStop(`Interceptor Error: ${err instanceof Error ? err.message : String(err)}`, -1);
300
+ const errorMsg = `Interceptor Error: ${err instanceof Error ? err.message : String(err)}`;
301
+ this._pushEvent({
302
+ type: 'error',
303
+ statusCode: -1,
304
+ message: errorMsg
305
+ });
306
+ this._consecutiveAuthErrors++;
307
+ const maxAuthRetries = config.maxAuthRetries ?? 3;
308
+ if (this._consecutiveAuthErrors > maxAuthRetries) {
309
+ this._disconnectReason = 'server_error';
310
+ this._failAndStop(`Auth retry limit reached (${maxAuthRetries}). Stopping.`, -1);
311
+ return;
312
+ }
313
+ this._scheduleReconnect(true, undefined, attemptVersion, config);
278
314
  return;
279
315
  }
280
316
  }
281
- if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
317
+ if (this._isStale(attemptVersion)) return;
282
318
 
283
319
  // URL syntax and protocol validation matching Native (http/https only)
284
320
  try {
285
- const parsedUrl = new URL(this._config.url, typeof window !== 'undefined' && window.location ? window.location.href : 'http://localhost');
321
+ const parsedUrl = new URL(config.url, typeof window !== 'undefined' && window.location ? window.location.href : 'http://localhost');
286
322
  if (!['http:', 'https:'].includes(parsedUrl.protocol)) {
287
- this._failAndStop(`Invalid URL: ${this._config.url}`, -1);
323
+ this._failAndStop(`Invalid URL: ${config.url}`, -1);
288
324
  return;
289
325
  }
290
326
  } catch {
291
- this._failAndStop(`Invalid URL: ${this._config.url}`, -1);
327
+ this._failAndStop(`Invalid URL: ${config.url}`, -1);
292
328
  return;
293
329
  }
294
330
 
295
331
  // 2. Build headers
296
332
  const filteredHeaders = {};
297
333
  for (const [k, v] of Object.entries({
298
- ...(this._config.headers ?? {}),
334
+ ...(config.headers ?? {}),
299
335
  ...this._dynamicHeaders,
300
336
  ...dynamicInterceptorHeaders
301
337
  })) {
@@ -309,19 +345,27 @@ export class FetchSseDriver {
309
345
  'Cache-Control': 'no-cache',
310
346
  ...filteredHeaders
311
347
  };
312
- if (this._lastProcessedId && this._lastProcessedId.length > 0) {
348
+ if (this._lastProcessedId) {
313
349
  mergedHeaders['Last-Event-ID'] = this._lastProcessedId;
314
350
  }
315
351
  const abortController = new AbortController();
316
352
  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();
353
+ const connectionTimeoutMs = config.connectionTimeoutMs ?? 15000;
354
+ const requestStartTime = Date.now();
355
+ let connectionTimer;
356
+ if (connectionTimeoutMs > 0) {
357
+ connectionTimer = setTimeout(() => {
358
+ if (this._connectionTimer === connectionTimer) {
359
+ this._connectionTimer = undefined;
360
+ }
361
+ if (attemptVersion === this._connectionAttemptVersion) {
362
+ this._disconnectReason = 'timeout';
363
+ abortController.abort();
364
+ }
365
+ }, connectionTimeoutMs);
366
+ this._connectionTimer = connectionTimer;
367
+ }
368
+ const method = (config.method ?? 'get').toUpperCase();
325
369
  const fetchOptions = {
326
370
  method,
327
371
  headers: mergedHeaders,
@@ -329,21 +373,24 @@ export class FetchSseDriver {
329
373
  mode: 'cors',
330
374
  credentials: 'same-origin'
331
375
  };
332
- if (method === 'POST') {
376
+ if (method === 'POST' && config.body) {
377
+ fetchOptions.body = config.body;
333
378
  const hasContentType = Object.keys(mergedHeaders).some(k => k.toLowerCase() === 'content-type');
334
- if (!hasContentType && this._config.body) {
379
+ if (!hasContentType) {
335
380
  mergedHeaders['Content-Type'] = 'application/json';
336
381
  }
337
- if (this._config.body) {
338
- fetchOptions.body = this._config.body;
339
- }
340
382
  }
341
383
  let response;
342
384
  try {
343
- response = await fetch(this._config.url, fetchOptions);
385
+ response = await fetch(config.url, fetchOptions);
344
386
  } catch (err) {
345
- clearTimeout(this._connectionTimer);
346
- if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
387
+ if (connectionTimer !== undefined) {
388
+ clearTimeout(connectionTimer);
389
+ if (this._connectionTimer === connectionTimer) {
390
+ this._connectionTimer = undefined;
391
+ }
392
+ }
393
+ if (this._isStale(attemptVersion)) return;
347
394
  const isAborted = abortController.signal.aborted;
348
395
  const errorMsg = isAborted ? 'Connection timeout' : err instanceof Error ? err.message : 'Failed to fetch';
349
396
  this._disconnectReason = isAborted ? 'timeout' : 'network_error';
@@ -355,27 +402,30 @@ export class FetchSseDriver {
355
402
  type: 'error',
356
403
  message: errorMsg
357
404
  });
358
- this._scheduleReconnect(true, undefined, attemptVersion);
405
+ this._scheduleReconnect(true, undefined, attemptVersion, config);
359
406
  return;
360
407
  }
361
- clearTimeout(this._connectionTimer);
362
- if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
408
+ if (connectionTimer !== undefined) {
409
+ clearTimeout(connectionTimer);
410
+ if (this._connectionTimer === connectionTimer) {
411
+ this._connectionTimer = undefined;
412
+ }
413
+ }
414
+ if (this._isStale(attemptVersion)) return;
363
415
  const statusCode = response.status;
364
416
  this._lastStatusCode = statusCode;
365
417
  let errorBody;
366
- if (statusCode >= 400 || statusCode === 204) {
367
- try {
368
- errorBody = await response.text();
369
- } catch {
370
- // Ignore body reading error
371
- }
418
+ if (statusCode >= 400) {
419
+ errorBody = await this._readBoundedErrorBody(response, connectionTimeoutMs, requestStartTime, abortController, attemptVersion);
420
+ if (this._isStale(attemptVersion)) return;
372
421
  }
373
422
 
374
423
  // 3. HTTP Validation Rules matching Native (WHATWG SSE Section 9.1)
375
424
  // 3a. HTTP 200 OK: Content-Type MIME type MUST be text/event-stream
376
425
  if (statusCode === 200) {
377
426
  const contentType = response.headers.get('Content-Type') ?? '';
378
- const mimeType = contentType.split(';')[0]?.trim().toLowerCase() ?? '';
427
+ const semiIdx = contentType.indexOf(';');
428
+ const mimeType = (semiIdx === -1 ? contentType : contentType.slice(0, semiIdx)).trim().toLowerCase();
379
429
  if (mimeType !== 'text/event-stream') {
380
430
  this._disconnectReason = 'server_error';
381
431
  this._failAndStop(`Invalid Content-Type: expected text/event-stream but received '${contentType}'. Stopping.`, statusCode);
@@ -388,25 +438,28 @@ export class FetchSseDriver {
388
438
  return;
389
439
  } else if (statusCode === 401 || statusCode === 403) {
390
440
  // 3c. HTTP 401/403 Auth errors
391
- const maxAuthRetries = this._config.maxAuthRetries ?? 3;
441
+ const maxAuthRetries = config.maxAuthRetries ?? 3;
392
442
  if (!this._onBeforeRequest) {
393
443
  this._disconnectReason = 'server_error';
394
- this._failAndStop(`Auth Error (${statusCode}) - No interceptor provided. Stopping.`, statusCode);
444
+ this._failAndStop(`Auth Error (${statusCode}) - No interceptor provided. Stopping.`, statusCode, errorBody);
395
445
  return;
396
446
  }
397
447
  this._consecutiveAuthErrors++;
398
448
  if (this._consecutiveAuthErrors > maxAuthRetries) {
399
449
  this._disconnectReason = 'server_error';
400
- this._failAndStop(`Auth Error (${statusCode}) - Retry limit reached (${maxAuthRetries}). Stopping.`, statusCode);
450
+ this._failAndStop(`Auth Error (${statusCode}) - Retry limit reached (${maxAuthRetries}). Stopping.`, statusCode, errorBody);
401
451
  return;
402
452
  }
403
453
  this._recordError(`Auth Error (${statusCode})`, String(statusCode));
404
454
  this._pushEvent({
405
455
  type: 'error',
406
456
  statusCode,
407
- message: `Auth Error (${statusCode}) - Retry ${this._consecutiveAuthErrors}/${maxAuthRetries}. Refreshing token...`
457
+ message: `Auth Error (${statusCode}) - Retry ${this._consecutiveAuthErrors}/${maxAuthRetries}. Refreshing token...`,
458
+ ...(errorBody !== undefined ? {
459
+ data: errorBody
460
+ } : {})
408
461
  });
409
- this._scheduleReconnect(true, undefined, attemptVersion);
462
+ this._scheduleReconnect(true, undefined, attemptVersion, config);
410
463
  return;
411
464
  } else if (statusCode === 408) {
412
465
  // 3d. Request Timeout: Recoverable per WHATWG SSE and Native specs
@@ -416,9 +469,12 @@ export class FetchSseDriver {
416
469
  this._pushEvent({
417
470
  type: 'error',
418
471
  statusCode: 408,
419
- message: 'HTTP 408'
472
+ message: 'HTTP 408',
473
+ ...(errorBody !== undefined ? {
474
+ data: errorBody
475
+ } : {})
420
476
  });
421
- this._scheduleReconnect(true, undefined, attemptVersion);
477
+ this._scheduleReconnect(true, undefined, attemptVersion, config);
422
478
  return;
423
479
  } else if (statusCode === 429 || statusCode === 503) {
424
480
  // 3e. Rate limit / Service unavailable: Honor Retry-After
@@ -427,52 +483,66 @@ export class FetchSseDriver {
427
483
  this._disconnectReason = 'server_error';
428
484
  this._recordError(`HTTP ${statusCode}`, String(statusCode));
429
485
  if (rawRetryAfterMs !== undefined) {
430
- const maxIntervalMs = this._config.maxRetryIntervalMs ?? 30000;
486
+ const maxIntervalMs = config.maxRetryIntervalMs ?? 30000;
431
487
  const boundedRetryMs = Math.max(0, Math.min(rawRetryAfterMs, maxIntervalMs));
488
+ const jitter = 500 + Math.floor(Math.random() * 1001); // 0.5s - 1.5s matching Native
489
+ const totalDelayMs = Math.max(1000, boundedRetryMs + jitter);
432
490
  this._pushEvent({
433
491
  type: 'error',
434
492
  statusCode,
435
- retry: boundedRetryMs,
436
- message: `Retry-After received: ${Math.round(boundedRetryMs / 1000)}s`
493
+ retry: totalDelayMs,
494
+ message: `Retry-After received: ${Math.round(totalDelayMs / 1000)}s`,
495
+ ...(errorBody !== undefined ? {
496
+ data: errorBody
497
+ } : {})
437
498
  });
438
- this._scheduleReconnect(true, boundedRetryMs, attemptVersion);
499
+ this._scheduleReconnect(true, totalDelayMs, attemptVersion, config);
439
500
  return;
440
501
  }
441
502
  if (statusCode === 429) {
442
503
  this._pushEvent({
443
504
  type: 'error',
444
505
  statusCode: 429,
445
- message: 'Rate Limited (429). Retrying with backoff...'
506
+ message: 'Rate Limited (429). Retrying with backoff...',
507
+ ...(errorBody !== undefined ? {
508
+ data: errorBody
509
+ } : {})
446
510
  });
447
- this._scheduleReconnect(true, undefined, attemptVersion);
511
+ this._scheduleReconnect(true, undefined, attemptVersion, config);
448
512
  return;
449
513
  }
450
514
  this._pushEvent({
451
515
  type: 'error',
452
516
  statusCode,
453
- message: `HTTP ${statusCode}`
517
+ message: `HTTP ${statusCode}`,
518
+ ...(errorBody !== undefined ? {
519
+ data: errorBody
520
+ } : {})
454
521
  });
455
- this._scheduleReconnect(true, undefined, attemptVersion);
522
+ this._scheduleReconnect(true, undefined, attemptVersion, config);
456
523
  return;
457
524
  } else if (statusCode >= 400 && statusCode <= 499) {
458
525
  // 3f. Fatal client error (e.g. 400 Bad Request, 404 Not Found, 405 Method Not Allowed)
459
526
  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);
527
+ const bodyPreview = formatErrorBodyPreview(errorBody);
528
+ const fatalMessage = bodyPreview ? `Fatal Error (${statusCode}): ${bodyPreview}` : `Fatal Error (${statusCode}). Stopping.`;
529
+ this._failAndStop(fatalMessage, statusCode, errorBody);
463
530
  return;
464
531
  } else if (statusCode >= 500) {
465
532
  // 3g. Server error: Recoverable
466
533
  this._disconnectReason = 'server_error';
467
534
  this._recordError(`Server Error (${statusCode})`, String(statusCode));
468
- const bodyText = errorBody?.trim();
469
- const errorMsg = bodyText ? `Server Error (${statusCode}): ${bodyText}` : `Server Error (${statusCode})`;
535
+ const bodyPreview = formatErrorBodyPreview(errorBody);
536
+ const errorMsg = bodyPreview ? `Server Error (${statusCode}): ${bodyPreview}` : `Server Error (${statusCode})`;
470
537
  this._pushEvent({
471
538
  type: 'error',
472
539
  statusCode,
473
- message: errorMsg
540
+ message: errorMsg,
541
+ ...(errorBody !== undefined ? {
542
+ data: errorBody
543
+ } : {})
474
544
  });
475
- this._scheduleReconnect(true, undefined, attemptVersion);
545
+ this._scheduleReconnect(true, undefined, attemptVersion, config);
476
546
  return;
477
547
  } else {
478
548
  // Any other non-200 status code (e.g. 201 Created, 202, 3xx) is fatal per WHATWG SSE Section 9.1
@@ -488,51 +558,60 @@ export class FetchSseDriver {
488
558
  // 4. Connection established successfully
489
559
  this._reconnectStrategy.reset();
490
560
  this._consecutiveAuthErrors = 0;
491
- if (this._isReconnecting || this._state === 'reconnecting') {
561
+ if (this._isReconnecting) {
492
562
  this._reconnectCount++;
493
563
  this._isReconnecting = false;
494
564
  }
495
565
  this._connectedAt = Date.now();
496
566
  this._updateState('open');
567
+ if (this._isStale(attemptVersion)) return;
497
568
  this._pushEvent({
498
569
  type: 'open',
499
570
  statusCode
500
571
  });
572
+ if (this._isStale(attemptVersion)) return;
501
573
 
502
574
  // 5. Initialize streaming reader and parser
503
- this._parser = new SseEventParser(this, this._lastProcessedId);
575
+ const parser = new SseEventParser(this, this._lastProcessedId);
576
+ this._activeParser = parser;
504
577
  const reader = response.body.getReader();
505
578
  this._activeReader = reader;
506
579
  const decoder = new TextDecoder('utf-8');
507
580
 
508
581
  // 6. Setup idle read timeout
509
- this._resetReadTimeout(attemptVersion);
582
+ this._resetReadTimeout(attemptVersion, config);
510
583
  try {
511
- while (this._isRunning && attemptVersion === this._connectionAttemptVersion) {
584
+ while (!this._isStale(attemptVersion)) {
512
585
  const {
513
586
  value,
514
587
  done
515
588
  } = await reader.read();
589
+ if (this._isStale(attemptVersion)) {
590
+ break;
591
+ }
516
592
  if (done) {
517
- decoder.decode(); // flush trailing bytes
518
- this._parser?.endOfStream();
593
+ const tail = decoder.decode();
594
+ if (tail) {
595
+ parser.feed(tail);
596
+ }
597
+ parser.endOfStream();
519
598
  break;
520
599
  }
521
600
  if (value) {
522
- if (this._timeToFirstByteMs === undefined && this._connectionAttemptStartTime) {
523
- this._timeToFirstByteMs = Date.now() - this._connectionAttemptStartTime;
601
+ if (this._timeToFirstByteMs === undefined) {
602
+ this._timeToFirstByteMs = Date.now() - attemptStartTime;
524
603
  }
525
604
  this._rawBytesReceived += value.byteLength;
526
605
  this._chunksReceived++;
527
- this._resetReadTimeout(attemptVersion);
606
+ this._resetReadTimeout(attemptVersion, config);
528
607
  const text = decoder.decode(value, {
529
608
  stream: true
530
609
  });
531
- this._parser?.feed(text);
610
+ parser.feed(text);
532
611
  }
533
612
  }
534
613
  } catch (readErr) {
535
- if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
614
+ if (this._isStale(attemptVersion)) return;
536
615
  const isAborted = abortController.signal.aborted;
537
616
  if (!isAborted) {
538
617
  const errorMsg = readErr instanceof Error ? readErr.message : 'Read error';
@@ -542,27 +621,26 @@ export class FetchSseDriver {
542
621
  type: 'error',
543
622
  message: errorMsg
544
623
  });
545
- this._scheduleReconnect(true, undefined, attemptVersion);
624
+ this._scheduleReconnect(true, undefined, attemptVersion, config);
546
625
  return;
547
626
  }
548
627
  } finally {
549
628
  this._clearReadTimeout();
550
629
  }
551
- if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
630
+ if (this._isStale(attemptVersion)) return;
552
631
 
553
632
  // Clean disconnect from server
554
- this._scheduleReconnect(false, undefined, attemptVersion);
633
+ this._scheduleReconnect(false, undefined, attemptVersion, config);
555
634
  }
556
635
 
557
636
  // =========================================================================
558
637
  // Reconnect & Teardown Helpers
559
638
  // =========================================================================
560
639
 
561
- _scheduleReconnect(isError, fixedDelayMs, attemptVersion) {
562
- if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
640
+ _scheduleReconnect(isError, fixedDelayMs, attemptVersion, config) {
641
+ if (this._isStale(attemptVersion)) return;
563
642
  if (this._reconnectStrategy.hasReachedMaxAttempts()) {
564
- const maxAttempts = this._config?.maxReconnectAttempts ?? -1;
565
- this._failAndStop(`Max reconnection attempts reached (${maxAttempts}).`);
643
+ this._failAndStop(`Max reconnection attempts reached (${this._reconnectStrategy.maxReconnectAttempts}).`);
566
644
  return;
567
645
  }
568
646
  let delay;
@@ -579,8 +657,9 @@ export class FetchSseDriver {
579
657
  this._updateState('reconnecting');
580
658
  this._cleanupTransport();
581
659
  this._reconnectTimer = setTimeout(() => {
582
- if (this._isRunning && newVersion === this._connectionAttemptVersion) {
583
- this._establishConnection(newVersion);
660
+ this._reconnectTimer = undefined;
661
+ if (!this._isStale(newVersion)) {
662
+ this._establishConnection(newVersion, config);
584
663
  }
585
664
  }, delay);
586
665
  }
@@ -588,27 +667,37 @@ export class FetchSseDriver {
588
667
  this._connectedAt = undefined;
589
668
  this._isRunning = false;
590
669
  this._isReconnecting = false;
670
+ this._wasRunningBeforeNetworkLoss = false;
671
+ this._reconnectStrategy.reset();
591
672
  this._connectionAttemptVersion++;
592
- this._cleanupTimers();
593
- this._cleanupTransport();
594
- this._flushBatch();
673
+ this._teardownConnection();
595
674
  if (emitClosed && this._state !== 'failed') {
596
675
  this._updateState('closed');
597
- this._flushBatch();
598
676
  }
599
677
  }
600
- _failAndStop(message, statusCode) {
601
- this._connectionAttemptVersion++;
678
+ _failAndStop(message, statusCode, data) {
602
679
  this._recordError(message, statusCode !== undefined ? String(statusCode) : undefined);
603
680
  this._pushEvent({
604
681
  type: 'error',
605
682
  message,
606
- statusCode
683
+ statusCode,
684
+ ...(data !== undefined ? {
685
+ data
686
+ } : {})
607
687
  });
608
688
  this._updateState('failed');
609
689
  this._stopInternal(false);
610
690
  }
691
+ _teardownConnection() {
692
+ this._cleanupTimers();
693
+ this._cleanupTransport();
694
+ this._flushBatch();
695
+ }
611
696
  _cleanupTransport() {
697
+ if (this._activeParser) {
698
+ this._activeParser.abort();
699
+ this._activeParser = undefined;
700
+ }
612
701
  if (this._activeReader) {
613
702
  try {
614
703
  this._activeReader.cancel().catch(() => {});
@@ -626,11 +715,150 @@ export class FetchSseDriver {
626
715
  this._abortController = undefined;
627
716
  }
628
717
  }
718
+ async _readBoundedErrorBody(response, connectionTimeoutMs, requestStartTime, abortController, attemptVersion) {
719
+ const effectiveTimeoutMs = connectionTimeoutMs > 0 ? connectionTimeoutMs : 15000;
720
+ const remainingTimeoutMs = Math.max(0, effectiveTimeoutMs - (Date.now() - requestStartTime));
721
+ if (remainingTimeoutMs <= 0) {
722
+ try {
723
+ response.body?.cancel?.().catch(() => {});
724
+ } catch {
725
+ // Ignore cancellation errors
726
+ }
727
+ return undefined;
728
+ }
729
+ if (response.body && typeof response.body.getReader === 'function') {
730
+ const reader = response.body.getReader();
731
+ this._activeReader = reader;
732
+ const chunks = [];
733
+ let totalBytes = 0;
734
+ let timedOut = false;
735
+ let streamTimer;
736
+ const timeoutPromise = new Promise(resolve => {
737
+ streamTimer = setTimeout(() => {
738
+ if (this._errorBodyTimer === streamTimer) {
739
+ this._errorBodyTimer = undefined;
740
+ }
741
+ timedOut = true;
742
+ resolve({
743
+ value: undefined,
744
+ done: true
745
+ });
746
+ try {
747
+ reader.cancel().catch(() => {});
748
+ } catch {
749
+ // Ignore reader cancellation errors
750
+ }
751
+ try {
752
+ abortController.abort();
753
+ } catch {
754
+ // Ignore abort errors
755
+ }
756
+ }, remainingTimeoutMs);
757
+ this._errorBodyTimer = streamTimer;
758
+ });
759
+ try {
760
+ while (totalBytes < MAX_ERROR_BODY_BYTES && !timedOut && !this._isStale(attemptVersion)) {
761
+ const {
762
+ value,
763
+ done
764
+ } = await Promise.race([reader.read(), timeoutPromise]);
765
+ if (timedOut || this._isStale(attemptVersion) || done) {
766
+ break;
767
+ }
768
+ if (value && value.byteLength > 0) {
769
+ const remaining = MAX_ERROR_BODY_BYTES - totalBytes;
770
+ const slice = value.byteLength > remaining ? value.subarray(0, remaining) : value;
771
+ chunks.push(slice);
772
+ totalBytes += slice.byteLength;
773
+ }
774
+ }
775
+ } catch {
776
+ // Preserve already-buffered partial error body bytes before disconnect/abort
777
+ } finally {
778
+ if (streamTimer !== undefined) {
779
+ clearTimeout(streamTimer);
780
+ if (this._errorBodyTimer === streamTimer) {
781
+ this._errorBodyTimer = undefined;
782
+ }
783
+ }
784
+ if (this._activeReader === reader) {
785
+ this._activeReader = undefined;
786
+ }
787
+ try {
788
+ reader.cancel().catch(() => {});
789
+ } catch {
790
+ // Ignore reader cancellation errors
791
+ }
792
+ try {
793
+ reader.releaseLock();
794
+ } catch {
795
+ // Ignore releaseLock errors
796
+ }
797
+ }
798
+ if (this._isStale(attemptVersion) || totalBytes === 0) {
799
+ return undefined;
800
+ }
801
+ let combined;
802
+ if (chunks.length === 1 && chunks[0]) {
803
+ combined = chunks[0];
804
+ } else {
805
+ combined = new Uint8Array(totalBytes);
806
+ let offset = 0;
807
+ for (const chunk of chunks) {
808
+ combined.set(chunk, offset);
809
+ offset += chunk.byteLength;
810
+ }
811
+ }
812
+ const decoded = new TextDecoder('utf-8').decode(combined);
813
+ return decoded.length > 0 ? decoded : undefined;
814
+ }
815
+
816
+ // Fallback for environments without ReadableStream body support
817
+ let fallbackTimer;
818
+ const fallbackTimeoutPromise = new Promise(resolve => {
819
+ fallbackTimer = setTimeout(() => {
820
+ if (this._errorBodyTimer === fallbackTimer) {
821
+ this._errorBodyTimer = undefined;
822
+ }
823
+ resolve(undefined);
824
+ try {
825
+ abortController.abort();
826
+ } catch {
827
+ // Ignore abort errors
828
+ }
829
+ }, remainingTimeoutMs);
830
+ this._errorBodyTimer = fallbackTimer;
831
+ });
832
+ let raw;
833
+ try {
834
+ raw = await Promise.race([response.text(), fallbackTimeoutPromise]);
835
+ } catch {
836
+ // Ignore body reading error
837
+ } finally {
838
+ if (fallbackTimer !== undefined) {
839
+ clearTimeout(fallbackTimer);
840
+ if (this._errorBodyTimer === fallbackTimer) {
841
+ this._errorBodyTimer = undefined;
842
+ }
843
+ }
844
+ }
845
+ if (this._isStale(attemptVersion) || !raw) {
846
+ return undefined;
847
+ }
848
+ const encoded = new TextEncoder().encode(raw);
849
+ const bounded = encoded.byteLength > MAX_ERROR_BODY_BYTES ? encoded.subarray(0, MAX_ERROR_BODY_BYTES) : encoded;
850
+ const decoded = new TextDecoder('utf-8').decode(bounded);
851
+ return decoded.length > 0 ? decoded : undefined;
852
+ }
629
853
  _cleanupTimers() {
630
854
  if (this._connectionTimer) {
631
855
  clearTimeout(this._connectionTimer);
632
856
  this._connectionTimer = undefined;
633
857
  }
858
+ if (this._errorBodyTimer) {
859
+ clearTimeout(this._errorBodyTimer);
860
+ this._errorBodyTimer = undefined;
861
+ }
634
862
  if (this._readTimeoutTimer) {
635
863
  clearTimeout(this._readTimeoutTimer);
636
864
  this._readTimeoutTimer = undefined;
@@ -639,17 +867,14 @@ export class FetchSseDriver {
639
867
  clearTimeout(this._reconnectTimer);
640
868
  this._reconnectTimer = undefined;
641
869
  }
642
- if (this._batchTimer) {
643
- clearTimeout(this._batchTimer);
644
- this._batchTimer = undefined;
645
- }
646
870
  }
647
- _resetReadTimeout(attemptVersion) {
871
+ _resetReadTimeout(attemptVersion, config = this._config) {
648
872
  this._clearReadTimeout();
649
- const readTimeoutMs = this._config?.readTimeoutMs ?? 300000;
873
+ const readTimeoutMs = config.readTimeoutMs ?? 300000;
650
874
  if (readTimeoutMs <= 0) return;
651
875
  this._readTimeoutTimer = setTimeout(() => {
652
- if (this._isRunning && attemptVersion === this._connectionAttemptVersion) {
876
+ this._readTimeoutTimer = undefined;
877
+ if (!this._isStale(attemptVersion)) {
653
878
  this._disconnectReason = 'timeout';
654
879
  this._updateState('stale');
655
880
  const errorMsg = 'Read timeout';
@@ -658,8 +883,7 @@ export class FetchSseDriver {
658
883
  type: 'error',
659
884
  message: errorMsg
660
885
  });
661
- this._cleanupTransport();
662
- this._scheduleReconnect(true, undefined, attemptVersion);
886
+ this._scheduleReconnect(true, undefined, attemptVersion, config);
663
887
  }
664
888
  }, readTimeoutMs);
665
889
  }
@@ -703,17 +927,15 @@ export class FetchSseDriver {
703
927
 
704
928
  _pushEvent(event) {
705
929
  const batchingIntervalMs = this._config?.batchingIntervalMs ?? 0;
706
- const maxBufferSize = this._config?.maxBufferSize ?? 1000;
930
+ const maxBufferSize = resolveMaxBufferSize(this._config?.maxBufferSize);
707
931
  this._batchBuffer.push(event);
708
932
  if (this._batchBuffer.length > this._peakBufferedEvents) {
709
933
  this._peakBufferedEvents = this._batchBuffer.length;
710
934
  }
711
- if (this._batchBuffer.length >= maxBufferSize && batchingIntervalMs > 0) {
712
- this._bufferOverflowCount++;
713
- this._cancelBatchTimer();
935
+ if (batchingIntervalMs <= 0) {
714
936
  this._flushBatch();
715
- } else if (this._batchBuffer.length >= maxBufferSize || batchingIntervalMs <= 0) {
716
- this._cancelBatchTimer();
937
+ } else if (this._batchBuffer.length >= maxBufferSize) {
938
+ this._bufferOverflowCount++;
717
939
  this._flushBatch();
718
940
  } else if (!this._batchTimer) {
719
941
  this._batchTimer = setTimeout(() => {
@@ -736,37 +958,34 @@ export class FetchSseDriver {
736
958
  this._batchTimer = undefined;
737
959
  }
738
960
  }
961
+ _recordActivity(now) {
962
+ if (this._lastActivityTime > 0) {
963
+ const gap = now - this._lastActivityTime;
964
+ if (gap > this._maxEventGapMs) {
965
+ this._maxEventGapMs = gap;
966
+ }
967
+ }
968
+ this._lastActivityTime = now;
969
+ }
739
970
 
740
971
  // =========================================================================
741
972
  // SseEventParserDelegate Implementation
742
973
  // =========================================================================
743
974
 
744
975
  onEvent(id, type, data) {
976
+ if (!this._isRunning) return;
745
977
  const now = Date.now();
746
978
  this._lastEventTime = now;
747
- if (this._lastActivityTime > 0) {
748
- const gap = now - this._lastActivityTime;
749
- if (gap > this._maxEventGapMs) {
750
- this._maxEventGapMs = gap;
751
- }
752
- }
753
- this._lastActivityTime = now;
979
+ this._recordActivity(now);
754
980
  const eventType = type ?? 'message';
755
981
  const encodedDataSize = getUtf8ByteCount(data);
756
982
  const eventTypeSize = eventType === 'message' ? 0 : getUtf8ByteCount(eventType);
757
983
  this._totalBytesReceived += encodedDataSize + eventTypeSize;
758
- if (id !== undefined && id !== this._lastProcessedId) {
759
- this._totalBytesReceived += getUtf8ByteCount(id);
760
- this._lastProcessedId = id;
761
- }
762
984
  this._totalEventsReceived++;
763
985
  let parsedData;
764
- if (this._config?.autoParseJSON && data.trimStart().startsWith('{')) {
986
+ if (this._config?.autoParseJSON && /^\s*\{/.test(data)) {
765
987
  try {
766
- const obj = JSON.parse(data);
767
- if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
768
- parsedData = obj;
769
- }
988
+ parsedData = JSON.parse(data);
770
989
  } catch {
771
990
  // Ignore JSON parsing failures
772
991
  }
@@ -781,15 +1000,10 @@ export class FetchSseDriver {
781
1000
  });
782
1001
  }
783
1002
  onComment(comment) {
1003
+ if (!this._isRunning) return;
784
1004
  const now = Date.now();
785
1005
  this._lastHeartbeatTime = now;
786
- if (this._lastActivityTime > 0) {
787
- const gap = now - this._lastActivityTime;
788
- if (gap > this._maxEventGapMs) {
789
- this._maxEventGapMs = gap;
790
- }
791
- }
792
- this._lastActivityTime = now;
1006
+ this._recordActivity(now);
793
1007
  this._totalBytesReceived += getUtf8ByteCount(comment);
794
1008
  this._commentsReceived++;
795
1009
  this._pushEvent({
@@ -798,21 +1012,25 @@ export class FetchSseDriver {
798
1012
  });
799
1013
  }
800
1014
  onRetry(retryMs) {
1015
+ if (!this._isRunning) return;
801
1016
  this._serverRetryDelayMs = retryMs;
802
1017
  this._reconnectStrategy.updateRetryInterval(retryMs);
803
1018
  }
804
1019
  onIdUpdate(id) {
1020
+ if (!this._isRunning) return;
805
1021
  if (id !== undefined && id !== this._lastProcessedId) {
806
1022
  this._totalBytesReceived += getUtf8ByteCount(id);
807
1023
  }
808
1024
  this._lastProcessedId = id;
809
1025
  }
810
1026
  onParseError(error) {
1027
+ if (!this._isRunning) return;
811
1028
  this._parseErrors++;
812
1029
  this._disconnectReason = 'parser_error';
813
1030
  this._failAndStop(`SSE parser error: ${error.message}`);
814
1031
  }
815
1032
  onLinesParsed(count) {
1033
+ if (!this._isRunning) return;
816
1034
  this._linesParsed += count;
817
1035
  }
818
1036
 
@@ -821,37 +1039,35 @@ export class FetchSseDriver {
821
1039
  // =========================================================================
822
1040
 
823
1041
  _setupNetworkListeners() {
824
- if (typeof window === 'undefined' || typeof window.addEventListener !== 'function' || this._offlineListener !== undefined) return;
825
- this._offlineListener = () => {
1042
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function' || this._removeNetworkListeners !== undefined) return;
1043
+ const offlineListener = () => {
826
1044
  if (this._isRunning) {
827
1045
  this._wasRunningBeforeNetworkLoss = true;
828
1046
  this._disconnectReason = 'network_error';
829
1047
  this._connectionAttemptVersion++;
830
- this._cleanupTimers();
831
- this._cleanupTransport();
1048
+ this._teardownConnection();
832
1049
  this._updateState('paused');
833
1050
  this._isRunning = false;
834
1051
  }
835
1052
  };
836
- this._onlineListener = () => {
1053
+ const onlineListener = () => {
837
1054
  if (this._wasRunningBeforeNetworkLoss) {
838
1055
  this._wasRunningBeforeNetworkLoss = false;
839
1056
  this.start();
840
1057
  }
841
1058
  };
842
- window.addEventListener('offline', this._offlineListener);
843
- window.addEventListener('online', this._onlineListener);
1059
+ const target = window;
1060
+ target.addEventListener('offline', offlineListener);
1061
+ target.addEventListener('online', onlineListener);
1062
+ this._removeNetworkListeners = () => {
1063
+ target.removeEventListener('offline', offlineListener);
1064
+ target.removeEventListener('online', onlineListener);
1065
+ };
844
1066
  }
845
1067
  _teardownNetworkListeners() {
846
- if (typeof window === 'undefined' || typeof window.removeEventListener !== 'function') return;
847
- if (this._offlineListener) {
848
- window.removeEventListener('offline', this._offlineListener);
849
- this._offlineListener = undefined;
850
- }
851
- if (this._onlineListener) {
852
- window.removeEventListener('online', this._onlineListener);
853
- this._onlineListener = undefined;
854
- }
1068
+ if (typeof window === 'undefined' || typeof window.removeEventListener !== 'function' || !this._removeNetworkListeners) return;
1069
+ this._removeNetworkListeners();
1070
+ this._removeNetworkListeners = undefined;
855
1071
  }
856
1072
  }
857
1073
  //# sourceMappingURL=FetchSseDriver.js.map