react-native-nitro-sse 1.3.1 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/NitroSse.podspec CHANGED
@@ -14,9 +14,12 @@ Pod::Spec.new do |s|
14
14
  s.source = { :git => "https://github.com/IAmTester35/react-native-nitro-sse.git", :tag => "#{s.version}" }
15
15
 
16
16
  s.source_files = [
17
- "ios/*.{swift}",
18
- "ios/*.{m,mm}",
19
- "cpp/**/*.{hpp,cpp}",
17
+ "ios/*.{h,m,mm,swift}",
18
+ "cpp/**/*.{h,hpp,cpp}",
19
+ ]
20
+
21
+ s.public_header_files = [
22
+ "ios/NitroSseNetworkInspector.h",
20
23
  ]
21
24
 
22
25
  s.test_spec 'Tests' do |test_spec|
package/README.md CHANGED
@@ -12,6 +12,7 @@ Unlike traditional EventSource libraries that run on the JS thread or use the le
12
12
  - **🌊 Backpressure Handling**: Advanced **Batching** mechanism aggregates messages and employs **Tail Drop** strategies to protect the UI thread from freezing during data surges.
13
13
  - **🔋 Mobile-First Architecture**: Automatically hibernates when the app enters the background and seamlessly reconnects upon foregrounding to conserve battery.
14
14
  - **💓 Heartbeat Detection**: Native-side detection of keep-alive signals (comments) to maintain a reliable connection watchdog.
15
+ - **🔍 DevTools Integration**: Plug-and-play support for **React Native 0.83+ DevTools Network Tab**. Monitor connection status, request/response headers, and timing directly in the official desktop debugger.
15
16
  - **🛠️ Full Protocol Support**: Comprehensive support for GET/POST methods and dynamic header updates.
16
17
 
17
18
  ---
@@ -26,6 +27,19 @@ npm install react-native-nitro-sse react-native-nitro-modules
26
27
 
27
28
  > **Note**: `react-native-nitro-modules` is required as the core foundation for JSI performance.
28
29
 
30
+ ---
31
+
32
+ ## 📊 Compatibility
33
+
34
+ | react-native-nitro-sse | react-native-nitro-modules |
35
+ | :--------------------- | :------------------------- |
36
+ | **1.4.0 - 1.4.1** | **0.35.0** |
37
+ | **1.2.2 - 1.3.1** | **0.34.1** |
38
+ | **1.2.0 - 1.2.1** | **0.34.0** |
39
+ | **1.1.0** | **0.33.9** |
40
+ | **1.0.0** | **0.33.8** |
41
+
42
+
29
43
  ---
30
44
 
31
45
  ## 🚀 Usage
@@ -35,9 +49,11 @@ npm install react-native-nitro-sse react-native-nitro-modules
35
49
  Initialize the module with your endpoint configuration and an event listener.
36
50
 
37
51
  ```tsx
38
- import { NitroSseModule } from 'react-native-nitro-sse';
52
+ import { createNitroSse } from 'react-native-nitro-sse';
39
53
 
40
- NitroSseModule.setup(
54
+ const nitroSse = createNitroSse();
55
+
56
+ nitroSse.setup(
41
57
  {
42
58
  url: 'https://api.yourserver.com/stream',
43
59
  method: 'get',
@@ -61,31 +77,34 @@ NitroSseModule.setup(
61
77
  );
62
78
 
63
79
  // Start the connection
64
- NitroSseModule.start();
80
+ nitroSse.start();
65
81
 
66
82
  // Stop the connection when unmounting or no longer needed
67
- // NitroSseModule.stop();
83
+ // nitroSse.stop();
68
84
  ```
69
85
 
86
+
70
87
  ### 2. Check Connection Status
71
88
 
72
89
  You can synchronously check the connection status at any time:
73
90
 
74
91
  ```tsx
75
- const connected = NitroSseModule.isConnected();
92
+ const connected = nitroSse.isConnected();
76
93
  console.log('Is Connected:', connected);
77
94
  ```
78
95
 
96
+
79
97
  ### 3. Dynamic Token Updates
80
98
 
81
99
  When your authentication token expires, update the headers instantly. The native layer will apply these headers to the next automatic reconnection attempt without interrupting the current flow if not necessary.
82
100
 
83
101
  ```tsx
84
- NitroSseModule.updateHeaders({
102
+ nitroSse.updateHeaders({
85
103
  'Authorization': 'Bearer new-fresh-token',
86
104
  });
87
105
  ```
88
106
 
107
+
89
108
  ---
90
109
 
91
110
  ## ⚙️ Configuration (SseConfig)
@@ -1,6 +1,10 @@
1
1
  #include <jni.h>
2
+ #include <fbjni/fbjni.h>
2
3
  #include "nitrosseOnLoad.hpp"
3
4
 
4
5
  JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) {
5
- return margelo::nitro::nitrosse::initialize(vm);
6
+ return facebook::jni::initialize(vm, []() {
7
+ margelo::nitro::nitrosse::registerAllNatives();
8
+ });
6
9
  }
10
+
@@ -0,0 +1,94 @@
1
+ package com.margelo.nitro.nitrosse
2
+
3
+ import android.util.Log
4
+ import okhttp3.Request
5
+ import okhttp3.Response
6
+ import java.util.UUID
7
+
8
+ /**
9
+ * A utility to report network events to the React Native DevTools Network Tab.
10
+ * It uses reflection to access the internal InspectorNetworkReporter class in RN.
11
+ */
12
+ object NetworkInspector {
13
+ private const val TAG = "NitroSseNetworkInspector"
14
+ private var reporterClass: Class<*>? = null
15
+ private var isEnabledCached: Boolean = false
16
+
17
+ init {
18
+ try {
19
+ reporterClass = Class.forName("com.facebook.react.modules.network.InspectorNetworkReporter")
20
+ Log.d(TAG, "InspectorNetworkReporter found. Network tracing is available.")
21
+ } catch (e: Exception) {
22
+ Log.d(TAG, "InspectorNetworkReporter not found. Network tracing is disabled.")
23
+ }
24
+ }
25
+
26
+ private fun isEnabled(): Boolean {
27
+ if (reporterClass == null) return false
28
+ return try {
29
+ val method = reporterClass?.getDeclaredMethod("isDebuggingEnabled")
30
+ method?.invoke(null) as? Boolean ?: false
31
+ } catch (e: Exception) {
32
+ false
33
+ }
34
+ }
35
+
36
+ fun reportRequestStart(requestId: String, request: Request) {
37
+ if (reporterClass == null || !isEnabled()) return
38
+ try {
39
+ val method = reporterClass?.getDeclaredMethod(
40
+ "reportRequestStart",
41
+ String::class.java,
42
+ String::class.java,
43
+ String::class.java,
44
+ Map::class.java,
45
+ String::class.java,
46
+ Long::class.javaPrimitiveType
47
+ )
48
+ val headers = request.headers.toMap()
49
+ // We send an empty body string as SSE setup usually doesn't have a large body
50
+ val body = ""
51
+ method?.invoke(null, requestId, request.url.toString(), request.method, headers, body, 0L)
52
+ } catch (e: Exception) {
53
+ Log.e(TAG, "Error reporting request start", e)
54
+ }
55
+ }
56
+
57
+ fun reportResponseStart(requestId: String, request: Request, response: Response) {
58
+ if (reporterClass == null || !isEnabled()) return
59
+ try {
60
+ val method = reporterClass?.getDeclaredMethod(
61
+ "reportResponseStart",
62
+ String::class.java,
63
+ String::class.java,
64
+ Int::class.javaPrimitiveType,
65
+ Map::class.java,
66
+ Long::class.javaPrimitiveType
67
+ )
68
+ val headers = response.headers.toMap()
69
+ method?.invoke(null, requestId, request.url.toString(), response.code, headers, -1L)
70
+ } catch (e: Exception) {
71
+ Log.e(TAG, "Error reporting response start", e)
72
+ }
73
+ }
74
+
75
+ fun reportResponseEnd(requestId: String, totalBytes: Long) {
76
+ if (reporterClass == null || !isEnabled()) return
77
+ try {
78
+ val method = reporterClass?.getDeclaredMethod("reportResponseEnd", String::class.java, Long::class.javaPrimitiveType)
79
+ method?.invoke(null, requestId, totalBytes)
80
+ } catch (e: Exception) {
81
+ Log.e(TAG, "Error reporting response end", e)
82
+ }
83
+ }
84
+
85
+ fun reportRequestFailed(requestId: String, cancelled: Boolean) {
86
+ if (reporterClass == null || !isEnabled()) return
87
+ try {
88
+ val method = reporterClass?.getDeclaredMethod("reportRequestFailed", String::class.java, Boolean::class.javaPrimitiveType)
89
+ method?.invoke(null, requestId, cancelled)
90
+ } catch (e: Exception) {
91
+ Log.e(TAG, "Error reporting request failure", e)
92
+ }
93
+ }
94
+ }
@@ -10,15 +10,14 @@ import okhttp3.RequestBody.Companion.toRequestBody
10
10
  import okhttp3.sse.EventSource
11
11
  import okhttp3.sse.EventSources
12
12
  import okhttp3.sse.EventSourceListener
13
- import okio.Buffer
14
- import okio.ForwardingSource
15
- import okio.buffer
13
+ import okio.*
16
14
  import androidx.lifecycle.DefaultLifecycleObserver
17
15
  import androidx.lifecycle.LifecycleOwner
18
16
  import androidx.lifecycle.ProcessLifecycleOwner
19
17
  import java.util.concurrent.TimeUnit
20
18
  import java.util.concurrent.atomic.AtomicBoolean
21
19
  import java.util.concurrent.atomic.AtomicLong
20
+ import java.util.UUID
22
21
  import kotlin.random.Random
23
22
 
24
23
  /**
@@ -41,6 +40,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
41
40
  @Volatile private var client: OkHttpClient? = null
42
41
  @Volatile private var eventSource: EventSource? = null
43
42
  @Volatile private var config: SseConfig? = null
43
+ @Volatile private var requestId: String? = null
44
44
  private var onEventsCallback: ((events: Array<SseEvent>) -> Unit)? = null
45
45
 
46
46
  private val isRunning = AtomicBoolean(false)
@@ -61,8 +61,8 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
61
61
 
62
62
  private var hasSubscribedToLifecycle = false
63
63
 
64
- private val defaultRetryDelayMs = 3000L
65
- private val baseBackoffDelayMs = 2000L
64
+ private val defaultRetryDelayMs = 2000L
65
+ private val baseBackoffDelayMs = 1000L
66
66
  private val maxBackoffDelayMs = 30000L
67
67
 
68
68
  companion object {
@@ -78,7 +78,15 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
78
78
  .connectTimeout(15, TimeUnit.SECONDS)
79
79
  .readTimeout(35, TimeUnit.SECONDS)
80
80
  .addNetworkInterceptor { chain ->
81
- val response = chain.proceed(chain.request())
81
+ val request = chain.request()
82
+ val rid = request.tag(String::class.java)
83
+
84
+ val response = chain.proceed(request)
85
+
86
+ rid?.let {
87
+ NetworkInspector.reportResponseStart(it, request, response)
88
+ }
89
+
82
90
  val responseBody = response.body
83
91
  if (responseBody != null) {
84
92
  val countingBody = object : ResponseBody() {
@@ -93,16 +101,17 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
93
101
  if (bytesRead != -1L) {
94
102
  totalBytesReceived.addAndGet(bytesRead)
95
103
 
104
+
96
105
  try {
97
106
  for (i in 0 until bytesRead) {
98
107
  val b = sink.get(bufferOffset + i)
99
- if (isAtStartOfLine && b == ':'.toByte()) {
108
+ if (isAtStartOfLine && b == ':'.code.toByte()) {
100
109
  pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, "keep-alive"))
101
110
  }
102
- isAtStartOfLine = (b == '\n'.toByte() || b == '\r'.toByte())
111
+ isAtStartOfLine = (b == '\n'.code.toByte() || b == '\r'.code.toByte())
103
112
  }
104
113
  } catch (e: Exception) {
105
- // Silent catch to prevent interceptor failure
114
+ // Silent
106
115
  }
107
116
  }
108
117
  return bytesRead
@@ -206,6 +215,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
206
215
  if (config == null || isRunning.get()) return
207
216
  isRunning.set(true)
208
217
  backoffCounter = 0
218
+ requestId = null
209
219
  sseHandler?.post { performConnection() }
210
220
  }
211
221
 
@@ -218,10 +228,19 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
218
228
  currentLastId = lastProcessedId
219
229
  }
220
230
 
231
+ // Report end for previous request if it was running
232
+ requestId?.let {
233
+ NetworkInspector.reportResponseEnd(it, totalBytesReceived.getAndSet(0))
234
+ this.requestId = null
235
+ }
236
+
221
237
  // Cancel existing event source if any before starting new one
222
238
  eventSource?.cancel()
223
239
  eventSource = null
224
240
 
241
+ val newRequestId = UUID.randomUUID().toString()
242
+ this.requestId = newRequestId
243
+
225
244
  val requestBuilder = Request.Builder()
226
245
  .url(currentConfig.url)
227
246
  .header("Accept", "text/event-stream")
@@ -238,7 +257,11 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
238
257
  requestBuilder.post(body)
239
258
  }
240
259
 
241
- eventSource = EventSources.createFactory(client!!).newEventSource(requestBuilder.build(), sseListener)
260
+ requestBuilder.tag(String::class.java, newRequestId)
261
+ val request = requestBuilder.build()
262
+ NetworkInspector.reportRequestStart(newRequestId, request)
263
+
264
+ eventSource = EventSources.createFactory(client!!).newEventSource(request, sseListener)
242
265
  }
243
266
 
244
267
  private fun extractRetryAfterMillis(response: Response?): Long? {
@@ -277,6 +300,8 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
277
300
  reconnectCount++
278
301
  lastErrorTime = System.currentTimeMillis().toDouble()
279
302
  lastErrorCode = t?.javaClass?.simpleName ?: statusCode.toString()
303
+
304
+ requestId?.let { NetworkInspector.reportRequestFailed(it, false) }
280
305
 
281
306
  val isFatal = (statusCode == 401 || statusCode == 403 || statusCode == 400)
282
307
  if (isFatal) {
@@ -317,6 +342,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
317
342
  override fun onClosed(eventSource: EventSource) {
318
343
  if (eventSource != this@NitroSse.eventSource) return
319
344
  if (isRunning.get()) {
345
+ requestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
320
346
  val delay = (defaultRetryDelayMs * (0.8 + Random.nextDouble() * 0.4)).toLong()
321
347
  sseHandler?.postDelayed({ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection() }, delay)
322
348
  }
@@ -342,6 +368,10 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
342
368
  sseHandler?.removeCallbacksAndMessages(null)
343
369
  eventSource?.cancel()
344
370
  eventSource = null
371
+ requestId?.let {
372
+ NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
373
+ requestId = null
374
+ }
345
375
  synchronized(eventBuffer) {
346
376
  eventBuffer.clear()
347
377
  }
@@ -19,6 +19,7 @@ class NitroSse: HybridNitroSseSpec {
19
19
  private var config: SseConfig?
20
20
  private var onEventsCallback: ((_ events: [SseEvent]) -> Void)?
21
21
  private var isRunning: Bool = false
22
+ private var requestId: String?
22
23
 
23
24
  private var eventBuffer: [SseEvent] = []
24
25
  private var isFlushPending: Bool = false
@@ -63,6 +64,10 @@ class NitroSse: HybridNitroSseSpec {
63
64
 
64
65
  self.eventSource?.stop()
65
66
  self.eventSource = nil
67
+ if let rid = self.requestId {
68
+ NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
69
+ self.requestId = nil
70
+ }
66
71
  self.isRunning = false
67
72
 
68
73
  self.cleanupBackgroundTask()
@@ -129,7 +134,7 @@ class NitroSse: HybridNitroSseSpec {
129
134
 
130
135
  func updateHeaders(headers: [String: String]) throws {
131
136
  sseQueue.async {
132
- guard var currentConfig = self.config else { return }
137
+ guard let currentConfig = self.config else { return }
133
138
  self.config = SseConfig(
134
139
  url: currentConfig.url,
135
140
  method: currentConfig.method,
@@ -167,6 +172,11 @@ class NitroSse: HybridNitroSseSpec {
167
172
  dispatchPrecondition(condition: .onQueue(sseQueue))
168
173
  guard isRunning, let config = config, let url = URL(string: config.url) else { return }
169
174
 
175
+ if let rid = self.requestId {
176
+ NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
177
+ self.requestId = nil
178
+ }
179
+
170
180
  let handler = SseHandler(parent: self)
171
181
  var esConfig = EventSource.Config(handler: handler, url: url)
172
182
  esConfig.headers = config.headers ?? [:]
@@ -182,6 +192,10 @@ class NitroSse: HybridNitroSseSpec {
182
192
  let es = EventSource(config: esConfig)
183
193
  self.eventSource = es
184
194
  handler.source = es
195
+
196
+ let request = URLRequest(url: url)
197
+ self.requestId = NitroSseNetworkInspector.reportRequestStart(request, encodedDataLength: 0)
198
+
185
199
  es.start()
186
200
  }
187
201
 
@@ -195,6 +209,10 @@ class NitroSse: HybridNitroSseSpec {
195
209
  self.isRunning = false
196
210
  self.eventSource?.stop()
197
211
  self.eventSource = nil
212
+ if let rid = self.requestId {
213
+ NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
214
+ self.requestId = nil
215
+ }
198
216
  self.backoffCounter = 0
199
217
  self.eventBuffer.removeAll()
200
218
  self.isFlushPending = false
@@ -212,6 +230,7 @@ class NitroSse: HybridNitroSseSpec {
212
230
  self.stopInternal()
213
231
  guard !self.isRunning else { return } // Should be false now
214
232
  self.isRunning = true
233
+ self.requestId = nil
215
234
  self.establishConnection()
216
235
  }
217
236
  }
@@ -247,6 +266,7 @@ class NitroSse: HybridNitroSseSpec {
247
266
  private func scheduleAutomaticReconnectWithFixedDelay(_ delay: TimeInterval) {
248
267
  dispatchPrecondition(condition: .onQueue(sseQueue))
249
268
  eventSource?.stop()
269
+ eventSource = nil
250
270
  sseQueue.asyncAfter(deadline: .now() + delay) { [weak self] in
251
271
  guard let self = self, self.isRunning else { return }
252
272
  self.establishConnection()
@@ -267,8 +287,10 @@ class NitroSse: HybridNitroSseSpec {
267
287
  }
268
288
  let safeDelay = max(delay, 2.0)
269
289
  let currentSource = self.eventSource
290
+ eventSource?.stop()
291
+ eventSource = nil
270
292
  sseQueue.asyncAfter(deadline: .now() + safeDelay) { [weak self] in
271
- guard let self = self, self.isRunning, self.eventSource === currentSource else { return }
293
+ guard let self = self, self.isRunning else { return }
272
294
  self.establishConnection()
273
295
  }
274
296
  }
@@ -286,6 +308,7 @@ class NitroSse: HybridNitroSseSpec {
286
308
  parent.sseQueue.async { [weak parent] in
287
309
  guard let parent = parent else { return }
288
310
  parent.backoffCounter = 0
311
+ NitroSseNetworkInspector.reportResponseStart(parent.requestId, url: parent.config?.url, response: nil, statusCode: 200, headers: [:])
289
312
  parent.pushEventToBuffer(SseEvent(type: .open, data: nil, id: nil, event: nil, message: nil))
290
313
  }
291
314
  }
@@ -294,6 +317,10 @@ class NitroSse: HybridNitroSseSpec {
294
317
  guard let parent = parent, source === parent.eventSource else { return }
295
318
  parent.sseQueue.async { [weak parent] in
296
319
  guard let parent = parent else { return }
320
+ if let rid = parent.requestId {
321
+ NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(parent.totalBytesReceived))
322
+ parent.requestId = nil
323
+ }
297
324
  if parent.isRunning {
298
325
  parent.scheduleAutomaticReconnect(isError: false)
299
326
  }
@@ -336,6 +363,9 @@ class NitroSse: HybridNitroSseSpec {
336
363
  parent.lastErrorTime = Date().timeIntervalSince1970 * 1000
337
364
  parent.lastErrorCode = "\(nsError.domain)(\(statusCode))"
338
365
 
366
+ NitroSseNetworkInspector.reportRequestFailed(parent.requestId, cancelled: false)
367
+ parent.requestId = nil
368
+
339
369
  let isFatalError = (statusCode == 401 || statusCode == 403 || statusCode == 400)
340
370
  if isFatalError {
341
371
  parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Fatal Error (\(statusCode)). Stopping."))
@@ -0,0 +1,24 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ NS_ASSUME_NONNULL_BEGIN
4
+
5
+ @interface NitroSseNetworkInspector : NSObject
6
+
7
+ + (nullable NSString *)reportRequestStart:(NSURLRequest *)request
8
+ encodedDataLength:(NSInteger)encodedDataLength;
9
+
10
+ + (void)reportResponseStart:(nullable NSString *)requestId
11
+ url:(nullable NSString *)url
12
+ response:(nullable NSURLResponse *)response
13
+ statusCode:(NSInteger)statusCode
14
+ headers:(NSDictionary<NSString *, NSString *> *)headers;
15
+
16
+ + (void)reportResponseEnd:(nullable NSString *)requestId
17
+ encodedDataLength:(NSInteger)encodedDataLength;
18
+
19
+ + (void)reportRequestFailed:(nullable NSString *)requestId
20
+ cancelled:(BOOL)cancelled;
21
+
22
+ @end
23
+
24
+ NS_ASSUME_NONNULL_END
@@ -0,0 +1,68 @@
1
+ #import "NitroSseNetworkInspector.h"
2
+
3
+ #if __has_include(<React/RCTInspectorNetworkReporter.h>)
4
+ #import <React/RCTInspectorNetworkReporter.h>
5
+ #define HAS_NETWORK_REPORTER 1
6
+ #endif
7
+
8
+ @implementation NitroSseNetworkInspector
9
+
10
+ + (nullable NSString *)reportRequestStart:(NSURLRequest *)request
11
+ encodedDataLength:(NSInteger)encodedDataLength {
12
+ #ifdef HAS_NETWORK_REPORTER
13
+ NSString *requestId = [[NSUUID UUID] UUIDString];
14
+ [RCTInspectorNetworkReporter reportRequestStart:requestId request:request encodedDataLength:(int)encodedDataLength];
15
+ [RCTInspectorNetworkReporter reportConnectionTiming:requestId request:request];
16
+ return requestId;
17
+ #else
18
+ return nil;
19
+ #endif
20
+ }
21
+
22
+ + (void)reportResponseStart:(nullable NSString *)requestId
23
+ url:(nullable NSString *)url
24
+ response:(nullable NSURLResponse *)response
25
+ statusCode:(NSInteger)statusCode
26
+ headers:(NSDictionary<NSString *, NSString *> *)headers {
27
+ #ifdef HAS_NETWORK_REPORTER
28
+ if (requestId) {
29
+ NSURLResponse *finalResponse = response;
30
+ if (finalResponse == nil) {
31
+ // Reconstruct a dummy response using standard SSE headers if none provided
32
+ NSMutableDictionary *mergedHeaders = [headers mutableCopy] ?: [NSMutableDictionary new];
33
+ if (!mergedHeaders[@"Content-Type"]) mergedHeaders[@"Content-Type"] = @"text/event-stream";
34
+ if (!mergedHeaders[@"Cache-Control"]) mergedHeaders[@"Cache-Control"] = @"no-cache";
35
+ if (!mergedHeaders[@"Connection"]) mergedHeaders[@"Connection"] = @"keep-alive";
36
+
37
+ finalResponse = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:url ?: @"http://sse-stream/"]
38
+ statusCode:statusCode
39
+ HTTPVersion:@"HTTP/1.1"
40
+ headerFields:mergedHeaders];
41
+ // Pass the merged headers to the reporter as well
42
+ [RCTInspectorNetworkReporter reportResponseStart:requestId response:finalResponse statusCode:(int)statusCode headers:mergedHeaders];
43
+ } else {
44
+ [RCTInspectorNetworkReporter reportResponseStart:requestId response:finalResponse statusCode:(int)statusCode headers:headers ?: @{}];
45
+ }
46
+ }
47
+ #endif
48
+ }
49
+
50
+ + (void)reportResponseEnd:(nullable NSString *)requestId
51
+ encodedDataLength:(NSInteger)encodedDataLength {
52
+ #ifdef HAS_NETWORK_REPORTER
53
+ if (requestId) {
54
+ [RCTInspectorNetworkReporter reportResponseEnd:requestId encodedDataLength:(int)encodedDataLength];
55
+ }
56
+ #endif
57
+ }
58
+
59
+ + (void)reportRequestFailed:(nullable NSString *)requestId
60
+ cancelled:(BOOL)cancelled {
61
+ #ifdef HAS_NETWORK_REPORTER
62
+ if (requestId) {
63
+ [RCTInspectorNetworkReporter reportRequestFailed:requestId cancelled:cancelled];
64
+ }
65
+ #endif
66
+ }
67
+
68
+ @end
@@ -38,37 +38,31 @@ namespace margelo::nitro::nitrosse { enum class SseEventType; }
38
38
 
39
39
  namespace margelo::nitro::nitrosse {
40
40
 
41
- jni::local_ref<JHybridNitroSseSpec::jhybriddata> JHybridNitroSseSpec::initHybrid(jni::alias_ref<jhybridobject> jThis) {
42
- return makeCxxInstance(jThis);
43
- }
44
-
45
- void JHybridNitroSseSpec::registerNatives() {
46
- registerHybrid({
47
- makeNativeMethod("initHybrid", JHybridNitroSseSpec::initHybrid),
48
- });
41
+ std::shared_ptr<JHybridNitroSseSpec> JHybridNitroSseSpec::JavaPart::getJHybridNitroSseSpec() {
42
+ auto hybridObject = JHybridObject::JavaPart::getJHybridObject();
43
+ auto castHybridObject = std::dynamic_pointer_cast<JHybridNitroSseSpec>(hybridObject);
44
+ if (castHybridObject == nullptr) [[unlikely]] {
45
+ throw std::runtime_error("Failed to downcast JHybridObject to JHybridNitroSseSpec!");
46
+ }
47
+ return castHybridObject;
49
48
  }
50
49
 
51
- size_t JHybridNitroSseSpec::getExternalMemorySize() noexcept {
52
- static const auto method = javaClassStatic()->getMethod<jlong()>("getMemorySize");
53
- return method(_javaPart);
50
+ jni::local_ref<JHybridNitroSseSpec::CxxPart::jhybriddata> JHybridNitroSseSpec::CxxPart::initHybrid(jni::alias_ref<jhybridobject> jThis) {
51
+ return makeCxxInstance(jThis);
54
52
  }
55
53
 
56
- bool JHybridNitroSseSpec::equals(const std::shared_ptr<HybridObject>& other) {
57
- if (auto otherCast = std::dynamic_pointer_cast<JHybridNitroSseSpec>(other)) {
58
- return _javaPart == otherCast->_javaPart;
54
+ std::shared_ptr<JHybridObject> JHybridNitroSseSpec::CxxPart::createHybridObject(const jni::local_ref<JHybridObject::JavaPart>& javaPart) {
55
+ auto castJavaPart = jni::dynamic_ref_cast<JHybridNitroSseSpec::JavaPart>(javaPart);
56
+ if (castJavaPart == nullptr) [[unlikely]] {
57
+ throw std::runtime_error("Failed to cast JHybridObject::JavaPart to JHybridNitroSseSpec::JavaPart!");
59
58
  }
60
- return false;
61
- }
62
-
63
- void JHybridNitroSseSpec::dispose() noexcept {
64
- static const auto method = javaClassStatic()->getMethod<void()>("dispose");
65
- method(_javaPart);
59
+ return std::make_shared<JHybridNitroSseSpec>(castJavaPart);
66
60
  }
67
61
 
68
- std::string JHybridNitroSseSpec::toString() {
69
- static const auto method = javaClassStatic()->getMethod<jni::JString()>("toString");
70
- auto javaString = method(_javaPart);
71
- return javaString->toStdString();
62
+ void JHybridNitroSseSpec::CxxPart::registerNatives() {
63
+ registerHybrid({
64
+ makeNativeMethod("initHybrid", JHybridNitroSseSpec::CxxPart::initHybrid),
65
+ });
72
66
  }
73
67
 
74
68
  // Properties
@@ -76,23 +70,23 @@ namespace margelo::nitro::nitrosse {
76
70
 
77
71
  // Methods
78
72
  void JHybridNitroSseSpec::setup(const SseConfig& config, const std::function<void(const std::vector<SseEvent>& /* events */)>& onEvent) {
79
- static const auto method = javaClassStatic()->getMethod<void(jni::alias_ref<JSseConfig> /* config */, jni::alias_ref<JFunc_void_std__vector_SseEvent_::javaobject> /* onEvent */)>("setup_cxx");
73
+ static const auto method = _javaPart->javaClassStatic()->getMethod<void(jni::alias_ref<JSseConfig> /* config */, jni::alias_ref<JFunc_void_std__vector_SseEvent_::javaobject> /* onEvent */)>("setup_cxx");
80
74
  method(_javaPart, JSseConfig::fromCpp(config), JFunc_void_std__vector_SseEvent__cxx::fromCpp(onEvent));
81
75
  }
82
76
  void JHybridNitroSseSpec::start() {
83
- static const auto method = javaClassStatic()->getMethod<void()>("start");
77
+ static const auto method = _javaPart->javaClassStatic()->getMethod<void()>("start");
84
78
  method(_javaPart);
85
79
  }
86
80
  void JHybridNitroSseSpec::stop() {
87
- static const auto method = javaClassStatic()->getMethod<void()>("stop");
81
+ static const auto method = _javaPart->javaClassStatic()->getMethod<void()>("stop");
88
82
  method(_javaPart);
89
83
  }
90
84
  void JHybridNitroSseSpec::setLastProcessedId(const std::string& id) {
91
- static const auto method = javaClassStatic()->getMethod<void(jni::alias_ref<jni::JString> /* id */)>("setLastProcessedId");
85
+ static const auto method = _javaPart->javaClassStatic()->getMethod<void(jni::alias_ref<jni::JString> /* id */)>("setLastProcessedId");
92
86
  method(_javaPart, jni::make_jstring(id));
93
87
  }
94
88
  void JHybridNitroSseSpec::updateHeaders(const std::unordered_map<std::string, std::string>& headers) {
95
- static const auto method = javaClassStatic()->getMethod<void(jni::alias_ref<jni::JMap<jni::JString, jni::JString>> /* headers */)>("updateHeaders");
89
+ static const auto method = _javaPart->javaClassStatic()->getMethod<void(jni::alias_ref<jni::JMap<jni::JString, jni::JString>> /* headers */)>("updateHeaders");
96
90
  method(_javaPart, [&]() -> jni::local_ref<jni::JMap<jni::JString, jni::JString>> {
97
91
  auto __map = jni::JHashMap<jni::JString, jni::JString>::create(headers.size());
98
92
  for (const auto& __entry : headers) {
@@ -102,20 +96,20 @@ namespace margelo::nitro::nitrosse {
102
96
  }());
103
97
  }
104
98
  SseStats JHybridNitroSseSpec::getStats() {
105
- static const auto method = javaClassStatic()->getMethod<jni::local_ref<JSseStats>()>("getStats");
99
+ static const auto method = _javaPart->javaClassStatic()->getMethod<jni::local_ref<JSseStats>()>("getStats");
106
100
  auto __result = method(_javaPart);
107
101
  return __result->toCpp();
108
102
  }
109
103
  void JHybridNitroSseSpec::flush() {
110
- static const auto method = javaClassStatic()->getMethod<void()>("flush");
104
+ static const auto method = _javaPart->javaClassStatic()->getMethod<void()>("flush");
111
105
  method(_javaPart);
112
106
  }
113
107
  void JHybridNitroSseSpec::restart() {
114
- static const auto method = javaClassStatic()->getMethod<void()>("restart");
108
+ static const auto method = _javaPart->javaClassStatic()->getMethod<void()>("restart");
115
109
  method(_javaPart);
116
110
  }
117
111
  bool JHybridNitroSseSpec::isConnected() {
118
- static const auto method = javaClassStatic()->getMethod<jboolean()>("isConnected");
112
+ static const auto method = _javaPart->javaClassStatic()->getMethod<jboolean()>("isConnected");
119
113
  auto __result = method(_javaPart);
120
114
  return static_cast<bool>(__result);
121
115
  }
@@ -18,34 +18,33 @@ namespace margelo::nitro::nitrosse {
18
18
 
19
19
  using namespace facebook;
20
20
 
21
- class JHybridNitroSseSpec: public jni::HybridClass<JHybridNitroSseSpec, JHybridObject>,
22
- public virtual HybridNitroSseSpec {
21
+ class JHybridNitroSseSpec: public virtual HybridNitroSseSpec, public virtual JHybridObject {
23
22
  public:
24
- static auto constexpr kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/HybridNitroSseSpec;";
25
- static jni::local_ref<jhybriddata> initHybrid(jni::alias_ref<jhybridobject> jThis);
26
- static void registerNatives();
27
-
28
- protected:
29
- // C++ constructor (called from Java via `initHybrid()`)
30
- explicit JHybridNitroSseSpec(jni::alias_ref<jhybridobject> jThis) :
31
- HybridObject(HybridNitroSseSpec::TAG),
32
- HybridBase(jThis),
33
- _javaPart(jni::make_global(jThis)) {}
23
+ struct JavaPart: public jni::JavaClass<JavaPart, JHybridObject::JavaPart> {
24
+ static auto constexpr kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/HybridNitroSseSpec;";
25
+ std::shared_ptr<JHybridNitroSseSpec> getJHybridNitroSseSpec();
26
+ };
27
+ struct CxxPart: public jni::HybridClass<CxxPart, JHybridObject::CxxPart> {
28
+ static auto constexpr kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/HybridNitroSseSpec$CxxPart;";
29
+ static jni::local_ref<jhybriddata> initHybrid(jni::alias_ref<jhybridobject> jThis);
30
+ static void registerNatives();
31
+ using HybridBase::HybridBase;
32
+ protected:
33
+ std::shared_ptr<JHybridObject> createHybridObject(const jni::local_ref<JHybridObject::JavaPart>& javaPart) override;
34
+ };
34
35
 
35
36
  public:
37
+ explicit JHybridNitroSseSpec(const jni::local_ref<JHybridNitroSseSpec::JavaPart>& javaPart):
38
+ HybridObject(HybridNitroSseSpec::TAG),
39
+ JHybridObject(javaPart),
40
+ _javaPart(jni::make_global(javaPart)) {}
36
41
  ~JHybridNitroSseSpec() override {
37
42
  // Hermes GC can destroy JS objects on a non-JNI Thread.
38
43
  jni::ThreadScope::WithClassLoader([&] { _javaPart.reset(); });
39
44
  }
40
45
 
41
46
  public:
42
- size_t getExternalMemorySize() noexcept override;
43
- bool equals(const std::shared_ptr<HybridObject>& other) override;
44
- void dispose() noexcept override;
45
- std::string toString() override;
46
-
47
- public:
48
- inline const jni::global_ref<JHybridNitroSseSpec::javaobject>& getJavaPart() const noexcept {
47
+ inline const jni::global_ref<JHybridNitroSseSpec::JavaPart>& getJavaPart() const noexcept {
49
48
  return _javaPart;
50
49
  }
51
50
 
@@ -66,9 +65,7 @@ namespace margelo::nitro::nitrosse {
66
65
  bool isConnected() override;
67
66
 
68
67
  private:
69
- friend HybridBase;
70
- using HybridBase::HybridBase;
71
- jni::global_ref<JHybridNitroSseSpec::javaobject> _javaPart;
68
+ jni::global_ref<JHybridNitroSseSpec::JavaPart> _javaPart;
72
69
  };
73
70
 
74
71
  } // namespace margelo::nitro::nitrosse
@@ -24,23 +24,6 @@ import com.margelo.nitro.core.HybridObject
24
24
  "LocalVariableName", "PropertyName", "PrivatePropertyName", "FunctionName"
25
25
  )
26
26
  abstract class HybridNitroSseSpec: HybridObject() {
27
- @DoNotStrip
28
- private var mHybridData: HybridData = initHybrid()
29
-
30
- init {
31
- super.updateNative(mHybridData)
32
- }
33
-
34
- override fun updateNative(hybridData: HybridData) {
35
- mHybridData = hybridData
36
- super.updateNative(hybridData)
37
- }
38
-
39
- // Default implementation of `HybridObject.toString()`
40
- override fun toString(): String {
41
- return "[HybridObject NitroSse]"
42
- }
43
-
44
27
  // Properties
45
28
 
46
29
 
@@ -86,7 +69,21 @@ abstract class HybridNitroSseSpec: HybridObject() {
86
69
  @Keep
87
70
  abstract fun isConnected(): Boolean
88
71
 
89
- private external fun initHybrid(): HybridData
72
+ // Default implementation of `HybridObject.toString()`
73
+ override fun toString(): String {
74
+ return "[HybridObject NitroSse]"
75
+ }
76
+
77
+ // C++ backing class
78
+ @DoNotStrip
79
+ @Keep
80
+ protected open class CxxPart(javaPart: HybridNitroSseSpec): HybridObject.CxxPart(javaPart) {
81
+ // C++ JHybridNitroSseSpec::CxxPart::initHybrid(...)
82
+ external override fun initHybrid(): HybridData
83
+ }
84
+ override fun createCxxPart(): CxxPart {
85
+ return CxxPart(this)
86
+ }
90
87
 
91
88
  companion object {
92
89
  protected const val TAG = "HybridNitroSseSpec"
@@ -27,21 +27,28 @@ int initialize(JavaVM* vm) {
27
27
  });
28
28
  }
29
29
 
30
+ struct JHybridNitroSseSpecImpl: public jni::JavaClass<JHybridNitroSseSpecImpl, JHybridNitroSseSpec::JavaPart> {
31
+ static auto constexpr kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/NitroSse;";
32
+ static std::shared_ptr<JHybridNitroSseSpec> create() {
33
+ static auto constructorFn = javaClassStatic()->getConstructor<JHybridNitroSseSpecImpl::javaobject()>();
34
+ jni::local_ref<JHybridNitroSseSpec::JavaPart> javaPart = javaClassStatic()->newObject(constructorFn);
35
+ return javaPart->getJHybridNitroSseSpec();
36
+ }
37
+ };
38
+
30
39
  void registerAllNatives() {
31
40
  using namespace margelo::nitro;
32
41
  using namespace margelo::nitro::nitrosse;
33
42
 
34
43
  // Register native JNI methods
35
- margelo::nitro::nitrosse::JHybridNitroSseSpec::registerNatives();
44
+ margelo::nitro::nitrosse::JHybridNitroSseSpec::CxxPart::registerNatives();
36
45
  margelo::nitro::nitrosse::JFunc_void_std__vector_SseEvent__cxx::registerNatives();
37
46
 
38
47
  // Register Nitro Hybrid Objects
39
48
  HybridObjectRegistry::registerHybridObjectConstructor(
40
49
  "NitroSse",
41
50
  []() -> std::shared_ptr<HybridObject> {
42
- static DefaultConstructableObject<JHybridNitroSseSpec::javaobject> object("com/margelo/nitro/nitrosse/NitroSse");
43
- auto instance = object.create();
44
- return instance->cthis()->shared();
51
+ return JHybridNitroSseSpecImpl::create();
45
52
  }
46
53
  );
47
54
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-nitro-sse",
3
- "version": "1.3.1",
3
+ "version": "1.4.1",
4
4
  "description": "High-performance Server-Sent Events (SSE) for React Native, powered by Nitro Modules.",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",
@@ -84,12 +84,12 @@
84
84
  "eslint-plugin-prettier": "^5.5.4",
85
85
  "jest": "^29.7.0",
86
86
  "lefthook": "^2.0.3",
87
- "nitrogen": "0.34.1",
87
+ "nitrogen": "0.35.0",
88
88
  "prettier": "^2.8.8",
89
89
  "react": "19.2.0",
90
90
  "react-native": "0.83.0",
91
91
  "react-native-builder-bob": "^0.40.17",
92
- "react-native-nitro-modules": "0.34.1",
92
+ "react-native-nitro-modules": "0.35.0",
93
93
  "release-it": "^19.0.4",
94
94
  "turbo": "^2.5.6",
95
95
  "typescript": "^5.9.2"
@@ -97,7 +97,7 @@
97
97
  "peerDependencies": {
98
98
  "react": "*",
99
99
  "react-native": "*",
100
- "react-native-nitro-modules": "0.34.1"
100
+ "react-native-nitro-modules": "0.35.0"
101
101
  },
102
102
  "workspaces": [
103
103
  "example"