react-native-nitro-sse 3.0.0-beta.2 → 3.0.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 (33) hide show
  1. package/README.md +43 -23
  2. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +110 -64
  3. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +32 -23
  4. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +3 -0
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +29 -2
  6. package/ios/NitroSse.swift +53 -17
  7. package/ios/SseConfig+CopyWith.swift +35 -19
  8. package/lib/module/MockSseEngine.js +0 -5
  9. package/lib/module/NitroSseClient.js +55 -7
  10. package/lib/module/createNitroSse.js +24 -0
  11. package/lib/module/index.js +1 -22
  12. package/lib/module/useNitroSse.js +22 -5
  13. package/lib/typescript/src/NitroSse.nitro.d.ts +2 -2
  14. package/lib/typescript/src/NitroSseClient.d.ts +7 -3
  15. package/lib/typescript/src/SseInterface.d.ts +14 -7
  16. package/lib/typescript/src/createNitroSse.d.ts +9 -0
  17. package/lib/typescript/src/index.d.ts +1 -8
  18. package/lib/typescript/src/useNitroSse.d.ts +2 -2
  19. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +8 -8
  20. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -1
  21. package/nitrogen/generated/android/c++/JSseConfig.hpp +1 -18
  22. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +4 -3
  23. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +4 -13
  24. package/nitrogen/generated/android/nitrosseOnLoad.cpp +2 -2
  25. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +8 -8
  26. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +104 -104
  27. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +4 -4
  28. package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -1
  29. package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +34 -1
  30. package/nitrogen/generated/ios/swift/SseConfig.swift +1 -48
  31. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +3 -1
  32. package/nitrogen/generated/shared/c++/SseConfig.hpp +2 -8
  33. package/package.json +1 -1
package/README.md CHANGED
@@ -67,6 +67,11 @@ export function EventStream() {
67
67
  url: 'https://api.example.com/events',
68
68
  headers: { Authorization: 'Bearer TOKEN' },
69
69
  autoParseJSON: true,
70
+ // Async interceptor called before initial connection & auto-reconnects
71
+ onBeforeRequest: async () => {
72
+ const token = await getFreshAuthToken();
73
+ return { Authorization: `Bearer ${token}` };
74
+ },
70
75
  onMessage: (e) => console.log(e.parsedData ?? e.data),
71
76
  onError: (e) => console.error(e.message),
72
77
  // Strongly-typed named event types ('event: <name>')
@@ -89,7 +94,7 @@ export function EventStream() {
89
94
 
90
95
  #### `UseNitroSseOptions`
91
96
 
92
- Inherits all [`SseConfig`](#configuration-reference-sseconfig) options plus:
97
+ Inherits all [`SseClientOptions`](#configuration-reference-sseclientoptions) options plus:
93
98
 
94
99
  | Option | Type | Default | Description |
95
100
  | :-------------- | :----------------------------------------------------------------- | :------ | :------------------------------------------------------- |
@@ -141,6 +146,11 @@ sse.setup({
141
146
  url: 'https://api.example.com/events',
142
147
  headers: { Authorization: 'Bearer TOKEN' },
143
148
  autoParseJSON: true,
149
+ // Dynamic header refresh for initial connection and auto-reconnects
150
+ onBeforeRequest: async () => {
151
+ const token = await getFreshAuthToken();
152
+ return { Authorization: `Bearer ${token}` };
153
+ },
144
154
  });
145
155
 
146
156
  // Event listeners
@@ -160,30 +170,33 @@ sse.start();
160
170
  ## API & Configuration
161
171
 
162
172
  <details>
163
- <summary><b>Configuration Reference (<code>SseConfig</code>)</b></summary>
173
+ <summary><b>Configuration Reference (<code>SseClientOptions</code>)</b></summary>
164
174
 
175
+ <a id="configuration-reference-sseclientoptions"></a>
165
176
  <a id="configuration-reference-sseconfig"></a>
166
177
 
167
- | Parameter | Type | Default | Description |
168
- | :--------------------- | :-------------------------------------- | :------- | :-------------------------------------------------------------------- |
169
- | `url` | `string` | — | **Required**. Target SSE endpoint URL. |
170
- | `method` | `'get' \| 'post'` | `'get'` | HTTP method. |
171
- | `headers` | `Record<string, string>` | `{}` | Request headers. |
172
- | `body` | `string` | — | Body for POST requests. |
173
- | `backgroundExecution` | `boolean` | `false` | (iOS) Continues streaming while app is in background. |
174
- | `batchingIntervalMs` | `number` | `0` | Batching delay in ms (`0` dispatches immediately). |
175
- | `maxBufferSize` | `number` | `1000` | Max buffer size before forcing event dispatch. |
176
- | `connectionTimeoutMs` | `number` | `15000` | Socket connection timeout in ms. |
177
- | `readTimeoutMs` | `number` | `300000` | Inactivity timeout in ms before reconnecting. |
178
- | `retryIntervalMs` | `number` | `1000` | Base reconnect delay in ms. |
179
- | `maxRetryIntervalMs` | `number` | `30000` | Maximum exponential backoff delay in ms. |
180
- | `jitterFactor` | `number` | `0.5` | Jitter factor applied to reconnect delay (`0.0` to `1.0`). |
181
- | `maxReconnectAttempts` | `number` | `-1` | Max reconnect retries (`-1` = infinite, `0` = disabled). |
182
- | `maxAuthRetries` | `number` | `3` | Max retry attempts for 401/403 responses using `onBeforeRequest`. |
178
+ `SseClientOptions` is the configuration object accepted by `setup()` and `useNitroSse()`. It extends the native data struct `SseConfig` with dynamic client interceptors:
179
+
180
+ | Parameter | Type | Default | Description |
181
+ | :--------------------- | :-------------------------------------- | :------- | :------------------------------------------------------------------------------------------------- |
182
+ | `url` | `string` | — | **Required**. Target SSE endpoint URL. |
183
+ | `method` | `'get' \| 'post'` | `'get'` | HTTP method. |
184
+ | `headers` | `Record<string, string>` | `{}` | Request headers. |
185
+ | `body` | `string` | — | Body for POST requests. |
186
+ | `backgroundExecution` | `boolean` | `false` | (iOS) Continues streaming while app is in background. |
187
+ | `batchingIntervalMs` | `number` | `0` | Batching delay in ms (`0` dispatches immediately). |
188
+ | `maxBufferSize` | `number` | `1000` | Max buffer size before forcing event dispatch. |
189
+ | `connectionTimeoutMs` | `number` | `15000` | Socket connection timeout in ms. |
190
+ | `readTimeoutMs` | `number` | `300000` | Inactivity timeout in ms before reconnecting. |
191
+ | `retryIntervalMs` | `number` | `1000` | Base reconnect delay in ms. |
192
+ | `maxRetryIntervalMs` | `number` | `30000` | Maximum exponential backoff delay in ms. |
193
+ | `jitterFactor` | `number` | `0.5` | Jitter factor applied to reconnect delay (`0.0` to `1.0`). |
194
+ | `maxReconnectAttempts` | `number` | `-1` | Max reconnect retries (`-1` = infinite, `0` = disabled). |
195
+ | `maxAuthRetries` | `number` | `3` | Max retry attempts for 401/403 responses using `onBeforeRequest`. |
183
196
  | `autoParseJSON` | `boolean` | `false` | Parses JSON root objects (`'{...}'`) into `parsedData`. If `false`, use `data` and parse manually. |
184
- | `monitorNetwork` | `boolean` | `true` | Automatically pauses/resumes on network changes. |
185
- | `onBeforeRequest` | `() => Promise<Record<string, string>>` | — | Async hook to refresh headers prior to connection attempts. |
186
- | `mock` | `SseMockConfig` | — | Mock stream configuration (development only). |
197
+ | `monitorNetwork` | `boolean` | `true` | Automatically pauses/resumes on network changes. |
198
+ | `onBeforeRequest` | `() => Promise<Record<string, string>>` | — | Async hook to refresh headers prior to connection attempts. |
199
+ | `mock` | `SseMockConfig` | — | Mock stream configuration (development only). |
187
200
 
188
201
  </details>
189
202
 
@@ -202,7 +215,7 @@ sse.start();
202
215
  - **`addEventListener(type, listener)`**: Subscribes to an event type (`'message'`, `'open'`, `'close'`, `'error'`, `'heartbeat'`, `'state'`, or custom event name).
203
216
  - **`removeEventListener(type, listener)`**: Unsubscribes a specific listener.
204
217
  - **`removeAllEventListeners(type?)`**: Unregisters all listeners (or listeners for a given event type).
205
- - **`dispose()`**: Closes connection and releases native resources. Subsequent calls throw `NitroSseDisposedError`.
218
+ - **`dispose()`**: Closes connection and releases native resources. Idempotent and safe to call multiple times.
206
219
 
207
220
  </details>
208
221
 
@@ -238,6 +251,10 @@ try {
238
251
  Development-only mock stream simulation:
239
252
 
240
253
  ```ts
254
+ import { createNitroSse } from 'react-native-nitro-sse';
255
+
256
+ const sse = createNitroSse();
257
+
241
258
  sse.setup({
242
259
  url: 'https://api.example.com/events',
243
260
  mock: __DEV__
@@ -253,7 +270,10 @@ sse.setup({
253
270
  : undefined,
254
271
  });
255
272
 
256
- // Programmatic event injection
273
+ sse.addEventListener('message', (e) => console.log('Message:', e.data));
274
+ sse.start();
275
+
276
+ // Programmatic event injection (development only)
257
277
  sse.injectMockEvent({ type: 'message', data: 'Test' });
258
278
  ```
259
279
 
@@ -10,6 +10,7 @@ import okhttp3.MediaType.Companion.toMediaType
10
10
  import okhttp3.RequestBody.Companion.toRequestBody
11
11
  import okhttp3.sse.EventSource
12
12
  import com.margelo.nitro.NitroModules
13
+ import com.margelo.nitro.core.Promise
13
14
  import java.util.concurrent.TimeUnit
14
15
  import java.util.concurrent.atomic.AtomicBoolean
15
16
  import java.util.concurrent.atomic.AtomicLong
@@ -38,6 +39,13 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
38
39
  private var requestId: String? = null
39
40
 
40
41
  private val isRunning = AtomicBoolean(false)
42
+ /**
43
+ * Indicates whether the underlying React Native JS Dispatcher/CallInvoker has been destroyed
44
+ * (e.g. during Fast Refresh, bundle reload, or host teardown).
45
+ * Marked @Volatile to guarantee cross-thread memory visibility between sseDispatcher background
46
+ * thread, network callbacks, and JS/Main threads without stale CPU cache reads.
47
+ */
48
+ @Volatile
41
49
  private var isDispatcherDestroyed = false
42
50
  private var wasRunningBeforePaused = false
43
51
  private val consecutiveAuthErrors = AtomicInteger(0)
@@ -53,8 +61,10 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
53
61
  private var lastErrorTime: Double? = null
54
62
  private var lastErrorCode: String? = null
55
63
  private var wasRunningBeforeNetworkLoss = false
56
- private var lastNetworkCapabilities: NetworkCapabilities? = null
57
64
  private var interceptorTimeoutRunnable: Runnable? = null
65
+ private val isDisposed = AtomicBoolean(false)
66
+ /// Dynamic request interceptor decoupled from SseConfig (v3.0)
67
+ private var requestInterceptor: (() -> Promise<Promise<Map<String, String>>>)? = null
58
68
 
59
69
  private lateinit var eventBuffer: SseEventBuffer
60
70
  private val reconnectStrategy = SseReconnectStrategy()
@@ -68,9 +78,14 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
68
78
  private const val DEFAULT_MAX_AUTH_RETRIES = 3
69
79
  }
70
80
 
71
- override fun setup(config: SseConfig, onEvent: (events: Array<SseEvent>) -> Unit) {
81
+ override fun setup(
82
+ config: SseConfig,
83
+ onEvent: (events: Array<SseEvent>) -> Unit,
84
+ onBeforeRequest: (() -> Promise<Promise<Map<String, String>>>)?
85
+ ) {
72
86
  synchronized(this) {
73
87
  this.config = config
88
+ this.requestInterceptor = onBeforeRequest
74
89
 
75
90
  if (sseDispatcher == null) {
76
91
  sseDispatcherThread = android.os.HandlerThread("NitroSseThread").apply { start() }
@@ -79,6 +94,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
79
94
 
80
95
  if (!::eventBuffer.isInitialized) {
81
96
  eventBuffer = SseEventBuffer(onEvent, sseDispatcher)
97
+ eventBuffer.onFlushError = { e -> handleRuntimeOrFlushError(e) }
82
98
  } else {
83
99
  eventBuffer.setCallback(onEvent)
84
100
  }
@@ -99,7 +115,8 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
99
115
  // Enables transparent socket-level retry on route failures (multiple IP fallback, transient resets)
100
116
  // before bubbling up to full SSE stream reconnect.
101
117
  .retryOnConnectionFailure(true)
102
- .addNetworkInterceptor(HeartbeatNetworkInterceptor { heartbeatRid, comment ->
118
+ .addNetworkInterceptor(InspectorNetworkInterceptor())
119
+ .addInterceptor(HeartbeatInterceptor { heartbeatRid, comment ->
103
120
  sseDispatcher?.post {
104
121
  // Guard keep-alive signals by active request ID to ignore residual bytes from closed/closing sockets
105
122
  val currentRid = synchronized(this@NitroSse) { requestId }
@@ -129,32 +146,38 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
129
146
  )
130
147
  lifecycleManager?.startObserving()
131
148
  }
132
- }
133
-
134
- if (config.monitorNetwork != false) {
135
- sseDispatcher?.post {
136
- startNetworkMonitoring()
137
- }
138
- } else {
139
- sseDispatcher?.post {
140
- networkMonitor?.stop()
141
- networkMonitor = null
149
+ if (config.monitorNetwork != false) {
150
+ sseDispatcher?.post {
151
+ startNetworkMonitoring()
152
+ }
153
+ } else {
154
+ sseDispatcher?.post {
155
+ networkMonitor?.stop()
156
+ networkMonitor = null
157
+ }
142
158
  }
143
159
  }
144
160
  }
145
161
 
162
+ /**
163
+ * Convenience overload for setup without onBeforeRequest.
164
+ */
165
+ fun setup(config: SseConfig, onEvent: (events: Array<SseEvent>) -> Unit) {
166
+ setup(config, onEvent, null)
167
+ }
168
+
146
169
  private fun startNetworkMonitoring() {
147
170
  val context = NitroModules.applicationContext ?: return
148
171
  if (networkMonitor == null) {
149
- networkMonitor = SseNetworkMonitor(context, sseDispatcher) { isAvailable, capabilities ->
150
- handleNetworkChange(isAvailable, capabilities)
172
+ networkMonitor = SseNetworkMonitor(context, sseDispatcher) { isAvailable, interfaceChanged, capabilities ->
173
+ handleNetworkChange(isAvailable, interfaceChanged, capabilities)
151
174
  }
152
175
  }
153
176
  networkMonitor?.start()
154
177
  }
155
178
 
156
- private fun handleNetworkChange(isAvailable: Boolean, capabilities: NetworkCapabilities?) {
157
- Log.d(TAG, "Network change: available=$isAvailable")
179
+ private fun handleNetworkChange(isAvailable: Boolean, interfaceChanged: Boolean, capabilities: NetworkCapabilities?) {
180
+ Log.d(TAG, "Network change: available=$isAvailable, interfaceChanged=$interfaceChanged")
158
181
  if (isAvailable && capabilities != null) {
159
182
  if (wasRunningBeforeNetworkLoss) {
160
183
  Log.d(TAG, "Network restored. Resuming stream.")
@@ -164,19 +187,10 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
164
187
  } else {
165
188
  start()
166
189
  }
167
- } else if (isRunning.get() && lastNetworkCapabilities != null) {
168
- val isWifi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
169
- val isCellular = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
170
-
171
- val lastWifi = lastNetworkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ?: false
172
- val lastCellular = lastNetworkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ?: false
173
-
174
- if ((isWifi && !lastWifi) || (isCellular && !lastCellular)) {
175
- Log.d(TAG, "Network interface changed. Restarting stream.")
176
- restart()
177
- }
190
+ } else if (isRunning.get() && interfaceChanged) {
191
+ Log.d(TAG, "Network interface changed. Restarting stream.")
192
+ restart()
178
193
  }
179
- lastNetworkCapabilities = capabilities
180
194
  } else if (!isAvailable) {
181
195
  if (isRunning.get()) {
182
196
  Log.d(TAG, "Network lost. Hibernating.")
@@ -186,7 +200,6 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
186
200
  connectionAttemptVersion.incrementAndGet()
187
201
  performInternalCleanup()
188
202
  }
189
- lastNetworkCapabilities = null
190
203
  }
191
204
  }
192
205
 
@@ -293,7 +306,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
293
306
 
294
307
  val currentConfig = synchronized(this) { config } ?: return
295
308
  // Asynchronously await JS onBeforeRequest interceptor before creating EventSource.
296
- val interceptor = currentConfig.onBeforeRequest
309
+ val interceptor = synchronized(this) { requestInterceptor }
297
310
 
298
311
  if (interceptor != null) {
299
312
  val interceptorCompleted = AtomicBoolean(false)
@@ -323,12 +336,13 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
323
336
  if (interceptorCompleted.compareAndSet(false, true)) {
324
337
  interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
325
338
  interceptorTimeoutRunnable = null
326
- synchronized(this) {
327
- val mergedHeaders = (config?.headers ?: emptyMap()).toMutableMap()
339
+ val connectionConfig = synchronized(this) {
340
+ val base = config ?: return@post
341
+ val mergedHeaders = (base.headers ?: emptyMap()).toMutableMap()
328
342
  newHeaders.forEach { (k, v) -> mergedHeaders[k] = v }
329
- config = config?.copy(headers = mergedHeaders)
343
+ base.copy(headers = mergedHeaders)
330
344
  }
331
- executeConnection(version)
345
+ executeConnection(version, connectionConfig)
332
346
  }
333
347
  }
334
348
  }.catch { error ->
@@ -341,7 +355,16 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
341
355
  safeHandleError(e)
342
356
  }
343
357
  } else {
344
- executeConnection(version)
358
+ executeConnection(version, null)
359
+ }
360
+ }
361
+
362
+ private fun handleRuntimeOrFlushError(t: Throwable?) {
363
+ val isDispatcherDestroyedMsg = t?.message?.contains("Dispatcher has already been destroyed", ignoreCase = true) == true
364
+ if (isDispatcherDestroyedMsg) {
365
+ Log.w(TAG, "JS Dispatcher destroyed during event flush. Disposing NitroSse instance.")
366
+ this.isDispatcherDestroyed = true
367
+ dispose()
345
368
  }
346
369
  }
347
370
 
@@ -353,19 +376,18 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
353
376
 
354
377
  val isDispatcherDestroyedMsg = t?.message?.contains("Dispatcher has already been destroyed", ignoreCase = true) == true
355
378
  if (isDispatcherDestroyedMsg) {
356
- Log.w(TAG, "JS Dispatcher destroyed. Stopping SSE stream.")
357
- this@NitroSse.isDispatcherDestroyed = true
358
- stopInternal()
379
+ Log.w(TAG, "JS Dispatcher destroyed during interceptor error. Disposing NitroSse instance.")
380
+ this.isDispatcherDestroyed = true
381
+ dispose()
359
382
  return@post
360
383
  }
361
-
384
+
362
385
  eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null, null))
363
-
364
386
  scheduleReconnect(true, version)
365
387
  }
366
388
  }
367
389
 
368
- private fun executeConnection(version: Int) {
390
+ private fun executeConnection(version: Int, connectionConfig: SseConfig? = null) {
369
391
  val currentConfig: SseConfig
370
392
  val currentLastId: String?
371
393
  val oldRequestId: String?
@@ -373,7 +395,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
373
395
 
374
396
  synchronized(this) {
375
397
  if (!isRunning.get() || config == null || version != connectionAttemptVersion.get()) return
376
- currentConfig = config!!
398
+ currentConfig = connectionConfig ?: config!!
377
399
  currentLastId = lastProcessedId
378
400
 
379
401
  oldRequestId = requestId
@@ -403,11 +425,6 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
403
425
  if (it.isNotEmpty()) requestBuilder.header("Last-Event-ID", it)
404
426
  }
405
427
 
406
- // Explicitly set identity encoding after custom headers to prevent OkHttp from requesting gzip.
407
- // If gzipped, HeartbeatNetworkInterceptor intercepts raw compressed bytes before decompression,
408
- // corrupting byte-level comment scanning for keep-alive events (':').
409
- requestBuilder.header("Accept-Encoding", "identity")
410
-
411
428
  if (currentConfig.method == HttpMethod.POST) {
412
429
  val body = currentConfig.body?.toRequestBody("application/json".toMediaType()) ?: "".toRequestBody()
413
430
  requestBuilder.post(body)
@@ -420,6 +437,8 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
420
437
  val newEventSource = connectionHandler.createEventSource(client!!, request, newRequestId)
421
438
  synchronized(this) { eventSource = newEventSource }
422
439
  } catch (e: Exception) {
440
+ // Standard Java Exception catch: handles IllegalArgumentException (URL/headers), NullPointerException,
441
+ // and IllegalStateException without catching/suppressing fatal JVM errors (e.g. OutOfMemoryError, VirtualMachineError).
423
442
  Log.e(TAG, "Failed to create SSE connection request: ${e.message}", e)
424
443
  failAndStop("Invalid connection request: ${e.message}", -1.0)
425
444
  }
@@ -482,13 +501,13 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
482
501
  val maxRetries = synchronized(this@NitroSse) { config?.maxAuthRetries?.toInt() ?: DEFAULT_MAX_AUTH_RETRIES }
483
502
  // Handle 401/403 with async token refresh up to maxAuthRetries.
484
503
  if (statusCode == 401 || statusCode == 403) {
485
- val currentConfig = synchronized(this@NitroSse) { config }
486
- if (currentConfig?.onBeforeRequest == null) {
504
+ val hasInterceptor = synchronized(this@NitroSse) { requestInterceptor != null }
505
+ if (!hasInterceptor) {
487
506
  failAndStop("Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble())
488
507
  return@post
489
508
  }
490
509
  val retries = consecutiveAuthErrors.incrementAndGet()
491
- if (retries >= maxRetries) {
510
+ if (retries > maxRetries) {
492
511
  failAndStop("Auth Error ($statusCode) - Retry limit reached ($maxRetries). Stopping.", statusCode.toDouble())
493
512
  return@post
494
513
  }
@@ -592,15 +611,20 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
592
611
 
593
612
  override fun restart() {
594
613
  synchronized(this) { config } ?: return
595
- stopInternal()
596
- isRunning.set(true)
597
- val version = connectionAttemptVersion.incrementAndGet()
598
- updateState(SseState.RECONNECTING)
599
- sseDispatcher?.post {
614
+ val task = {
615
+ stopInternal()
616
+ isRunning.set(true)
617
+ val version = connectionAttemptVersion.incrementAndGet()
618
+ updateState(SseState.RECONNECTING)
600
619
  reconnectStrategy.reset()
601
620
  requestId = null
602
621
  performConnection(version)
603
622
  }
623
+ if (sseDispatcher?.isCurrentDispatcher() == true) {
624
+ task()
625
+ } else {
626
+ sseDispatcher?.post(task)
627
+ }
604
628
  }
605
629
 
606
630
  override fun isConnected(): Boolean {
@@ -608,16 +632,23 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
608
632
  }
609
633
 
610
634
  override fun stop() {
611
- isRunning.set(false)
612
- wasRunningBeforeNetworkLoss = false
613
- wasRunningBeforePaused = false
614
- if (currentState.get() != SseState.FAILED) {
615
- updateState(SseState.CLOSED)
616
- }
617
- connectionAttemptVersion.incrementAndGet()
618
- sseDispatcher?.post {
635
+ val task = {
636
+ isRunning.set(false)
637
+ wasRunningBeforeNetworkLoss = false
638
+ wasRunningBeforePaused = false
639
+ if (!isDispatcherDestroyed && currentState.get() != SseState.FAILED) {
640
+ updateState(SseState.CLOSED)
641
+ } else if (isDispatcherDestroyed) {
642
+ currentState.set(SseState.CLOSED)
643
+ }
644
+ connectionAttemptVersion.incrementAndGet()
619
645
  performInternalCleanup()
620
646
  }
647
+ if (sseDispatcher?.isCurrentDispatcher() == true) {
648
+ task()
649
+ } else {
650
+ sseDispatcher?.post(task)
651
+ }
621
652
  }
622
653
 
623
654
  private fun clearActiveRequestAndReportEnd() {
@@ -631,6 +662,10 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
631
662
  currentRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
632
663
  }
633
664
 
665
+ /**
666
+ * Cleans up timeouts, active socket, and flushes any pending buffered events.
667
+ * Always invoked within `sseDispatcherThread` execution context (from lifecycle, network, or stop).
668
+ */
634
669
  private fun performInternalCleanup() {
635
670
  interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
636
671
  interceptorTimeoutRunnable = null
@@ -647,11 +682,22 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
647
682
  * Synchronously cleans up active network sockets, timers, and lifecycle observers.
648
683
  */
649
684
  override fun dispose() {
685
+ if (!isDisposed.compareAndSet(false, true)) {
686
+ return
687
+ }
650
688
  Log.d(TAG, "Disposing NitroSse instance and cleaning up resources...")
651
689
 
652
690
  isRunning.set(false)
653
691
  connectionAttemptVersion.incrementAndGet()
654
692
 
693
+ synchronized(this) {
694
+ requestInterceptor = null
695
+ config = null
696
+ }
697
+
698
+ interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
699
+ interceptorTimeoutRunnable = null
700
+
655
701
  if (::eventBuffer.isInitialized) {
656
702
  eventBuffer.clearCallback()
657
703
  eventBuffer.clear()
@@ -10,7 +10,6 @@ import okhttp3.sse.EventSourceListener
10
10
  import okhttp3.sse.EventSources
11
11
  import okio.Buffer
12
12
  import okio.ForwardingSource
13
- import okio.GzipSource
14
13
  import okio.buffer
15
14
  import java.util.concurrent.atomic.AtomicLong
16
15
 
@@ -52,10 +51,30 @@ class SseConnectionHandler(private val delegate: SseConnectionDelegate) {
52
51
  }
53
52
 
54
53
  /**
55
- * Network interceptor for byte accounting and SSE heartbeat/comment detection.
56
- * Sniffs raw stream before EventSourceReader discards SSE comments (`:`).
54
+ * Network interceptor for recording raw wire response metadata for React Native DevTools.
55
+ * Runs at the network layer to capture true HTTP status, raw wire headers (e.g. Content-Encoding: gzip), and timing.
57
56
  */
58
- internal class HeartbeatNetworkInterceptor(
57
+ internal class InspectorNetworkInterceptor : Interceptor {
58
+ override fun intercept(chain: Interceptor.Chain): Response {
59
+ val request = chain.request()
60
+ val rid = request.tag(String::class.java)
61
+ val response = chain.proceed(request)
62
+ rid?.let {
63
+ NetworkInspector.reportResponseStart(it, request, response)
64
+ }
65
+ return response
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Application interceptor for byte accounting and SSE heartbeat/comment detection.
71
+ * Inspects decompressed UTF-8 stream before EventSourceReader discards SSE comments (`:`).
72
+ *
73
+ * Placed as an OkHttp Application Interceptor (above BridgeInterceptor), allowing OkHttp
74
+ * to handle transparent gzip/deflate decompression naturally without requiring manual GzipSource
75
+ * wrapping or disabling compression with 'Accept-Encoding: identity'.
76
+ */
77
+ internal class HeartbeatInterceptor(
59
78
  private val totalBytesReceived: AtomicLong? = null,
60
79
  private val onHeartbeat: (requestId: String?, comment: String) -> Unit
61
80
  ) : Interceptor {
@@ -64,28 +83,16 @@ internal class HeartbeatNetworkInterceptor(
64
83
  override fun intercept(chain: Interceptor.Chain): Response {
65
84
  val request = chain.request()
66
85
  val rid = request.tag(String::class.java)
67
-
68
86
  val response = chain.proceed(request)
69
87
 
70
- rid?.let {
71
- NetworkInspector.reportResponseStart(it, request, response)
72
- }
73
-
74
88
  val responseBody = response.body
75
89
  if (responseBody != null) {
76
- val isGzip = "gzip".equals(response.header("Content-Encoding"), ignoreCase = true)
77
- val rawSource = if (isGzip) {
78
- GzipSource(responseBody.source())
79
- } else {
80
- responseBody.source()
81
- }
82
-
83
90
  val countingBody = object : ResponseBody() {
84
91
  override fun contentType() = responseBody.contentType()
85
- override fun contentLength() = if (isGzip) -1L else responseBody.contentLength()
92
+ override fun contentLength() = responseBody.contentLength()
86
93
 
87
94
  private val bufferedSource by lazy {
88
- (object : ForwardingSource(rawSource) {
95
+ (object : ForwardingSource(responseBody.source()) {
89
96
  private var isAtStartOfLine = true
90
97
  private var isReadingComment = false
91
98
  private val commentBuffer = java.io.ByteArrayOutputStream()
@@ -128,12 +135,14 @@ internal class HeartbeatNetworkInterceptor(
128
135
 
129
136
  override fun source() = bufferedSource
130
137
  }
131
- val responseBuilder = response.newBuilder().body(countingBody)
132
- if (isGzip) {
133
- responseBuilder.removeHeader("Content-Encoding").removeHeader("Content-Length")
134
- }
135
- return responseBuilder.build()
138
+ return response.newBuilder().body(countingBody).build()
136
139
  }
137
140
  return response
138
141
  }
139
142
  }
143
+
144
+ @Deprecated(
145
+ message = "Use HeartbeatInterceptor instead. This interceptor is an OkHttp application interceptor, not a network interceptor.",
146
+ replaceWith = ReplaceWith("HeartbeatInterceptor")
147
+ )
148
+ internal typealias HeartbeatNetworkInterceptor = HeartbeatInterceptor
@@ -16,6 +16,8 @@ class SseEventBuffer(
16
16
  @Volatile
17
17
  private var onFlush: (Array<SseEvent>) -> Unit = onFlush
18
18
 
19
+ var onFlushError: ((Exception) -> Unit)? = null
20
+
19
21
  private val eventBuffer = mutableListOf<SseEvent>()
20
22
  private val isFlushPending = AtomicBoolean(false)
21
23
 
@@ -95,6 +97,7 @@ class SseEventBuffer(
95
97
  onFlush(eventsToEmit)
96
98
  } catch (e: Exception) {
97
99
  Log.e("SseEventBuffer", "Error invoking onFlush: ${e.message}")
100
+ onFlushError?.invoke(e)
98
101
  }
99
102
  }
100
103
 
@@ -7,13 +7,14 @@ import android.net.NetworkCapabilities
7
7
  import android.net.NetworkRequest
8
8
  import android.util.Log
9
9
 
10
- typealias NetworkChangeHandler = (isAvailable: Boolean, capabilities: NetworkCapabilities?) -> Unit
10
+ typealias NetworkChangeHandler = (isAvailable: Boolean, interfaceChanged: Boolean, capabilities: NetworkCapabilities?) -> Unit
11
11
 
12
12
  /**
13
13
  * Monitors system connectivity changes using Android's [ConnectivityManager].
14
14
  *
15
15
  * Emits network availability and capability updates to enable automatic stream reconnection
16
16
  * upon network restoration or interface handovers (e.g. Wi-Fi to cellular transition).
17
+ * Initial network detection is captured internally without flagging a false interface change.
17
18
  */
18
19
  class SseNetworkMonitor(
19
20
  private val context: Context,
@@ -22,6 +23,7 @@ class SseNetworkMonitor(
22
23
  ) {
23
24
  private val lock = Any()
24
25
  private var networkCallback: ConnectivityManager.NetworkCallback? = null
26
+ private var lastCapabilities: NetworkCapabilities? = null
25
27
 
26
28
  companion object {
27
29
  private const val TAG = "SseNetworkMonitor"
@@ -39,7 +41,31 @@ class SseNetworkMonitor(
39
41
 
40
42
  val callback = object : ConnectivityManager.NetworkCallback() {
41
43
  private fun dispatchChange(isAvailable: Boolean, capabilities: NetworkCapabilities?) {
42
- dispatcher?.post { onChange(isAvailable, capabilities) } ?: onChange(isAvailable, capabilities)
44
+ val interfaceChanged: Boolean
45
+ if (isAvailable && capabilities != null) {
46
+ val prev = lastCapabilities
47
+ if (prev != null) {
48
+ val isWifi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
49
+ val isCellular = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
50
+ val lastWifi = prev.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
51
+ val lastCellular = prev.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
52
+ interfaceChanged = (isWifi && !lastWifi) || (isCellular && !lastCellular)
53
+ } else {
54
+ interfaceChanged = false
55
+ }
56
+ lastCapabilities = capabilities
57
+ } else {
58
+ interfaceChanged = false
59
+ if (!isAvailable) {
60
+ lastCapabilities = null
61
+ }
62
+ }
63
+
64
+ if (dispatcher == null || dispatcher.isCurrentDispatcher()) {
65
+ onChange(isAvailable, interfaceChanged, capabilities)
66
+ } else {
67
+ dispatcher.post { onChange(isAvailable, interfaceChanged, capabilities) }
68
+ }
43
69
  }
44
70
 
45
71
  override fun onAvailable(network: Network) {
@@ -77,6 +103,7 @@ class SseNetworkMonitor(
77
103
 
78
104
  fun stop() {
79
105
  synchronized(lock) {
106
+ lastCapabilities = null
80
107
  val callback = networkCallback ?: return
81
108
  try {
82
109
  val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager