react-native-nitro-sse 2.2.3 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/ios/NitroSse.swift +4 -2
  2. package/lib/module/NitroSseClient.js +171 -2
  3. package/lib/module/NitroSseClient.js.map +1 -1
  4. package/lib/typescript/src/NitroSseClient.d.ts +5 -0
  5. package/lib/typescript/src/NitroSseClient.d.ts.map +1 -1
  6. package/lib/typescript/src/SseInterface.d.ts +61 -0
  7. package/lib/typescript/src/SseInterface.d.ts.map +1 -1
  8. package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +14 -14
  9. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +17 -5
  10. package/nitrogen/generated/android/c++/JSseConfig.hpp +18 -3
  11. package/nitrogen/generated/android/c++/JSseMockConfig.hpp +101 -0
  12. package/nitrogen/generated/android/c++/JSseMockEvent.hpp +94 -0
  13. package/nitrogen/generated/android/c++/JSseMockMode.hpp +58 -0
  14. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +53 -5
  15. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +27 -0
  16. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockConfig.kt +71 -0
  17. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockEvent.kt +91 -0
  18. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockMode.kt +23 -0
  19. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +19 -0
  20. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +50 -0
  21. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +9 -0
  22. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +12 -3
  23. package/nitrogen/generated/ios/swift/SseConfig.swift +12 -1
  24. package/nitrogen/generated/ios/swift/SseMockConfig.swift +94 -0
  25. package/nitrogen/generated/ios/swift/SseMockEvent.swift +179 -0
  26. package/nitrogen/generated/ios/swift/SseMockMode.swift +40 -0
  27. package/nitrogen/generated/shared/c++/SseConfig.hpp +9 -2
  28. package/nitrogen/generated/shared/c++/SseMockConfig.hpp +105 -0
  29. package/nitrogen/generated/shared/c++/SseMockEvent.hpp +119 -0
  30. package/nitrogen/generated/shared/c++/SseMockMode.hpp +76 -0
  31. package/package.json +4 -4
  32. package/src/NitroSseClient.ts +203 -2
  33. package/src/SseInterface.ts +64 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-nitro-sse",
3
- "version": "2.2.3",
3
+ "version": "2.3.0",
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",
@@ -89,12 +89,12 @@
89
89
  "eslint-plugin-prettier": "^5.5.4",
90
90
  "jest": "^29.7.0",
91
91
  "lefthook": "^2.0.3",
92
- "nitrogen": "^0.35.4",
92
+ "nitrogen": "0.35.6",
93
93
  "prettier": "^2.8.8",
94
94
  "react": "19.2.0",
95
95
  "react-native": "0.83.4",
96
96
  "react-native-builder-bob": "^0.40.17",
97
- "react-native-nitro-modules": "^0.35.4",
97
+ "react-native-nitro-modules": "0.35.6",
98
98
  "release-it": "^19.0.4",
99
99
  "turbo": "^2.5.6",
100
100
  "typescript": "^5.9.2"
@@ -102,7 +102,7 @@
102
102
  "peerDependencies": {
103
103
  "react": "*",
104
104
  "react-native": "*",
105
- "react-native-nitro-modules": ">= 0.35.2"
105
+ "react-native-nitro-modules": ">= 0.35.6"
106
106
  },
107
107
  "workspaces": [
108
108
  "example"
@@ -7,20 +7,49 @@ import type {
7
7
  SseStats,
8
8
  } from './SseInterface';
9
9
 
10
+ declare const __DEV__: boolean | undefined;
11
+
10
12
  export class NitroSseClient implements SseClient {
11
13
  private _native: NitroSse;
12
14
  private _listeners: Map<string, Set<SseListener>> = new Map();
13
15
  private _legacyCallback?: (events: SseEvent[]) => void;
16
+ private _config?: SseConfig;
17
+ private _mockIntervalId?: any;
18
+ private _mockIndex: number = 0;
14
19
 
15
20
  constructor(native: NitroSse) {
16
21
  this._native = native;
17
22
  }
18
23
 
19
24
  setup(config: SseConfig, onEvent?: (events: SseEvent[]) => void): void {
25
+ this._config = { ...config };
20
26
  this._legacyCallback = onEvent;
21
27
 
28
+ const isDev = typeof __DEV__ !== 'undefined' ? __DEV__ === true : false;
29
+ if (!isDev) {
30
+ delete this._config.mock;
31
+ }
32
+
33
+ if (this._config.mock) {
34
+ console.warn(
35
+ '\n' +
36
+ '=================================================================\n' +
37
+ '⚠️ [react-native-nitro-sse] WARNING: MOCK STREAMING IS ENABLED! ⚠️\n' +
38
+ ` Mode: ${this._config.mock.mode.toUpperCase()} | Speed: ${
39
+ this._config.mock.eventsPerSecond ?? 1
40
+ } events/sec\n` +
41
+ ' Please ensure mocking is disabled before building for production!\n' +
42
+ '=================================================================\n'
43
+ );
44
+ }
45
+
46
+ if (this._mockIntervalId) {
47
+ clearTimeout(this._mockIntervalId);
48
+ this._mockIntervalId = undefined;
49
+ }
50
+
22
51
  // We wrap the native setup to dispatch events to typed listeners
23
- this._native.setup(config, (events) => {
52
+ this._native.setup(this._config, (events) => {
24
53
  // 1. Call legacy batch callback if provided
25
54
  this._legacyCallback?.(events);
26
55
 
@@ -62,16 +91,170 @@ export class NitroSseClient implements SseClient {
62
91
  }
63
92
  }
64
93
 
94
+ private _createSseEvent(rawMock: any): SseEvent {
95
+ return {
96
+ type: rawMock.type ?? 'message',
97
+ data: rawMock.data,
98
+ parsedData: rawMock.parsedData,
99
+ id: rawMock.id,
100
+ event: rawMock.event,
101
+ message: rawMock.message,
102
+ statusCode: rawMock.statusCode ?? 200,
103
+ retry: rawMock.retry,
104
+ };
105
+ }
106
+
65
107
  start(): void {
108
+ if (this._mockIntervalId) {
109
+ clearTimeout(this._mockIntervalId);
110
+ this._mockIntervalId = undefined;
111
+ }
112
+
113
+ if (this._config?.mock) {
114
+ const {
115
+ mode,
116
+ data,
117
+ eventsPerSecond = 1,
118
+ loop = false,
119
+ errorRate = 0,
120
+ } = this._config.mock;
121
+ this._mockIndex = 0;
122
+
123
+ // Validate and normalize eventsPerSecond (must be a finite positive number, default to 1)
124
+ let validatedEventsPerSecond = Number(eventsPerSecond);
125
+ if (
126
+ Number.isNaN(validatedEventsPerSecond) ||
127
+ !Number.isFinite(validatedEventsPerSecond) ||
128
+ validatedEventsPerSecond <= 0
129
+ ) {
130
+ validatedEventsPerSecond = 1;
131
+ }
132
+
133
+ // Validate and normalize errorRate (must be a finite number within [0,1], default to 0)
134
+ let validatedErrorRate = Number(errorRate);
135
+ if (
136
+ Number.isNaN(validatedErrorRate) ||
137
+ !Number.isFinite(validatedErrorRate)
138
+ ) {
139
+ validatedErrorRate = 0;
140
+ } else {
141
+ validatedErrorRate = Math.max(0, Math.min(1, validatedErrorRate));
142
+ }
143
+
144
+ const delayMs = 1000 / validatedEventsPerSecond;
145
+ // Safeguard: if eventsPerSecond is huge (e.g. 1000), setInterval/setTimeout is too slow.
146
+ // We batch events together in chunks if the calculated interval is under 10ms.
147
+ const batchSize = Math.max(1, Math.round(validatedEventsPerSecond / 100)); // chunk size for 10ms intervals
148
+ const intervalMs = Math.max(10, delayMs * batchSize);
149
+
150
+ const scheduleNext = () => {
151
+ if (this._mockIndex >= data.length) {
152
+ if (loop && data.length > 0) {
153
+ this._mockIndex = 0;
154
+ } else {
155
+ if (this._mockIntervalId) {
156
+ clearTimeout(this._mockIntervalId);
157
+ this._mockIntervalId = undefined;
158
+ }
159
+ const closeEvent: SseEvent = { type: 'close', statusCode: 200 };
160
+ this._legacyCallback?.([closeEvent]);
161
+ this._emit('close', closeEvent);
162
+ return;
163
+ }
164
+ }
165
+
166
+ // Simulate connection drops
167
+ if (validatedErrorRate && Math.random() < validatedErrorRate) {
168
+ const errorEvent: SseEvent = {
169
+ type: 'error',
170
+ message: 'Mock Connection Drop (Simulated Error)',
171
+ statusCode: 500,
172
+ };
173
+ this._legacyCallback?.([errorEvent]);
174
+ this._emit('error', errorEvent);
175
+
176
+ // Retry / reconnect delay simulator (e.g. 2000ms)
177
+ this._mockIntervalId = setTimeout(scheduleNext, 2000);
178
+ return;
179
+ }
180
+
181
+ const currentItem = data[this._mockIndex];
182
+ const hasCustomDelay =
183
+ currentItem && typeof currentItem.delayMs === 'number';
184
+
185
+ const batch: SseEvent[] = [];
186
+ if (hasCustomDelay) {
187
+ const rawMock = data[this._mockIndex++];
188
+ if (rawMock) {
189
+ batch.push(this._createSseEvent(rawMock));
190
+ }
191
+ } else {
192
+ for (let i = 0; i < batchSize && this._mockIndex < data.length; i++) {
193
+ const nextItem = data[this._mockIndex];
194
+ if (nextItem && typeof nextItem.delayMs === 'number') {
195
+ break;
196
+ }
197
+ const rawMock = data[this._mockIndex++];
198
+ if (rawMock) {
199
+ batch.push(this._createSseEvent(rawMock));
200
+ }
201
+ }
202
+ }
203
+
204
+ if (batch.length > 0) {
205
+ // 1. Call legacy batch callback if provided
206
+ this._legacyCallback?.(batch);
207
+
208
+ // 2. Dispatch individual events to registered listeners
209
+ for (const event of batch) {
210
+ this._emit(event.type, event);
211
+ if (event.event && event.event !== event.type) {
212
+ this._emit(event.event, event);
213
+ }
214
+ }
215
+ }
216
+
217
+ const nextDelay = hasCustomDelay ? currentItem.delayMs! : intervalMs;
218
+ this._mockIntervalId = setTimeout(scheduleNext, nextDelay);
219
+ };
220
+
221
+ const firstItem = data[0];
222
+ const firstDelay =
223
+ firstItem && typeof firstItem.delayMs === 'number'
224
+ ? firstItem.delayMs
225
+ : intervalMs;
226
+
227
+ if (mode === 'replace') {
228
+ // Emit simulated open event
229
+ const openEvent: SseEvent = { type: 'open', statusCode: 200 };
230
+ this._legacyCallback?.([openEvent]);
231
+ this._emit('open', openEvent);
232
+
233
+ this._mockIntervalId = setTimeout(scheduleNext, firstDelay);
234
+ return; // Skip native start
235
+ } else if (mode === 'inject') {
236
+ this._mockIntervalId = setTimeout(scheduleNext, firstDelay);
237
+ }
238
+ }
239
+
66
240
  this._native.start();
67
241
  }
68
242
 
69
243
  stop(): void {
244
+ if (this._mockIntervalId) {
245
+ clearTimeout(this._mockIntervalId);
246
+ this._mockIntervalId = undefined;
247
+ }
70
248
  this._native.stop();
71
249
  }
72
250
 
73
251
  restart(): void {
74
- this._native.restart();
252
+ if (this._config?.mock) {
253
+ this.stop();
254
+ this.start();
255
+ } else {
256
+ this._native.restart();
257
+ }
75
258
  }
76
259
 
77
260
  flush(): void {
@@ -79,10 +262,19 @@ export class NitroSseClient implements SseClient {
79
262
  }
80
263
 
81
264
  isConnected(): boolean {
265
+ if (this._config?.mock?.mode === 'replace' && this._mockIntervalId) {
266
+ return true;
267
+ }
82
268
  return this._native.isConnected();
83
269
  }
84
270
 
85
271
  getStats(): SseStats {
272
+ if (this._config?.mock?.mode === 'replace') {
273
+ return {
274
+ totalBytesReceived: this._mockIndex * 150,
275
+ reconnectCount: 0,
276
+ };
277
+ }
86
278
  return this._native.getStats();
87
279
  }
88
280
 
@@ -93,4 +285,13 @@ export class NitroSseClient implements SseClient {
93
285
  setLastProcessedId(id: string): void {
94
286
  this._native.setLastProcessedId(id);
95
287
  }
288
+
289
+ injectMockEvent(event: Partial<SseEvent>): void {
290
+ const sseEvent = this._createSseEvent(event);
291
+ this._legacyCallback?.([sseEvent]);
292
+ this._emit(sseEvent.type, sseEvent);
293
+ if (sseEvent.event && sseEvent.event !== sseEvent.type) {
294
+ this._emit(sseEvent.event, sseEvent);
295
+ }
296
+ }
96
297
  }
@@ -100,6 +100,68 @@ export interface SseConfig {
100
100
  * Note: This is protected by a native timeout to prevent the app from hanging.
101
101
  */
102
102
  onBeforeRequest?: () => Promise<Record<string, string>>;
103
+ /**
104
+ * Configuration for mock streaming data.
105
+ * Used for local testing and debugging.
106
+ */
107
+ mock?: SseMockConfig;
108
+ }
109
+
110
+ export type SseMockMode = 'replace' | 'inject';
111
+
112
+ /**
113
+ * Represents a single mock SSE event configuration.
114
+ */
115
+ export interface SseMockEvent {
116
+ /** The type of the event. */
117
+ type?: SseEventType;
118
+ /** The data payload of the event as a raw string. */
119
+ data?: string;
120
+ /** The parsed JSON data, if autoParseJSON is enabled and parsing succeeds. */
121
+ parsedData?: AnyMap;
122
+ /** The event ID, if provided. */
123
+ id?: string;
124
+ /** The event name, if provided (internal 'event' field in SSE). */
125
+ event?: string;
126
+ /** System message or error description. */
127
+ message?: string;
128
+ /** HTTP status code if applicable. */
129
+ statusCode?: number;
130
+ /** Server-requested retry delay in milliseconds. */
131
+ retry?: number;
132
+ /** Custom delay in milliseconds before this event is dispatched. */
133
+ delayMs?: number;
134
+ }
135
+
136
+ /**
137
+ * Configuration for mock streaming data.
138
+ */
139
+ export interface SseMockConfig {
140
+ /**
141
+ * - 'replace': Simulates the stream completely in JavaScript without any native network connection.
142
+ * - 'inject': Establishes the real server connection and injects mock events alongside it.
143
+ */
144
+ mode: SseMockMode;
145
+ /**
146
+ * The list of mock events to be streamed.
147
+ */
148
+ data: SseMockEvent[];
149
+ /**
150
+ * The frequency at which mock events are dispatched.
151
+ * Represented in events per second.
152
+ * @default 1
153
+ */
154
+ eventsPerSecond?: number;
155
+ /**
156
+ * Whether to loop the mock stream indefinitely.
157
+ * @default false
158
+ */
159
+ loop?: boolean;
160
+ /**
161
+ * Probability of simulated connection drop/error events (0.0 to 1.0).
162
+ * @default 0
163
+ */
164
+ errorRate?: number;
103
165
  }
104
166
 
105
167
  /**
@@ -181,4 +243,6 @@ export interface SseClient {
181
243
  updateHeaders(headers: Record<string, string>): void;
182
244
  /** Set last event ID. */
183
245
  setLastProcessedId(id: string): void;
246
+ /** Manually inject a mock event into the stream (for testing/debugging). */
247
+ injectMockEvent(event: Partial<SseEvent>): void;
184
248
  }