react-native-nitro-sse 1.2.3 → 1.3.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,11 +14,15 @@ 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}",
17
+ "ios/*.{swift}",
18
+ "ios/*.{m,mm}",
19
19
  "cpp/**/*.{hpp,cpp}",
20
20
  ]
21
21
 
22
+ s.test_spec 'Tests' do |test_spec|
23
+ test_spec.source_files = 'ios/Tests/**/*.{swift}'
24
+ end
25
+
22
26
  s.dependency 'React-jsi'
23
27
  s.dependency 'React-callinvoker'
24
28
  s.dependency 'LDSwiftEventSource'
@@ -118,4 +118,6 @@ dependencies {
118
118
  implementation "com.squareup.okhttp3:okhttp:4.12.0"
119
119
  implementation "com.squareup.okhttp3:okhttp-sse:4.12.0"
120
120
  implementation "androidx.lifecycle:lifecycle-process:2.8.7"
121
+
122
+ testImplementation "junit:junit:4.13.2"
121
123
  }
@@ -38,9 +38,9 @@ import kotlin.random.Random
38
38
  */
39
39
  @DoNotStrip
40
40
  class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
41
- private var client: OkHttpClient? = null
42
- private var eventSource: EventSource? = null
43
- private var config: SseConfig? = null
41
+ @Volatile private var client: OkHttpClient? = null
42
+ @Volatile private var eventSource: EventSource? = null
43
+ @Volatile private var config: SseConfig? = null
44
44
  private var onEventsCallback: ((events: Array<SseEvent>) -> Unit)? = null
45
45
 
46
46
  private val isRunning = AtomicBoolean(false)
@@ -85,18 +85,24 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
85
85
  override fun contentType() = responseBody.contentType()
86
86
  override fun contentLength() = responseBody.contentLength()
87
87
  override fun source() = (object : okio.ForwardingSource(responseBody.source()) {
88
+ private var isAtStartOfLine = true
89
+
88
90
  override fun read(sink: okio.Buffer, byteCount: Long): Long {
91
+ val bufferOffset = sink.size
89
92
  val bytesRead = super.read(sink, byteCount)
90
93
  if (bytesRead != -1L) {
91
94
  totalBytesReceived.addAndGet(bytesRead)
92
95
 
93
96
  try {
94
- val snapshot = sink.snapshot()
95
- if (snapshot.size > 0 && snapshot.get(0) == ':'.toByte()) {
96
- pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, "keep-alive"))
97
+ for (i in 0 until bytesRead) {
98
+ val b = sink.get(bufferOffset + i)
99
+ if (isAtStartOfLine && b == ':'.toByte()) {
100
+ pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, "keep-alive"))
101
+ }
102
+ isAtStartOfLine = (b == '\n'.toByte() || b == '\r'.toByte())
97
103
  }
98
104
  } catch (e: Exception) {
99
- // Silent catch for interceptor parsing
105
+ // Silent catch to prevent interceptor failure
100
106
  }
101
107
  }
102
108
  return bytesRead
@@ -179,9 +185,11 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
179
185
  }
180
186
 
181
187
  override fun updateHeaders(headers: Map<String, String>) {
182
- this.config?.let {
183
- this.config = it.copy(headers = headers)
184
- Log.d(TAG, "Headers updated for subsequent connections")
188
+ synchronized(this) {
189
+ this.config?.let {
190
+ this.config = it.copy(headers = headers)
191
+ Log.d(TAG, "Headers updated for subsequent connections")
192
+ }
185
193
  }
186
194
  }
187
195
 
@@ -202,25 +210,31 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
202
210
  }
203
211
 
204
212
  private fun performConnection() {
205
- if (!isRunning.get()) return
213
+ val currentConfig: SseConfig
214
+ val currentLastId: String?
215
+ synchronized(this) {
216
+ if (!isRunning.get() || config == null) return
217
+ currentConfig = config!!
218
+ currentLastId = lastProcessedId
219
+ }
206
220
 
207
221
  // Cancel existing event source if any before starting new one
208
222
  eventSource?.cancel()
209
223
  eventSource = null
210
224
 
211
225
  val requestBuilder = Request.Builder()
212
- .url(config!!.url)
226
+ .url(currentConfig.url)
213
227
  .header("Accept", "text/event-stream")
214
228
  .header("Cache-Control", "no-cache")
215
229
 
216
- lastProcessedId?.let {
230
+ currentLastId?.let {
217
231
  if (it.isNotEmpty()) requestBuilder.header("Last-Event-ID", it)
218
232
  }
219
233
 
220
- config!!.headers?.forEach { (k, v) -> requestBuilder.header(k, v) }
234
+ currentConfig.headers?.forEach { (k, v) -> requestBuilder.header(k, v) }
221
235
 
222
- if (config!!.method == HttpMethod.POST) {
223
- val body = config!!.body?.toRequestBody("application/json".toMediaType()) ?: "".toRequestBody()
236
+ if (currentConfig.method == HttpMethod.POST) {
237
+ val body = currentConfig.body?.toRequestBody("application/json".toMediaType()) ?: "".toRequestBody()
224
238
  requestBuilder.post(body)
225
239
  }
226
240
 
@@ -248,6 +262,9 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
248
262
 
249
263
  override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
250
264
  if (eventSource != this@NitroSse.eventSource) return
265
+ if (!id.isNullOrEmpty()) {
266
+ this@NitroSse.lastProcessedId = id
267
+ }
251
268
  pushEventToBuffer(SseEvent(SseEventType.MESSAGE, data, id, type, null))
252
269
  }
253
270
 
@@ -0,0 +1,98 @@
1
+ package com.margelo.nitro.nitrosse
2
+
3
+ import org.junit.Assert.assertEquals
4
+ import org.junit.Test
5
+
6
+ class HeartbeatScanner {
7
+ private var isAtStartOfLine = true
8
+ var heartbeatCount = 0
9
+ private set
10
+
11
+ fun scan(bytes: ByteArray, length: Int) {
12
+ for (i in 0 until length) {
13
+ val b = bytes[i]
14
+ if (isAtStartOfLine && b == ':'.toByte()) {
15
+ heartbeatCount++
16
+ }
17
+ isAtStartOfLine = (b == '\n'.toByte() || b == '\r'.toByte())
18
+ }
19
+ }
20
+ }
21
+
22
+ class HeartbeatScannerTest {
23
+
24
+ @Test
25
+ fun testNormalHeartbeat() {
26
+ val scanner = HeartbeatScanner()
27
+ val data = ":heartbeat\n".toByteArray()
28
+ scanner.scan(data, data.size)
29
+ assertEquals(1, scanner.heartbeatCount)
30
+ }
31
+
32
+ @Test
33
+ fun testHeartbeatAfterNewline() {
34
+ val scanner = HeartbeatScanner()
35
+ val data = "data: hello\n:heartbeat\n".toByteArray()
36
+ scanner.scan(data, data.size)
37
+ assertEquals(1, scanner.heartbeatCount)
38
+ }
39
+
40
+ @Test
41
+ fun testSplitPacketHeartbeat() {
42
+ val scanner = HeartbeatScanner()
43
+
44
+ // Packet 1 ends right before heartbeat
45
+ val p1 = "data: hello\n".toByteArray()
46
+ scanner.scan(p1, p1.size)
47
+
48
+ // Packet 2 starts with heartbeat
49
+ val p2 = ":heartbeat\n".toByteArray()
50
+ scanner.scan(p2, p2.size)
51
+
52
+ assertEquals(1, scanner.heartbeatCount)
53
+ }
54
+
55
+ @Test
56
+ fun testHeartbeatSplitAcrossPackets() {
57
+ val scanner = HeartbeatScanner()
58
+
59
+ // Packet 1 ends with newline
60
+ val p1 = "data: hello\n".toByteArray()
61
+ scanner.scan(p1, p1.size)
62
+
63
+ // Packet 2 starts with ':' but no more
64
+ val p2 = ":".toByteArray()
65
+ scanner.scan(p2, p2.size)
66
+ assertEquals(1, scanner.heartbeatCount)
67
+
68
+ // Packet 3 contains the rest of comment
69
+ val p3 = "heartbeat\n".toByteArray()
70
+ scanner.scan(p3, p3.size)
71
+
72
+ assertEquals(1, scanner.heartbeatCount)
73
+ }
74
+
75
+ @Test
76
+ fun testColonsInDataAreNotHeartbeats() {
77
+ val scanner = HeartbeatScanner()
78
+ val data = "data: something:with:colons\n".toByteArray()
79
+ scanner.scan(data, data.size)
80
+ assertEquals(0, scanner.heartbeatCount)
81
+ }
82
+
83
+ @Test
84
+ fun testMultipleHeartbeats() {
85
+ val scanner = HeartbeatScanner()
86
+ val data = ":h1\n:h2\n\n:h3\n".toByteArray()
87
+ scanner.scan(data, data.size)
88
+ assertEquals(3, scanner.heartbeatCount)
89
+ }
90
+
91
+ @Test
92
+ fun testCRLFHeartbeat() {
93
+ val scanner = HeartbeatScanner()
94
+ val data = "data: ok\r\n:heartbeat\r\n".toByteArray()
95
+ scanner.scan(data, data.size)
96
+ assertEquals(1, scanner.heartbeatCount)
97
+ }
98
+ }
@@ -0,0 +1,110 @@
1
+ package com.margelo.nitro.nitrosse
2
+
3
+ import org.junit.Assert.*
4
+ import org.junit.Before
5
+ import org.junit.Test
6
+ import java.util.concurrent.atomic.AtomicInteger
7
+
8
+ class NitroSseLogicTest {
9
+
10
+ private lateinit var eventBuffer: MutableList<SseEvent>
11
+ private var bufferCapacity = 100
12
+ private var batchInterval = 0.0
13
+
14
+ @Before
15
+ fun setup() {
16
+ eventBuffer = mutableListOf()
17
+ }
18
+
19
+ private fun pushEventToBuffer(event: SseEvent, onFlush: () -> Unit) {
20
+ synchronized(eventBuffer) {
21
+ while (eventBuffer.size >= bufferCapacity) {
22
+ eventBuffer.removeAt(0)
23
+ }
24
+ eventBuffer.add(event)
25
+ }
26
+
27
+ if (batchInterval <= 0) {
28
+ onFlush()
29
+ }
30
+ }
31
+
32
+ @Test
33
+ fun testBufferCapacityLimit() {
34
+ bufferCapacity = 5
35
+ batchInterval = 100.0 // Enable batching so we don't flush immediately
36
+
37
+ for (i in 1..10) {
38
+ pushEventToBuffer(SseEvent(SseEventType.MESSAGE, "data $i", "$i", null, null)) {}
39
+ }
40
+
41
+ assertEquals(5, eventBuffer.size)
42
+ assertEquals("6", eventBuffer[0].id)
43
+ assertEquals("10", eventBuffer[4].id)
44
+ }
45
+
46
+ @Test
47
+ fun testImmediateFlushWhenNoBatching() {
48
+ batchInterval = 0.0
49
+ val flushCount = AtomicInteger(0)
50
+
51
+ pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null)) {
52
+ flushCount.incrementAndGet()
53
+ }
54
+
55
+ assertEquals(1, flushCount.get())
56
+ }
57
+
58
+ @Test
59
+ fun testRetryAfterExtraction() {
60
+ // Mock non-standard retry after logic (conceptual check of the method)
61
+ fun extractMillis(headerValue: String?): Long? {
62
+ if (headerValue == null) return null
63
+ return try {
64
+ headerValue.toLong() * 1000L
65
+ } catch (e: Exception) {
66
+ null // Simplifying for the logic test
67
+ }
68
+ }
69
+
70
+ assertEquals(5000L, extractMillis("5"))
71
+ assertEquals(60000L, extractMillis("60"))
72
+ assertNull(extractMillis(null))
73
+ assertNull(extractMillis("invalid"))
74
+ }
75
+
76
+ @Test
77
+ fun testBackoffCalculation() {
78
+ val baseBackoffDelayMs = 2000L
79
+ val maxBackoffDelayMs = 30000L
80
+
81
+ fun calculateDelay(counter: Int): Long {
82
+ return Math.min(baseBackoffDelayMs * (1 shl counter), maxBackoffDelayMs)
83
+ }
84
+
85
+ assertEquals(2000L, calculateDelay(0))
86
+ assertEquals(4000L, calculateDelay(1))
87
+ assertEquals(8000L, calculateDelay(2))
88
+ assertEquals(16000L, calculateDelay(3))
89
+ assertEquals(30000L, calculateDelay(4)) // Capped at max
90
+ assertEquals(30000L, calculateDelay(10)) // Still capped
91
+ }
92
+
93
+ @Test
94
+ fun testHeartbeatScannerLogic_Integrated() {
95
+ val heartbeatCount = AtomicInteger(0)
96
+ var isAtStartOfLine = true
97
+
98
+ fun processByte(b: Byte) {
99
+ if (isAtStartOfLine && b == ':'.toByte()) {
100
+ heartbeatCount.incrementAndGet()
101
+ }
102
+ isAtStartOfLine = (b == '\n'.toByte() || b == '\r'.toByte())
103
+ }
104
+
105
+ val stream = "data: hello\n:heartbeat\n\n:ping\n".toByteArray()
106
+ for (b in stream) processByte(b)
107
+
108
+ assertEquals(2, heartbeatCount.get())
109
+ }
110
+ }
@@ -129,17 +129,17 @@ class NitroSse: HybridNitroSseSpec {
129
129
 
130
130
  func updateHeaders(headers: [String: String]) throws {
131
131
  sseQueue.async {
132
- if let currentConfig = self.config {
133
- self.config = SseConfig(
134
- url: currentConfig.url,
135
- method: currentConfig.method,
136
- headers: headers,
137
- body: currentConfig.body,
138
- backgroundExecution: currentConfig.backgroundExecution,
139
- batchingIntervalMs: currentConfig.batchingIntervalMs,
140
- maxBufferSize: currentConfig.maxBufferSize
141
- )
142
- }
132
+ guard var currentConfig = self.config else { return }
133
+ self.config = SseConfig(
134
+ url: currentConfig.url,
135
+ method: currentConfig.method,
136
+ headers: headers,
137
+ body: currentConfig.body,
138
+ backgroundExecution: currentConfig.backgroundExecution,
139
+ batchingIntervalMs: currentConfig.batchingIntervalMs,
140
+ maxBufferSize: currentConfig.maxBufferSize
141
+ )
142
+ print("[NitroSse] Headers updated for subsequent connections.")
143
143
  }
144
144
  }
145
145
 
@@ -222,38 +222,6 @@ class NitroSse: HybridNitroSseSpec {
222
222
  }
223
223
  }
224
224
 
225
- func onOpened() {
226
- sseQueue.async {
227
- self.backoffCounter = 0
228
- self.pushEventToBuffer(SseEvent(type: .open, data: nil, id: nil, event: nil, message: nil))
229
- }
230
- }
231
-
232
- func onClosed() {
233
- sseQueue.async {
234
- if self.isRunning {
235
- self.scheduleAutomaticReconnect(isError: false)
236
- }
237
- }
238
- }
239
-
240
- func onMessage(eventType: String, messageEvent: MessageEvent) {
241
- sseQueue.async {
242
- let encodedDataSize = Double(messageEvent.data.utf8.count)
243
- let metadataSize = Double(eventType.utf8.count) + Double((messageEvent.lastEventId).utf8.count)
244
- self.totalBytesReceived += encodedDataSize + metadataSize
245
-
246
- self.pushEventToBuffer(SseEvent(type: .message, data: messageEvent.data, id: messageEvent.lastEventId, event: eventType, message: nil))
247
- }
248
- }
249
-
250
- func onComment(comment: String) {
251
- sseQueue.async {
252
- self.totalBytesReceived += Double(comment.utf8.count)
253
- self.pushEventToBuffer(SseEvent(type: .heartbeat, data: nil, id: nil, event: nil, message: comment))
254
- }
255
- }
256
-
257
225
  private func extractRetryAfterSeconds(error: Error) -> TimeInterval? {
258
226
  let nsError = error as NSError
259
227
  guard let response = nsError.userInfo["response"] as? HTTPURLResponse else { return nil }
@@ -273,42 +241,8 @@ class NitroSse: HybridNitroSseSpec {
273
241
  return nil
274
242
  }
275
243
 
276
- func onError(error: Error) {
277
- sseQueue.async {
278
- guard self.isRunning else { return }
279
- let nsError = error as NSError
280
- let statusCode = nsError.code
281
-
282
- self.reconnectCount += 1
283
- self.lastErrorTime = Date().timeIntervalSince1970 * 1000
284
- self.lastErrorCode = "\(nsError.domain)(\(statusCode))"
285
-
286
- let isFatalError = (statusCode == 401 || statusCode == 403 || statusCode == 400)
287
- if isFatalError {
288
- self.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Fatal Error (\(statusCode)). Stopping."))
289
- self.stop()
290
- return
291
- }
244
+ // EventSource callback handling is done via SseHandler class below.
292
245
 
293
- let retryAfterSeconds = self.extractRetryAfterSeconds(error: error)
294
- if (statusCode == 429 || statusCode == 503), let delay = retryAfterSeconds {
295
- let jitter = Double.random(in: 0.5...2.0)
296
- let totalDelay = delay + jitter
297
- self.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Retry-After received (\(statusCode))"))
298
- self.scheduleAutomaticReconnectWithFixedDelay(totalDelay)
299
- return
300
- }
301
-
302
- if statusCode == 429 {
303
- self.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Rate Limited (429) without Retry-After. Stopping."))
304
- self.stop()
305
- return
306
- }
307
-
308
- self.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: error.localizedDescription))
309
- self.scheduleAutomaticReconnect(isError: true)
310
- }
311
- }
312
246
 
313
247
  private func scheduleAutomaticReconnectWithFixedDelay(_ delay: TimeInterval) {
314
248
  dispatchPrecondition(condition: .onQueue(sseQueue))
@@ -349,7 +283,8 @@ class NitroSse: HybridNitroSseSpec {
349
283
 
350
284
  func onOpened() {
351
285
  guard let parent = parent, source === parent.eventSource else { return }
352
- parent.sseQueue.async {
286
+ parent.sseQueue.async { [weak parent] in
287
+ guard let parent = parent else { return }
353
288
  parent.backoffCounter = 0
354
289
  parent.pushEventToBuffer(SseEvent(type: .open, data: nil, id: nil, event: nil, message: nil))
355
290
  }
@@ -357,7 +292,8 @@ class NitroSse: HybridNitroSseSpec {
357
292
 
358
293
  func onClosed() {
359
294
  guard let parent = parent, source === parent.eventSource else { return }
360
- parent.sseQueue.async {
295
+ parent.sseQueue.async { [weak parent] in
296
+ guard let parent = parent else { return }
361
297
  if parent.isRunning {
362
298
  parent.scheduleAutomaticReconnect(isError: false)
363
299
  }
@@ -366,18 +302,24 @@ class NitroSse: HybridNitroSseSpec {
366
302
 
367
303
  func onMessage(eventType: String, messageEvent: MessageEvent) {
368
304
  guard let parent = parent, source === parent.eventSource else { return }
369
- parent.sseQueue.async {
305
+ parent.sseQueue.async { [weak parent] in
306
+ guard let parent = parent else { return }
370
307
  let encodedDataSize = Double(messageEvent.data.utf8.count)
371
308
  let metadataSize = Double(eventType.utf8.count) + Double((messageEvent.lastEventId).utf8.count)
372
309
  parent.totalBytesReceived += encodedDataSize + metadataSize
373
310
 
311
+ if !messageEvent.lastEventId.isEmpty {
312
+ parent.lastProcessedId = messageEvent.lastEventId
313
+ }
314
+
374
315
  parent.pushEventToBuffer(SseEvent(type: .message, data: messageEvent.data, id: messageEvent.lastEventId, event: eventType, message: nil))
375
316
  }
376
317
  }
377
318
 
378
319
  func onComment(comment: String) {
379
320
  guard let parent = parent, source === parent.eventSource else { return }
380
- parent.sseQueue.async {
321
+ parent.sseQueue.async { [weak parent] in
322
+ guard let parent = parent else { return }
381
323
  parent.totalBytesReceived += Double(comment.utf8.count)
382
324
  parent.pushEventToBuffer(SseEvent(type: .heartbeat, data: nil, id: nil, event: nil, message: comment))
383
325
  }
@@ -385,8 +327,8 @@ class NitroSse: HybridNitroSseSpec {
385
327
 
386
328
  func onError(error: Error) {
387
329
  guard let parent = parent, source === parent.eventSource else { return }
388
- parent.sseQueue.async {
389
- guard parent.isRunning else { return }
330
+ parent.sseQueue.async { [weak parent] in
331
+ guard let parent = parent, parent.isRunning else { return }
390
332
  let nsError = error as NSError
391
333
  let statusCode = nsError.code
392
334
 
@@ -0,0 +1,86 @@
1
+ import XCTest
2
+ @testable import NitroSse
3
+
4
+ class NitroSseTests: XCTestCase {
5
+
6
+ // Manual re-implementation of core logic for unit testing
7
+ // since NitroSse is heavily tied to background queues and LDSwiftEventSource
8
+ // but the algorithms are extracted for verify quality.
9
+
10
+ func testBackoffDelayCalculation() {
11
+ let baseBackoffDelay: TimeInterval = 2.0
12
+ let maxBackoffDelay: TimeInterval = 30.0
13
+
14
+ func calculateDelay(counter: Int) -> TimeInterval {
15
+ let exponent = Double(counter)
16
+ return min(baseBackoffDelay * pow(2.0, exponent), maxBackoffDelay)
17
+ }
18
+
19
+ XCTAssertEqual(calculateDelay(counter: 0), 2.0)
20
+ XCTAssertEqual(calculateDelay(counter: 1), 4.0)
21
+ XCTAssertEqual(calculateDelay(counter: 2), 8.0)
22
+ XCTAssertEqual(calculateDelay(counter: 3), 16.0)
23
+ XCTAssertEqual(calculateDelay(counter: 4), 30.0) // Capped
24
+ XCTAssertEqual(calculateDelay(counter: 10), 30.0) // Still capped
25
+ }
26
+
27
+ func testRetryAfterExtraction() {
28
+ // Mocked logic for testing since URLResponse and HTTPURLResponse initialization is complex
29
+ func extractRetryAfter(headerValue: String?) -> TimeInterval? {
30
+ guard let retryAfterHeader = headerValue else { return nil }
31
+ if let seconds = Double(retryAfterHeader) {
32
+ return seconds
33
+ }
34
+ // Date parsing (Simplified RFC1123 check)
35
+ let formatter = DateFormatter()
36
+ formatter.locale = Locale(identifier: "en_US_POSIX")
37
+ formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
38
+ if let date = formatter.date(from: retryAfterHeader) {
39
+ let diff = date.timeIntervalSinceNow
40
+ return diff > 0 ? diff : nil
41
+ }
42
+ return nil
43
+ }
44
+
45
+ XCTAssertEqual(extractRetryAfter(headerValue: "5"), 5.0)
46
+ XCTAssertEqual(extractRetryAfter(headerValue: "60"), 60.0)
47
+ XCTAssertNil(extractRetryAfter(headerValue: nil))
48
+ XCTAssertNil(extractRetryAfter(headerValue: "invalid"))
49
+
50
+ // Test date format (far in future)
51
+ let futureDate = "Wed, 01 Jan 2030 00:00:00 GMT"
52
+ XCTAssertNotNil(extractRetryAfter(headerValue: futureDate))
53
+ }
54
+
55
+ func testBufferManagement() {
56
+ var buffer: [String] = []
57
+ let capacity = 5
58
+
59
+ func pushToBuffer(_ item: String) {
60
+ while buffer.count >= capacity {
61
+ buffer.removeFirst()
62
+ }
63
+ buffer.append(item)
64
+ }
65
+
66
+ for i in 1...10 {
67
+ pushToBuffer("event-\(i)")
68
+ }
69
+
70
+ XCTAssertEqual(buffer.count, 5)
71
+ XCTAssertEqual(buffer.first, "event-6")
72
+ XCTAssertEqual(buffer.last, "event-10")
73
+ }
74
+
75
+ func testEventSizeCalculation() {
76
+ // Total bytes count logic
77
+ func calculateSize(eventType: String, data: String, lastId: String) -> Double {
78
+ let encodedDataSize = Double(data.utf8.count)
79
+ let metadataSize = Double(eventType.utf8.count) + Double(lastId.utf8.count)
80
+ return encodedDataSize + metadataSize
81
+ }
82
+
83
+ let size = calculateSize(eventType: "message", data: "{\"id\":1}", lastId: "event-1")
84
+ XCTAssertEqual(size, 22.0) // 8 (data) + 7 (type) + 7 (id) = 22 bytes
85
+ }
86
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-nitro-sse",
3
- "version": "1.2.3",
3
+ "version": "1.3.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",
@@ -177,4 +177,4 @@
177
177
  ],
178
178
  "version": "0.57.0"
179
179
  }
180
- }
180
+ }