react-native-nitro-sse 2.0.0 → 2.1.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.
Files changed (25) hide show
  1. package/README.md +2 -0
  2. package/android/build.gradle +1 -0
  3. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +74 -16
  4. package/ios/NitroSse.swift +42 -28
  5. package/lib/module/SseInterface.js +2 -0
  6. package/lib/typescript/src/SseInterface.d.ts +10 -1
  7. package/lib/typescript/src/SseInterface.d.ts.map +1 -1
  8. package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +2 -0
  9. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +2 -0
  10. package/nitrogen/generated/android/c++/JSseConfig.hpp +5 -1
  11. package/nitrogen/generated/android/c++/JSseEvent.hpp +7 -1
  12. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +7 -4
  13. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +6 -3
  14. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +16 -0
  15. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +1 -0
  16. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +1 -0
  17. package/nitrogen/generated/ios/swift/SseConfig.swift +19 -1
  18. package/nitrogen/generated/ios/swift/SseEvent.swift +19 -1
  19. package/nitrogen/generated/shared/c++/SseConfig.hpp +5 -1
  20. package/nitrogen/generated/shared/c++/SseEvent.hpp +6 -1
  21. package/package.json +9 -4
  22. package/src/SseInterface.ts +10 -1
  23. package/android/src/test/java/com/margelo/nitro/nitrosse/HeartbeatScannerTest.kt +0 -98
  24. package/android/src/test/java/com/margelo/nitro/nitrosse/NitroSseLogicTest.kt +0 -238
  25. package/ios/Tests/NitroSseTests.swift +0 -242
package/README.md CHANGED
@@ -33,6 +33,7 @@ npm install react-native-nitro-sse react-native-nitro-modules
33
33
 
34
34
  | react-native-nitro-sse | react-native-nitro-modules |
35
35
  | :--------------------- | :------------------------- |
36
+ | **2.0.0 - latest** | **0.35.2** |
36
37
  | **1.6.2** | **0.35.2** |
37
38
  | **1.4.0 - 1.6.1** | **0.35.0** |
38
39
  | **1.2.2 - 1.3.1** | **0.34.1** |
@@ -108,6 +109,7 @@ console.log(`Reconnections: ${stats.reconnectCount}`);
108
109
  | `connectionTimeoutMs`| `number` | `15000` | Max time for initial handshake / connect. |
109
110
  | `readTimeoutMs` | `number` | `300000`| Max idle time between data packets before reconnecting. |
110
111
  | `backgroundExecution` | `boolean` | `false` | (iOS) Attempt to maintain connection via background tasks. |
112
+ | `autoParseJSON` | `boolean` | `false` | Automatically parse message data as JSON in a background native thread. Result is in `parsedData`. |
111
113
  | `onBeforeRequest` | `function`| - | Async hook to refresh headers/tokens before every attempt. |
112
114
 
113
115
  ---
@@ -120,4 +120,5 @@ dependencies {
120
120
  implementation "androidx.lifecycle:lifecycle-process:2.8.7"
121
121
 
122
122
  testImplementation "junit:junit:4.13.2"
123
+ testImplementation "org.json:json:20240303"
123
124
  }
@@ -11,6 +11,9 @@ import okhttp3.sse.EventSource
11
11
  import okhttp3.sse.EventSources
12
12
  import okhttp3.sse.EventSourceListener
13
13
  import okio.*
14
+ import com.margelo.nitro.core.AnyMap
15
+ import org.json.JSONObject
16
+ import org.json.JSONArray
14
17
  import androidx.lifecycle.DefaultLifecycleObserver
15
18
  import androidx.lifecycle.LifecycleOwner
16
19
  import androidx.lifecycle.ProcessLifecycleOwner
@@ -68,6 +71,40 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
68
71
 
69
72
  companion object {
70
73
  private const val TAG = "NitroSse"
74
+
75
+ internal fun jsonObjectToMap(jsonObject: JSONObject): Map<String, Any?> {
76
+ val map = mutableMapOf<String, Any?>()
77
+ val keys = jsonObject.keys()
78
+ while (keys.hasNext()) {
79
+ val key = keys.next()
80
+ var value = jsonObject.get(key)
81
+ if (value is JSONObject) {
82
+ value = jsonObjectToMap(value)
83
+ } else if (value is JSONArray) {
84
+ value = jsonArrayToList(value)
85
+ } else if (value == JSONObject.NULL) {
86
+ value = null
87
+ }
88
+ map[key] = value
89
+ }
90
+ return map
91
+ }
92
+
93
+ internal fun jsonArrayToList(jsonArray: JSONArray): List<Any?> {
94
+ val list = mutableListOf<Any?>()
95
+ for (i in 0 until jsonArray.length()) {
96
+ var value = jsonArray.get(i)
97
+ if (value is JSONObject) {
98
+ value = jsonObjectToMap(value)
99
+ } else if (value is JSONArray) {
100
+ value = jsonArrayToList(value)
101
+ } else if (value == JSONObject.NULL) {
102
+ value = null
103
+ }
104
+ list.add(value)
105
+ }
106
+ return list
107
+ }
71
108
  }
72
109
 
73
110
  /**
@@ -85,10 +122,10 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
85
122
  this.client = OkHttpClient.Builder()
86
123
  .connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
87
124
  .readTimeout((config.readTimeoutMs ?: 300000.0).toLong(), TimeUnit.MILLISECONDS)
88
- .addNetworkInterceptor(HeartbeatNetworkInterceptor(totalBytesReceived) {
89
- pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, "keep-alive", null, null))
90
- })
91
- .build()
125
+ .addNetworkInterceptor(HeartbeatNetworkInterceptor(totalBytesReceived) {
126
+ pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, null, "keep-alive", null, null))
127
+ })
128
+ .build()
92
129
  }
93
130
 
94
131
  if (sseHandlerThread == null) {
@@ -167,6 +204,24 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
167
204
  onEventsCallback?.invoke(eventsToEmit)
168
205
  }
169
206
 
207
+ private fun parseJsonToAnyMap(data: String): AnyMap? {
208
+ return try {
209
+ val trimmed = data.trim()
210
+ if (trimmed.startsWith("{")) {
211
+ val jsonObject = JSONObject(trimmed)
212
+ val map = jsonObjectToMap(jsonObject)
213
+ AnyMap.fromMap(map, true)
214
+ } else {
215
+ // AnyMap represents a JS Object (Map).
216
+ // If it's a JSON array or primitive, we currently don't support auto-parsing into AnyMap.
217
+ null
218
+ }
219
+ } catch (e: Exception) {
220
+ Log.w(TAG, "Failed to parse JSON: ${e.message}")
221
+ null
222
+ }
223
+ }
224
+
170
225
  /**
171
226
  * Manually set the last seen event ID.
172
227
  * This will be used as the 'Last-Event-ID' header on the next connection attempt.
@@ -286,7 +341,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
286
341
  sseHandler?.post {
287
342
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
288
343
  Log.e(TAG, "Request Interceptor Error: ${t?.message}")
289
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null))
344
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null))
290
345
 
291
346
  // Reconnect with delay
292
347
  val currentJitterFactor = config?.jitterFactor ?: 0.5
@@ -369,7 +424,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
369
424
  backoffCounter = 0
370
425
  currentReconnectAttempts = 0
371
426
  synchronized(this@NitroSse) {
372
- pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null, response.code.toDouble(), null))
427
+ pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null, null, response.code.toDouble(), null))
373
428
  }
374
429
  }
375
430
  }
@@ -389,8 +444,11 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
389
444
  if (!id.isNullOrEmpty()) {
390
445
  this@NitroSse.lastProcessedId = id
391
446
  }
447
+
448
+ val parsedData = if (config?.autoParseJSON == true) parseJsonToAnyMap(data) else null
449
+
392
450
  synchronized(this@NitroSse) {
393
- pushEventToBuffer(SseEvent(SseEventType.MESSAGE, data, id, type, null, 200.0, null))
451
+ pushEventToBuffer(SseEvent(SseEventType.MESSAGE, data, parsedData, id, type, null, 200.0, null))
394
452
  }
395
453
  }
396
454
  }
@@ -433,25 +491,25 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
433
491
  if (statusCode == 401 || statusCode == 403) {
434
492
  val currentConfig = synchronized(this@NitroSse) { config }
435
493
  if (currentConfig?.onBeforeRequest == null) {
436
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble(), null))
494
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble(), null))
437
495
  stop()
438
496
  return@post
439
497
  }
440
498
 
441
499
  val retries = consecutiveAuthErrors.incrementAndGet()
442
500
  if (retries >= maxAuthRetries) {
443
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Auth Error ($statusCode) - Retry limit reached ($maxAuthRetries). Stopping.", statusCode.toDouble(), null))
501
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - Retry limit reached ($maxAuthRetries). Stopping.", statusCode.toDouble(), null))
444
502
  stop()
445
503
  return@post
446
504
  }
447
505
 
448
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Auth Error ($statusCode) - Retry $retries/$maxAuthRetries. Refreshing token...", statusCode.toDouble(), null))
506
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - Retry $retries/$maxAuthRetries. Refreshing token...", statusCode.toDouble(), null))
449
507
  scheduleReconnect(true)
450
508
  return@post
451
509
  }
452
510
 
453
511
  if (statusCode == 400) {
454
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Fatal Error ($statusCode). Stopping.", statusCode.toDouble(), null))
512
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Fatal Error ($statusCode). Stopping.", statusCode.toDouble(), null))
455
513
  stop()
456
514
  return@post
457
515
  }
@@ -460,7 +518,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
460
518
  if ((statusCode == 429 || statusCode == 503) && retryAfterMillis != null) {
461
519
  val jitter = (500 + Random.nextInt(1500)).toLong()
462
520
  val totalDelay = retryAfterMillis + jitter
463
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Retry-After received: ${totalDelay/1000}s", statusCode.toDouble(), totalDelay.toDouble()))
521
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Retry-After received: ${totalDelay/1000}s", statusCode.toDouble(), totalDelay.toDouble()))
464
522
  sseHandler?.postDelayed({
465
523
  if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection(connectionAttemptVersion.get())
466
524
  }, totalDelay)
@@ -468,18 +526,18 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
468
526
  }
469
527
 
470
528
  if (statusCode == 429) {
471
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Rate Limited (429) without Retry-After. Stopping.", 429.0, null))
529
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Rate Limited (429) without Retry-After. Stopping.", 429.0, null))
472
530
  stop()
473
531
  return@post
474
532
  }
475
533
 
476
534
  if (statusCode == 204) {
477
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "No Content (204). Stopping.", 204.0, null))
535
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "No Content (204). Stopping.", 204.0, null))
478
536
  stop()
479
537
  return@post
480
538
  }
481
539
 
482
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, t?.message ?: "Link lost ($statusCode)", if (statusCode != -1) statusCode.toDouble() else null, null))
540
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, t?.message ?: "Link lost ($statusCode)", if (statusCode != -1) statusCode.toDouble() else null, null))
483
541
  scheduleReconnect(true)
484
542
  }
485
543
  }
@@ -525,7 +583,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
525
583
  val maxAttempts = (currentConfig.maxReconnectAttempts ?: -1.0).toInt()
526
584
  if (maxAttempts != -1 && currentReconnectAttempts >= maxAttempts) {
527
585
  Log.d(TAG, "Max reconnection attempts reached ($maxAttempts). Stopping.")
528
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Max reconnection attempts reached ($maxAttempts).", null, null))
586
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Max reconnection attempts reached ($maxAttempts).", null, null))
529
587
  stop()
530
588
  return
531
589
  }
@@ -152,20 +152,30 @@ class NitroSse: HybridNitroSseSpec {
152
152
  }
153
153
  }
154
154
  }
155
-
156
155
  private func flushEventsToJs() {
157
156
  dispatchPrecondition(condition: .onQueue(sseQueue))
158
- guard !eventBuffer.isEmpty else {
159
- isFlushPending = false
160
- return
161
- }
157
+ guard !eventBuffer.isEmpty else { return }
162
158
 
163
159
  let batch = eventBuffer
164
160
  eventBuffer.removeAll()
165
161
  isFlushPending = false
162
+
166
163
  onEventsCallback?(batch)
167
164
  }
168
165
 
166
+ internal func parseJsonToAnyMap(_ data: String) -> AnyMap? {
167
+ guard let jsonData = data.data(using: .utf8) else { return nil }
168
+ do {
169
+ if let dictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any?] {
170
+ return AnyMap.fromDictionaryIgnoreIncompatible(dictionary)
171
+ }
172
+ } catch {
173
+ // Non-fatal, just log and return nil
174
+ print("[NitroSse] Failed to parse JSON: \(error.localizedDescription)")
175
+ }
176
+ return nil
177
+ }
178
+
169
179
  /**
170
180
  * Manually set the last seen event ID.
171
181
  * This will be used as the 'Last-Event-ID' header on the next connection attempt.
@@ -196,6 +206,7 @@ class NitroSse: HybridNitroSseSpec {
196
206
  maxRetryIntervalMs: config.maxRetryIntervalMs,
197
207
  jitterFactor: config.jitterFactor,
198
208
  maxReconnectAttempts: config.maxReconnectAttempts,
209
+ autoParseJSON: config.autoParseJSON,
199
210
  onBeforeRequest: config.onBeforeRequest
200
211
  )
201
212
  print("[NitroSse] Headers updated for subsequent connections.")
@@ -265,8 +276,8 @@ class NitroSse: HybridNitroSseSpec {
265
276
 
266
277
  sseQueue.asyncAfter(deadline: .now() + (timeoutMs / 1000.0)) { [weak self] in
267
278
  guard let self = self else { return }
268
- self.sseQueue.async {
269
- guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
279
+ self.sseQueue.async { [weak self] in
280
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
270
281
  if !flag.isCompleted {
271
282
  flag.isCompleted = true
272
283
  let error = NSError(domain: "NitroSse", code: -1, userInfo: [NSLocalizedDescriptionKey: "onBeforeRequest interceptor timed out after \(timeoutMs) ms"])
@@ -277,7 +288,7 @@ class NitroSse: HybridNitroSseSpec {
277
288
 
278
289
  interceptor().then { [weak self] promise2 in
279
290
  promise2.then { [weak self] newHeaders in
280
- self?.sseQueue.async {
291
+ self?.sseQueue.async { [weak self] in
281
292
  guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
282
293
  if !flag.isCompleted {
283
294
  flag.isCompleted = true
@@ -300,13 +311,14 @@ class NitroSse: HybridNitroSseSpec {
300
311
  maxRetryIntervalMs: currentConfig.maxRetryIntervalMs,
301
312
  jitterFactor: currentConfig.jitterFactor,
302
313
  maxReconnectAttempts: currentConfig.maxReconnectAttempts,
314
+ autoParseJSON: currentConfig.autoParseJSON,
303
315
  onBeforeRequest: currentConfig.onBeforeRequest
304
316
  )
305
317
  self.performEstablishConnection(attemptVersion: attemptVersion)
306
318
  }
307
319
  }
308
320
  }.catch { [weak self] error in
309
- self?.sseQueue.async {
321
+ self?.sseQueue.async { [weak self] in
310
322
  guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
311
323
  if !flag.isCompleted {
312
324
  flag.isCompleted = true
@@ -315,7 +327,7 @@ class NitroSse: HybridNitroSseSpec {
315
327
  }
316
328
  }
317
329
  }.catch { [weak self] error in
318
- self?.sseQueue.async {
330
+ self?.sseQueue.async { [weak self] in
319
331
  guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
320
332
  if !flag.isCompleted {
321
333
  flag.isCompleted = true
@@ -332,7 +344,7 @@ class NitroSse: HybridNitroSseSpec {
332
344
  dispatchPrecondition(condition: .onQueue(sseQueue))
333
345
  guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
334
346
  print("[NitroSse] Interceptor failed: \(error.localizedDescription)")
335
- self.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Interceptor Error: \(error.localizedDescription)", statusCode: -1, retry: nil))
347
+ self.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Interceptor Error: \(error.localizedDescription)", statusCode: -1, retry: nil))
336
348
  // Reconnect after delay
337
349
  self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
338
350
  }
@@ -480,7 +492,7 @@ class NitroSse: HybridNitroSseSpec {
480
492
  let maxAttempts = Int(config?.maxReconnectAttempts ?? -1.0)
481
493
  if maxAttempts != -1 && currentReconnectAttempts >= maxAttempts {
482
494
  print("[NitroSse] Max reconnection attempts reached (\(maxAttempts)). Stopping.")
483
- self.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Max reconnection attempts reached (\(maxAttempts)).", statusCode: nil, retry: nil))
495
+ self.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Max reconnection attempts reached (\(maxAttempts)).", statusCode: nil, retry: nil))
484
496
  self.stopInternal()
485
497
  return
486
498
  }
@@ -522,18 +534,18 @@ class NitroSse: HybridNitroSseSpec {
522
534
  ///
523
535
  /// If this handler corresponds to the active connection and its attempt version matches the parent's current connectionAttemptVersion, resets `backoffCounter`, `currentReconnectAttempts`, and `consecutiveAuthErrors`, and enqueues an `.open` `SseEvent` with status code 200.
524
536
  func onOpened() {
525
- guard let parent = parent, source === parent.eventSource else { return }
537
+ guard let parent = self.parent, source === parent.eventSource else { return }
526
538
  parent.sseQueue.async { [weak parent] in
527
539
  guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
528
540
  parent.backoffCounter = 0
529
541
  parent.currentReconnectAttempts = 0
530
542
  parent.consecutiveAuthErrors = 0
531
- parent.pushEventToBuffer(SseEvent(type: .open, data: nil, id: nil, event: nil, message: nil, statusCode: 200, retry: nil))
543
+ parent.pushEventToBuffer(SseEvent(type: .open, data: nil, parsedData: nil, id: nil, event: nil, message: nil, statusCode: 200, retry: nil))
532
544
  }
533
545
  }
534
546
 
535
547
  func onClosed() {
536
- guard let parent = parent, source === parent.eventSource else { return }
548
+ guard let parent = self.parent, source === parent.eventSource else { return }
537
549
  parent.sseQueue.async { [weak parent] in
538
550
  guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
539
551
  if let rid = parent.requestId {
@@ -547,7 +559,7 @@ class NitroSse: HybridNitroSseSpec {
547
559
  }
548
560
 
549
561
  func onMessage(eventType: String, messageEvent: MessageEvent) {
550
- guard let parent = parent, source === parent.eventSource else { return }
562
+ guard let parent = self.parent, source === parent.eventSource else { return }
551
563
  parent.sseQueue.async { [weak parent] in
552
564
  guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
553
565
  let encodedDataSize = Double(messageEvent.data.utf8.count)
@@ -558,21 +570,23 @@ class NitroSse: HybridNitroSseSpec {
558
570
  parent.lastProcessedId = messageEvent.lastEventId
559
571
  }
560
572
 
561
- parent.pushEventToBuffer(SseEvent(type: .message, data: messageEvent.data, id: messageEvent.lastEventId, event: eventType, message: nil, statusCode: 200, retry: nil))
573
+ let parsedData = (parent.config?.autoParseJSON == true) ? parent.parseJsonToAnyMap(messageEvent.data) : nil
574
+
575
+ parent.pushEventToBuffer(SseEvent(type: .message, data: messageEvent.data, parsedData: parsedData, id: messageEvent.lastEventId, event: eventType, message: nil, statusCode: 200, retry: nil))
562
576
  }
563
577
  }
564
578
 
565
579
  func onComment(comment: String) {
566
- guard let parent = parent, source === parent.eventSource else { return }
580
+ guard let parent = self.parent, source === parent.eventSource else { return }
567
581
  parent.sseQueue.async { [weak parent] in
568
582
  guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
569
583
  parent.totalBytesReceived += Double(comment.utf8.count)
570
- parent.pushEventToBuffer(SseEvent(type: .heartbeat, data: nil, id: nil, event: nil, message: comment, statusCode: nil, retry: nil))
584
+ parent.pushEventToBuffer(SseEvent(type: .heartbeat, data: nil, parsedData: nil, id: nil, event: nil, message: comment, statusCode: nil, retry: nil))
571
585
  }
572
586
  }
573
587
 
574
588
  func onError(error: Error) {
575
- guard let parent = parent, source === parent.eventSource else { return }
589
+ guard let parent = self.parent, source === parent.eventSource else { return }
576
590
  parent.sseQueue.async { [weak parent] in
577
591
  guard let parent = parent, parent.isRunning, self.attemptVersion == parent.connectionAttemptVersion else { return }
578
592
  let nsError = error as NSError
@@ -586,33 +600,33 @@ class NitroSse: HybridNitroSseSpec {
586
600
  parent.requestId = nil
587
601
 
588
602
  if statusCode == 204 {
589
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "No Content (204). Stopping.", statusCode: 204, retry: nil))
603
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "No Content (204). Stopping.", statusCode: 204, retry: nil))
590
604
  parent.stopInternal()
591
605
  return
592
606
  }
593
607
 
594
608
  if statusCode == 401 || statusCode == 403 {
595
609
  if parent.config?.onBeforeRequest == nil {
596
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - No interceptor provided. Stopping.", statusCode: Double(statusCode), retry: nil))
610
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - No interceptor provided. Stopping.", statusCode: Double(statusCode), retry: nil))
597
611
  parent.stopInternal()
598
612
  return
599
613
  }
600
614
 
601
615
  parent.consecutiveAuthErrors += 1
602
616
  if parent.consecutiveAuthErrors >= parent.maxAuthRetries {
603
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - Retry limit reached (\(parent.maxAuthRetries)). Stopping.", statusCode: Double(statusCode), retry: nil))
617
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - Retry limit reached (\(parent.maxAuthRetries)). Stopping.", statusCode: Double(statusCode), retry: nil))
604
618
  parent.stopInternal()
605
619
  return
606
620
  }
607
621
 
608
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - Retry \(parent.consecutiveAuthErrors)/\(parent.maxAuthRetries). Refreshing token...", statusCode: Double(statusCode), retry: nil))
622
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - Retry \(parent.consecutiveAuthErrors)/\(parent.maxAuthRetries). Refreshing token...", statusCode: Double(statusCode), retry: nil))
609
623
  parent.scheduleAutomaticReconnect(isError: true, attemptVersion: self.attemptVersion)
610
624
  return
611
625
  }
612
626
 
613
627
  let isFatal = (statusCode == 400)
614
628
  if isFatal {
615
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Fatal Error (\(statusCode)). Stopping.", statusCode: Double(statusCode), retry: nil))
629
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Fatal Error (\(statusCode)). Stopping.", statusCode: Double(statusCode), retry: nil))
616
630
  parent.stopInternal()
617
631
  return
618
632
  }
@@ -621,18 +635,18 @@ class NitroSse: HybridNitroSseSpec {
621
635
  if (statusCode == 429 || statusCode == 503), let retryAfter = retryAfterSeconds {
622
636
  let jitter = Double.random(in: 0.5...1.5)
623
637
  let totalDelay = retryAfter + jitter
624
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Retry-After received: \(Int(totalDelay))s", statusCode: Double(statusCode), retry: totalDelay * 1000.0))
638
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Retry-After received: \(Int(totalDelay))s", statusCode: Double(statusCode), retry: totalDelay * 1000.0))
625
639
  parent.scheduleAutomaticReconnectWithFixedDelay(totalDelay, attemptVersion: self.attemptVersion)
626
640
  return
627
641
  }
628
642
 
629
643
  if statusCode == 429 {
630
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Rate Limited (429) without Retry-After. Stopping.", statusCode: 429, retry: nil))
644
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Rate Limited (429) without Retry-After. Stopping.", statusCode: 429, retry: nil))
631
645
  parent.stopInternal()
632
646
  return
633
647
  }
634
648
 
635
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: error.localizedDescription, statusCode: Double(statusCode), retry: nil))
649
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: error.localizedDescription, statusCode: Double(statusCode), retry: nil))
636
650
  parent.scheduleAutomaticReconnect(isError: true, attemptVersion: self.attemptVersion)
637
651
  }
638
652
  }
@@ -1,2 +1,4 @@
1
1
  "use strict";
2
+
3
+ export {};
2
4
  //# sourceMappingURL=SseInterface.js.map
@@ -1,3 +1,4 @@
1
+ import type { AnyMap } from 'react-native-nitro-modules';
1
2
  /**
2
3
  * HTTP method to use for the SSE connection.
3
4
  */
@@ -78,6 +79,12 @@ export interface SseConfig {
78
79
  * @default -1
79
80
  */
80
81
  maxReconnectAttempts?: number;
82
+ /**
83
+ * Whether to automatically parse message data as JSON in a background native thread.
84
+ * If true, and parsing succeeds, the result will be available in the 'parsedData' field.
85
+ * @default false
86
+ */
87
+ autoParseJSON?: boolean;
81
88
  /**
82
89
  * Async interceptor called before every connection attempt (including auto-reconnects).
83
90
  * Use this to refresh tokens or calculate dynamic headers.
@@ -91,8 +98,10 @@ export interface SseConfig {
91
98
  export interface SseEvent {
92
99
  /** The type of the event. */
93
100
  type: SseEventType;
94
- /** The data payload of the event. */
101
+ /** The data payload of the event as a raw string. */
95
102
  data?: string;
103
+ /** The parsed JSON data, if autoParseJSON is enabled and parsing succeeds. */
104
+ parsedData?: AnyMap;
96
105
  /** The event ID, if provided. */
97
106
  id?: string;
98
107
  /** The event name, if provided (internal 'event' field in SSE). */
@@ -1 +1 @@
1
- {"version":3,"file":"SseInterface.d.ts","sourceRoot":"","sources":["../../../src/SseInterface.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,MAAM,CAAC;AAExC;;;;;;;GAOG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,GAAG,WAAW,CAAC;AAEhF;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,mCAAmC;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,oCAAoC;IACpC,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,qDAAqD;IACrD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,8BAA8B;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;;OAKG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;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MAAM,MAAM,WAAW,GAAG,CAAC,KAAK,EAAE,QAAQ,KAAK,IAAI,CAAC;AAEpD;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB;;;;OAIG;IACH,KAAK,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,QAAQ,EAAE,KAAK,IAAI,GAAG,IAAI,CAAC;IAEvE;;;OAGG;IACH,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,GAAG,IAAI,CAAC;IAE5D;;OAEG;IACH,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,GAAG,IAAI,CAAC;IAE/D,4BAA4B;IAC5B,KAAK,IAAI,IAAI,CAAC;IACd,2BAA2B;IAC3B,IAAI,IAAI,IAAI,CAAC;IACb,6CAA6C;IAC7C,OAAO,IAAI,IAAI,CAAC;IAChB,yCAAyC;IACzC,KAAK,IAAI,IAAI,CAAC;IACd,uBAAuB;IACvB,WAAW,IAAI,OAAO,CAAC;IACvB,iBAAiB;IACjB,QAAQ,IAAI,QAAQ,CAAC;IACrB,+BAA+B;IAC/B,aAAa,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAC;IACrD,yBAAyB;IACzB,kBAAkB,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;CACtC"}
@@ -19,6 +19,8 @@
19
19
  #include "JSseEventType.hpp"
20
20
  #include <string>
21
21
  #include <optional>
22
+ #include <NitroModules/AnyMap.hpp>
23
+ #include <NitroModules/JAnyMap.hpp>
22
24
 
23
25
  namespace margelo::nitro::nitrosse {
24
26
 
@@ -38,6 +38,8 @@ namespace margelo::nitro::nitrosse { enum class SseEventType; }
38
38
  #include "JSseEvent.hpp"
39
39
  #include "SseEventType.hpp"
40
40
  #include "JSseEventType.hpp"
41
+ #include <NitroModules/AnyMap.hpp>
42
+ #include <NitroModules/JAnyMap.hpp>
41
43
 
42
44
  namespace margelo::nitro::nitrosse {
43
45
 
@@ -66,6 +66,8 @@ namespace margelo::nitro::nitrosse {
66
66
  jni::local_ref<jni::JDouble> jitterFactor = this->getFieldValue(fieldJitterFactor);
67
67
  static const auto fieldMaxReconnectAttempts = clazz->getField<jni::JDouble>("maxReconnectAttempts");
68
68
  jni::local_ref<jni::JDouble> maxReconnectAttempts = this->getFieldValue(fieldMaxReconnectAttempts);
69
+ static const auto fieldAutoParseJSON = clazz->getField<jni::JBoolean>("autoParseJSON");
70
+ jni::local_ref<jni::JBoolean> autoParseJSON = this->getFieldValue(fieldAutoParseJSON);
69
71
  static const auto fieldOnBeforeRequest = clazz->getField<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____::javaobject>("onBeforeRequest");
70
72
  jni::local_ref<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____::javaobject> onBeforeRequest = this->getFieldValue(fieldOnBeforeRequest);
71
73
  return SseConfig(
@@ -89,6 +91,7 @@ namespace margelo::nitro::nitrosse {
89
91
  maxRetryIntervalMs != nullptr ? std::make_optional(maxRetryIntervalMs->value()) : std::nullopt,
90
92
  jitterFactor != nullptr ? std::make_optional(jitterFactor->value()) : std::nullopt,
91
93
  maxReconnectAttempts != nullptr ? std::make_optional(maxReconnectAttempts->value()) : std::nullopt,
94
+ autoParseJSON != nullptr ? std::make_optional(static_cast<bool>(autoParseJSON->value())) : std::nullopt,
92
95
  onBeforeRequest != nullptr ? std::make_optional([&]() -> std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()> {
93
96
  if (onBeforeRequest->isInstanceOf(JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx::javaClassStatic())) [[likely]] {
94
97
  auto downcast = jni::static_ref_cast<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx::javaobject>(onBeforeRequest);
@@ -107,7 +110,7 @@ namespace margelo::nitro::nitrosse {
107
110
  */
108
111
  [[maybe_unused]]
109
112
  static jni::local_ref<JSseConfig::javaobject> fromCpp(const SseConfig& value) {
110
- using JSignature = JSseConfig(jni::alias_ref<jni::JString>, jni::alias_ref<JHttpMethod>, jni::alias_ref<jni::JMap<jni::JString, jni::JString>>, jni::alias_ref<jni::JString>, jni::alias_ref<jni::JBoolean>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____::javaobject>);
113
+ using JSignature = JSseConfig(jni::alias_ref<jni::JString>, jni::alias_ref<JHttpMethod>, jni::alias_ref<jni::JMap<jni::JString, jni::JString>>, jni::alias_ref<jni::JString>, jni::alias_ref<jni::JBoolean>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JBoolean>, jni::alias_ref<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____::javaobject>);
111
114
  static const auto clazz = javaClassStatic();
112
115
  static const auto create = clazz->getStaticMethod<JSignature>("fromCpp");
113
116
  return create(
@@ -131,6 +134,7 @@ namespace margelo::nitro::nitrosse {
131
134
  value.maxRetryIntervalMs.has_value() ? jni::JDouble::valueOf(value.maxRetryIntervalMs.value()) : nullptr,
132
135
  value.jitterFactor.has_value() ? jni::JDouble::valueOf(value.jitterFactor.value()) : nullptr,
133
136
  value.maxReconnectAttempts.has_value() ? jni::JDouble::valueOf(value.maxReconnectAttempts.value()) : nullptr,
137
+ value.autoParseJSON.has_value() ? jni::JBoolean::valueOf(value.autoParseJSON.value()) : nullptr,
134
138
  value.onBeforeRequest.has_value() ? JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx::fromCpp(value.onBeforeRequest.value()) : nullptr
135
139
  );
136
140
  }
@@ -12,6 +12,8 @@
12
12
 
13
13
  #include "JSseEventType.hpp"
14
14
  #include "SseEventType.hpp"
15
+ #include <NitroModules/AnyMap.hpp>
16
+ #include <NitroModules/JAnyMap.hpp>
15
17
  #include <optional>
16
18
  #include <string>
17
19
 
@@ -38,6 +40,8 @@ namespace margelo::nitro::nitrosse {
38
40
  jni::local_ref<JSseEventType> type = this->getFieldValue(fieldType);
39
41
  static const auto fieldData = clazz->getField<jni::JString>("data");
40
42
  jni::local_ref<jni::JString> data = this->getFieldValue(fieldData);
43
+ static const auto fieldParsedData = clazz->getField<JAnyMap::javaobject>("parsedData");
44
+ jni::local_ref<JAnyMap::javaobject> parsedData = this->getFieldValue(fieldParsedData);
41
45
  static const auto fieldId = clazz->getField<jni::JString>("id");
42
46
  jni::local_ref<jni::JString> id = this->getFieldValue(fieldId);
43
47
  static const auto fieldEvent = clazz->getField<jni::JString>("event");
@@ -51,6 +55,7 @@ namespace margelo::nitro::nitrosse {
51
55
  return SseEvent(
52
56
  type->toCpp(),
53
57
  data != nullptr ? std::make_optional(data->toStdString()) : std::nullopt,
58
+ parsedData != nullptr ? std::make_optional(parsedData->cthis()->getMap()) : std::nullopt,
54
59
  id != nullptr ? std::make_optional(id->toStdString()) : std::nullopt,
55
60
  event != nullptr ? std::make_optional(event->toStdString()) : std::nullopt,
56
61
  message != nullptr ? std::make_optional(message->toStdString()) : std::nullopt,
@@ -65,13 +70,14 @@ namespace margelo::nitro::nitrosse {
65
70
  */
66
71
  [[maybe_unused]]
67
72
  static jni::local_ref<JSseEvent::javaobject> fromCpp(const SseEvent& value) {
68
- using JSignature = JSseEvent(jni::alias_ref<JSseEventType>, jni::alias_ref<jni::JString>, jni::alias_ref<jni::JString>, jni::alias_ref<jni::JString>, jni::alias_ref<jni::JString>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>);
73
+ using JSignature = JSseEvent(jni::alias_ref<JSseEventType>, jni::alias_ref<jni::JString>, jni::alias_ref<JAnyMap::javaobject>, jni::alias_ref<jni::JString>, jni::alias_ref<jni::JString>, jni::alias_ref<jni::JString>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>);
69
74
  static const auto clazz = javaClassStatic();
70
75
  static const auto create = clazz->getStaticMethod<JSignature>("fromCpp");
71
76
  return create(
72
77
  clazz,
73
78
  JSseEventType::fromCpp(value.type),
74
79
  value.data.has_value() ? jni::make_jstring(value.data.value()) : nullptr,
80
+ value.parsedData.has_value() ? JAnyMap::create(value.parsedData.value()) : nullptr,
75
81
  value.id.has_value() ? jni::make_jstring(value.id.value()) : nullptr,
76
82
  value.event.has_value() ? jni::make_jstring(value.event.value()) : nullptr,
77
83
  value.message.has_value() ? jni::make_jstring(value.message.value()) : nullptr,
@@ -58,13 +58,16 @@ data class SseConfig(
58
58
  val maxReconnectAttempts: Double?,
59
59
  @DoNotStrip
60
60
  @Keep
61
+ val autoParseJSON: Boolean?,
62
+ @DoNotStrip
63
+ @Keep
61
64
  val onBeforeRequest: Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____?
62
65
  ) {
63
66
  /**
64
67
  * Create a new instance of SseConfig from Kotlin
65
68
  */
66
- constructor(url: String, method: HttpMethod?, headers: Map<String, String>?, body: String?, backgroundExecution: Boolean?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, onBeforeRequest: (() -> Promise<Promise<Map<String, String>>>)?):
67
- this(url, method, headers, body, backgroundExecution, batchingIntervalMs, maxBufferSize, connectionTimeoutMs, readTimeoutMs, retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts, onBeforeRequest?.let { Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______java(it) })
69
+ constructor(url: String, method: HttpMethod?, headers: Map<String, String>?, body: String?, backgroundExecution: Boolean?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Boolean?, onBeforeRequest: (() -> Promise<Promise<Map<String, String>>>)?):
70
+ this(url, method, headers, body, backgroundExecution, batchingIntervalMs, maxBufferSize, connectionTimeoutMs, readTimeoutMs, retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts, autoParseJSON, onBeforeRequest?.let { Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______java(it) })
68
71
 
69
72
  companion object {
70
73
  /**
@@ -74,8 +77,8 @@ data class SseConfig(
74
77
  @Keep
75
78
  @Suppress("unused")
76
79
  @JvmStatic
77
- private fun fromCpp(url: String, method: HttpMethod?, headers: Map<String, String>?, body: String?, backgroundExecution: Boolean?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, onBeforeRequest: Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____?): SseConfig {
78
- return SseConfig(url, method, headers, body, backgroundExecution, batchingIntervalMs, maxBufferSize, connectionTimeoutMs, readTimeoutMs, retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts, onBeforeRequest)
80
+ private fun fromCpp(url: String, method: HttpMethod?, headers: Map<String, String>?, body: String?, backgroundExecution: Boolean?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Boolean?, onBeforeRequest: Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____?): SseConfig {
81
+ return SseConfig(url, method, headers, body, backgroundExecution, batchingIntervalMs, maxBufferSize, connectionTimeoutMs, readTimeoutMs, retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts, autoParseJSON, onBeforeRequest)
79
82
  }
80
83
  }
81
84
  }