react-native-nitro-sse 3.1.0 → 3.2.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.
@@ -0,0 +1,857 @@
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
+ const errorMsg = readErr instanceof Error ? readErr.message : 'Read error';
539
+ this._disconnectReason = 'network_error';
540
+ this._recordError(errorMsg, undefined);
541
+ this._pushEvent({
542
+ type: 'error',
543
+ message: errorMsg
544
+ });
545
+ this._scheduleReconnect(true, undefined, attemptVersion);
546
+ return;
547
+ }
548
+ } finally {
549
+ this._clearReadTimeout();
550
+ }
551
+ if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
552
+
553
+ // Clean disconnect from server
554
+ this._scheduleReconnect(false, undefined, attemptVersion);
555
+ }
556
+
557
+ // =========================================================================
558
+ // Reconnect & Teardown Helpers
559
+ // =========================================================================
560
+
561
+ _scheduleReconnect(isError, fixedDelayMs, attemptVersion) {
562
+ if (!this._isRunning || attemptVersion !== this._connectionAttemptVersion) return;
563
+ if (this._reconnectStrategy.hasReachedMaxAttempts()) {
564
+ const maxAttempts = this._config?.maxReconnectAttempts ?? -1;
565
+ this._failAndStop(`Max reconnection attempts reached (${maxAttempts}).`);
566
+ return;
567
+ }
568
+ let delay;
569
+ if (fixedDelayMs !== undefined) {
570
+ this._reconnectStrategy.recordAttempt();
571
+ delay = fixedDelayMs;
572
+ } else {
573
+ delay = this._reconnectStrategy.nextDelayMs(isError);
574
+ }
575
+ this._lastReconnectDelayMs = delay;
576
+ this._connectionAttemptVersion++;
577
+ const newVersion = this._connectionAttemptVersion;
578
+ this._isReconnecting = true;
579
+ this._updateState('reconnecting');
580
+ this._cleanupTransport();
581
+ this._reconnectTimer = setTimeout(() => {
582
+ if (this._isRunning && newVersion === this._connectionAttemptVersion) {
583
+ this._establishConnection(newVersion);
584
+ }
585
+ }, delay);
586
+ }
587
+ _stopInternal(emitClosed) {
588
+ this._connectedAt = undefined;
589
+ this._isRunning = false;
590
+ this._isReconnecting = false;
591
+ this._connectionAttemptVersion++;
592
+ this._cleanupTimers();
593
+ this._cleanupTransport();
594
+ this._flushBatch();
595
+ if (emitClosed && this._state !== 'failed') {
596
+ this._updateState('closed');
597
+ this._flushBatch();
598
+ }
599
+ }
600
+ _failAndStop(message, statusCode) {
601
+ this._connectionAttemptVersion++;
602
+ this._recordError(message, statusCode !== undefined ? String(statusCode) : undefined);
603
+ this._pushEvent({
604
+ type: 'error',
605
+ message,
606
+ statusCode
607
+ });
608
+ this._updateState('failed');
609
+ this._stopInternal(false);
610
+ }
611
+ _cleanupTransport() {
612
+ if (this._activeReader) {
613
+ try {
614
+ this._activeReader.cancel().catch(() => {});
615
+ } catch {
616
+ // Ignore reader cancellation errors
617
+ }
618
+ this._activeReader = undefined;
619
+ }
620
+ if (this._abortController) {
621
+ try {
622
+ this._abortController.abort();
623
+ } catch {
624
+ // Ignore abort errors
625
+ }
626
+ this._abortController = undefined;
627
+ }
628
+ }
629
+ _cleanupTimers() {
630
+ if (this._connectionTimer) {
631
+ clearTimeout(this._connectionTimer);
632
+ this._connectionTimer = undefined;
633
+ }
634
+ if (this._readTimeoutTimer) {
635
+ clearTimeout(this._readTimeoutTimer);
636
+ this._readTimeoutTimer = undefined;
637
+ }
638
+ if (this._reconnectTimer) {
639
+ clearTimeout(this._reconnectTimer);
640
+ this._reconnectTimer = undefined;
641
+ }
642
+ if (this._batchTimer) {
643
+ clearTimeout(this._batchTimer);
644
+ this._batchTimer = undefined;
645
+ }
646
+ }
647
+ _resetReadTimeout(attemptVersion) {
648
+ this._clearReadTimeout();
649
+ const readTimeoutMs = this._config?.readTimeoutMs ?? 300000;
650
+ if (readTimeoutMs <= 0) return;
651
+ this._readTimeoutTimer = setTimeout(() => {
652
+ if (this._isRunning && attemptVersion === this._connectionAttemptVersion) {
653
+ this._disconnectReason = 'timeout';
654
+ this._updateState('stale');
655
+ const errorMsg = 'Read timeout';
656
+ this._recordError(errorMsg, undefined);
657
+ this._pushEvent({
658
+ type: 'error',
659
+ message: errorMsg
660
+ });
661
+ this._cleanupTransport();
662
+ this._scheduleReconnect(true, undefined, attemptVersion);
663
+ }
664
+ }, readTimeoutMs);
665
+ }
666
+ _clearReadTimeout() {
667
+ if (this._readTimeoutTimer) {
668
+ clearTimeout(this._readTimeoutTimer);
669
+ this._readTimeoutTimer = undefined;
670
+ }
671
+ }
672
+ _updateState(newState) {
673
+ if (this._state === newState) return;
674
+ this._state = newState;
675
+ this._pushEvent({
676
+ type: 'state',
677
+ state: newState
678
+ });
679
+ this._flushBatch();
680
+ }
681
+ _recordError(message, code) {
682
+ this._lastErrorTime = Date.now();
683
+ this._lastErrorCode = code ?? message;
684
+ }
685
+ _parseRetryAfterHeader(value) {
686
+ if (!value) return undefined;
687
+ const trimmed = value.trim();
688
+ if (/^[0-9]+$/.test(trimmed)) {
689
+ const seconds = parseInt(trimmed, 10);
690
+ return seconds * 1000;
691
+ }
692
+ const timestamp = Date.parse(trimmed);
693
+ if (!Number.isNaN(timestamp)) {
694
+ const diff = timestamp - Date.now();
695
+ return Math.max(diff, 1000);
696
+ }
697
+ return undefined;
698
+ }
699
+
700
+ // =========================================================================
701
+ // Batching & Dispatching
702
+ // =========================================================================
703
+
704
+ _pushEvent(event) {
705
+ const batchingIntervalMs = this._config?.batchingIntervalMs ?? 0;
706
+ const maxBufferSize = this._config?.maxBufferSize ?? 1000;
707
+ this._batchBuffer.push(event);
708
+ if (this._batchBuffer.length > this._peakBufferedEvents) {
709
+ this._peakBufferedEvents = this._batchBuffer.length;
710
+ }
711
+ if (this._batchBuffer.length >= maxBufferSize && batchingIntervalMs > 0) {
712
+ this._bufferOverflowCount++;
713
+ this._cancelBatchTimer();
714
+ this._flushBatch();
715
+ } else if (this._batchBuffer.length >= maxBufferSize || batchingIntervalMs <= 0) {
716
+ this._cancelBatchTimer();
717
+ this._flushBatch();
718
+ } else if (!this._batchTimer) {
719
+ this._batchTimer = setTimeout(() => {
720
+ this._batchTimer = undefined;
721
+ this._flushBatch();
722
+ }, batchingIntervalMs);
723
+ }
724
+ }
725
+ _flushBatch() {
726
+ this._cancelBatchTimer();
727
+ if (this._batchBuffer.length === 0) return;
728
+ this._bufferFlushCount++;
729
+ const batch = this._batchBuffer;
730
+ this._batchBuffer = [];
731
+ this._dispatchEvents(batch);
732
+ }
733
+ _cancelBatchTimer() {
734
+ if (this._batchTimer) {
735
+ clearTimeout(this._batchTimer);
736
+ this._batchTimer = undefined;
737
+ }
738
+ }
739
+
740
+ // =========================================================================
741
+ // SseEventParserDelegate Implementation
742
+ // =========================================================================
743
+
744
+ onEvent(id, type, data) {
745
+ const now = Date.now();
746
+ 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;
754
+ const eventType = type ?? 'message';
755
+ const encodedDataSize = getUtf8ByteCount(data);
756
+ const eventTypeSize = eventType === 'message' ? 0 : getUtf8ByteCount(eventType);
757
+ this._totalBytesReceived += encodedDataSize + eventTypeSize;
758
+ if (id !== undefined && id !== this._lastProcessedId) {
759
+ this._totalBytesReceived += getUtf8ByteCount(id);
760
+ this._lastProcessedId = id;
761
+ }
762
+ this._totalEventsReceived++;
763
+ let parsedData;
764
+ if (this._config?.autoParseJSON && data.trimStart().startsWith('{')) {
765
+ try {
766
+ const obj = JSON.parse(data);
767
+ if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
768
+ parsedData = obj;
769
+ }
770
+ } catch {
771
+ // Ignore JSON parsing failures
772
+ }
773
+ }
774
+ this._pushEvent({
775
+ type: 'message',
776
+ data,
777
+ parsedData,
778
+ id: id ?? this._lastProcessedId,
779
+ event: type,
780
+ statusCode: 200
781
+ });
782
+ }
783
+ onComment(comment) {
784
+ const now = Date.now();
785
+ 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;
793
+ this._totalBytesReceived += getUtf8ByteCount(comment);
794
+ this._commentsReceived++;
795
+ this._pushEvent({
796
+ type: 'heartbeat',
797
+ message: comment
798
+ });
799
+ }
800
+ onRetry(retryMs) {
801
+ this._serverRetryDelayMs = retryMs;
802
+ this._reconnectStrategy.updateRetryInterval(retryMs);
803
+ }
804
+ onIdUpdate(id) {
805
+ if (id !== undefined && id !== this._lastProcessedId) {
806
+ this._totalBytesReceived += getUtf8ByteCount(id);
807
+ }
808
+ this._lastProcessedId = id;
809
+ }
810
+ onParseError(error) {
811
+ this._parseErrors++;
812
+ this._disconnectReason = 'parser_error';
813
+ this._failAndStop(`SSE parser error: ${error.message}`);
814
+ }
815
+ onLinesParsed(count) {
816
+ this._linesParsed += count;
817
+ }
818
+
819
+ // =========================================================================
820
+ // Network Monitoring
821
+ // =========================================================================
822
+
823
+ _setupNetworkListeners() {
824
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function' || this._offlineListener !== undefined) return;
825
+ this._offlineListener = () => {
826
+ if (this._isRunning) {
827
+ this._wasRunningBeforeNetworkLoss = true;
828
+ this._disconnectReason = 'network_error';
829
+ this._connectionAttemptVersion++;
830
+ this._cleanupTimers();
831
+ this._cleanupTransport();
832
+ this._updateState('paused');
833
+ this._isRunning = false;
834
+ }
835
+ };
836
+ this._onlineListener = () => {
837
+ if (this._wasRunningBeforeNetworkLoss) {
838
+ this._wasRunningBeforeNetworkLoss = false;
839
+ this.start();
840
+ }
841
+ };
842
+ window.addEventListener('offline', this._offlineListener);
843
+ window.addEventListener('online', this._onlineListener);
844
+ }
845
+ _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
+ }
855
+ }
856
+ }
857
+ //# sourceMappingURL=FetchSseDriver.js.map