react-native-nitro-sse 2.4.1 → 3.0.0-beta.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/README.md +209 -95
- package/android/src/main/java/com/margelo/nitro/nitrosse/AndroidSseDispatcher.kt +5 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +11 -18
- package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +79 -38
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +194 -100
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +40 -15
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseDispatcher.kt +1 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +34 -28
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseLifecycleManager.kt +8 -1
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +7 -4
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +6 -4
- package/ios/NitroSse.swift +244 -190
- package/ios/SseConfig+CopyWith.swift +2 -1
- package/ios/SseConnectionHandler.swift +59 -29
- package/ios/SseDispatchQueueDispatcher.swift +15 -2
- package/ios/SseDispatcher.swift +7 -1
- package/ios/SseEventBuffer.swift +23 -7
- package/ios/SseLifecycleManager.swift +10 -1
- package/ios/SseNetworkMonitor.swift +8 -2
- package/ios/SseReconnectStrategy.swift +9 -3
- package/lib/module/MockSseEngine.js +203 -0
- package/lib/module/NitroSseClient.js +411 -214
- package/lib/module/NitroSseError.js +61 -0
- package/lib/module/SseDriver.js +156 -0
- package/lib/module/index.js +6 -3
- package/lib/module/useNitroSse.js +359 -0
- package/lib/typescript/src/MockSseEngine.d.ts +31 -0
- package/lib/typescript/src/NitroSse.nitro.d.ts +25 -2
- package/lib/typescript/src/NitroSseClient.d.ts +25 -7
- package/lib/typescript/src/NitroSseError.d.ts +38 -0
- package/lib/typescript/src/SseDriver.d.ts +80 -0
- package/lib/typescript/src/SseInterface.d.ts +25 -7
- package/lib/typescript/src/index.d.ts +4 -2
- package/lib/typescript/src/useNitroSse.d.ts +69 -0
- package/nitrogen/generated/android/c++/JSseConfig.hpp +7 -1
- package/nitrogen/generated/android/c++/JSseMockConfig.hpp +2 -0
- package/nitrogen/generated/android/c++/JSseMockEvent.hpp +9 -3
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +9 -4
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockEvent.kt +9 -4
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +15 -15
- package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +3 -3
- package/nitrogen/generated/ios/swift/SseConfig.swift +19 -1
- package/nitrogen/generated/ios/swift/SseMockEvent.swift +12 -1
- package/nitrogen/generated/shared/c++/SseConfig.hpp +5 -1
- package/nitrogen/generated/shared/c++/SseMockEvent.hpp +9 -2
- package/package.json +10 -11
- package/android/jacoco.gradle +0 -33
- package/lib/module/NitroSse.nitro.js.map +0 -1
- package/lib/module/NitroSseClient.js.map +0 -1
- package/lib/module/SseInterface.js.map +0 -1
- package/lib/module/index.js.map +0 -1
- package/lib/typescript/src/NitroSse.nitro.d.ts.map +0 -1
- package/lib/typescript/src/NitroSseClient.d.ts.map +0 -1
- package/lib/typescript/src/SseInterface.d.ts.map +0 -1
- package/lib/typescript/src/index.d.ts.map +0 -1
- package/src/NitroSse.nitro.ts +0 -58
- package/src/NitroSseClient.ts +0 -337
- package/src/SseInterface.ts +0 -272
- package/src/index.ts +0 -31
|
@@ -1,279 +1,476 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
+
import { MockSseEngine } from "./MockSseEngine.js";
|
|
4
|
+
import { NativeDriver, MockReplaceDriver, MockInjectDriver } from "./SseDriver.js";
|
|
5
|
+
import { NitroSseValidationError, NitroSseDisposedError, NitroSseStateError } from "./NitroSseError.js";
|
|
6
|
+
/**
|
|
7
|
+
* Sanitizes HTTP headers by stripping carriage returns, newlines, null bytes,
|
|
8
|
+
* converting non-string values to strings, and pruning null/undefined values.
|
|
9
|
+
*/
|
|
10
|
+
export function sanitizeHeaders(headers) {
|
|
11
|
+
if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
|
|
12
|
+
return {};
|
|
13
|
+
}
|
|
14
|
+
const clean = {};
|
|
15
|
+
for (const [key, rawValue] of Object.entries(headers)) {
|
|
16
|
+
if (rawValue === null || rawValue === undefined) continue;
|
|
17
|
+
const cleanKey = String(key).replace(/[\r\n\0]+/g, '').trim();
|
|
18
|
+
if (!cleanKey) continue;
|
|
19
|
+
const cleanVal = String(rawValue).replace(/[\r\n\0]+/g, '');
|
|
20
|
+
clean[cleanKey] = cleanVal;
|
|
21
|
+
}
|
|
22
|
+
return clean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Defensively validates and normalizes the SSE configuration object.
|
|
27
|
+
* Throws NitroSseValidationError if essential requirements (e.g. valid URL) are violated.
|
|
28
|
+
* Clamps numeric properties to safe boundaries and warns in __DEV__.
|
|
29
|
+
*/
|
|
30
|
+
export function validateConfig(config) {
|
|
31
|
+
if (!config || typeof config !== 'object' || Array.isArray(config)) {
|
|
32
|
+
throw new NitroSseValidationError('[NitroSse] Invalid config: Expected a configuration object.', 'INVALID_CONFIG', {
|
|
33
|
+
received: config
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
const rawUrl = config.url;
|
|
37
|
+
if (typeof rawUrl !== 'string' || !rawUrl.trim()) {
|
|
38
|
+
throw new NitroSseValidationError("[NitroSse] Invalid config: 'url' must be a non-empty string.", 'INVALID_CONFIG', {
|
|
39
|
+
received: rawUrl
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
const trimmedUrl = config.url.trim();
|
|
43
|
+
const lowerUrl = trimmedUrl.toLowerCase();
|
|
44
|
+
if (
|
|
45
|
+
// eslint-disable-next-line no-script-url
|
|
46
|
+
lowerUrl.startsWith('javascript:') || lowerUrl.startsWith('data:') || lowerUrl.startsWith('file:') || lowerUrl.startsWith('ftp:') || lowerUrl.startsWith('ws:') || lowerUrl.startsWith('wss:')) {
|
|
47
|
+
const isWs = lowerUrl.startsWith('ws:') || lowerUrl.startsWith('wss:');
|
|
48
|
+
const reason = isWs ? `Unsupported protocol (WebSocket "${trimmedUrl}"). SSE requires HTTP or HTTPS.` : `Unsupported protocol in URL "${trimmedUrl}". SSE requires HTTP or HTTPS.`;
|
|
49
|
+
throw new NitroSseValidationError(`[NitroSse] Invalid config: ${reason}`, 'INVALID_CONFIG', {
|
|
50
|
+
url: trimmedUrl
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
if (!lowerUrl.startsWith('http://') && !lowerUrl.startsWith('https://')) {
|
|
54
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
55
|
+
console.warn(`[NitroSse] URL "${trimmedUrl}" does not start with http:// or https://. Ensure it is an absolute URL; relative paths will fail on native.`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (config.headers !== undefined) {
|
|
59
|
+
if (!config.headers || typeof config.headers !== 'object' || Array.isArray(config.headers)) {
|
|
60
|
+
throw new NitroSseValidationError("[NitroSse] Invalid config: 'headers' must be an object of key-value pairs.", 'INVALID_CONFIG', {
|
|
61
|
+
received: config.headers
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
let lowerMethod;
|
|
66
|
+
if (config.method !== undefined) {
|
|
67
|
+
if (typeof config.method !== 'string') {
|
|
68
|
+
throw new NitroSseValidationError(`[NitroSse] Invalid config: 'method' must be a string ('get' or 'post').`, 'INVALID_CONFIG', {
|
|
69
|
+
received: config.method
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
const lm = config.method.toLowerCase();
|
|
73
|
+
if (lm === 'get' || lm === 'post') {
|
|
74
|
+
lowerMethod = lm;
|
|
75
|
+
} else {
|
|
76
|
+
throw new NitroSseValidationError(`[NitroSse] Invalid config: 'method' must be 'get' or 'post', received '${config.method}'.`, 'INVALID_CONFIG', {
|
|
77
|
+
received: config.method
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (config.onBeforeRequest !== undefined && typeof config.onBeforeRequest !== 'function') {
|
|
82
|
+
throw new NitroSseValidationError("[NitroSse] Invalid config: 'onBeforeRequest' must be a function.", 'INVALID_CONFIG', {
|
|
83
|
+
received: typeof config.onBeforeRequest
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
let connectionTimeoutMs = config.connectionTimeoutMs;
|
|
87
|
+
if (connectionTimeoutMs !== undefined) {
|
|
88
|
+
if (!Number.isFinite(connectionTimeoutMs) || connectionTimeoutMs < 0) {
|
|
89
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
90
|
+
console.warn(`[NitroSse] Invalid connectionTimeoutMs (${connectionTimeoutMs}). Resetting to default 15000.`);
|
|
91
|
+
}
|
|
92
|
+
connectionTimeoutMs = 15000;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
let readTimeoutMs = config.readTimeoutMs;
|
|
96
|
+
if (readTimeoutMs !== undefined) {
|
|
97
|
+
if (!Number.isFinite(readTimeoutMs) || readTimeoutMs <= 0) {
|
|
98
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
99
|
+
console.warn(`[NitroSse] Invalid readTimeoutMs (${readTimeoutMs}). Resetting to default 300000.`);
|
|
100
|
+
}
|
|
101
|
+
readTimeoutMs = 300000;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
let batchingIntervalMs = config.batchingIntervalMs;
|
|
105
|
+
if (batchingIntervalMs !== undefined) {
|
|
106
|
+
if (!Number.isFinite(batchingIntervalMs) || batchingIntervalMs < 0) {
|
|
107
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
108
|
+
console.warn(`[NitroSse] Invalid batchingIntervalMs (${batchingIntervalMs}). Clamping to 0.`);
|
|
109
|
+
}
|
|
110
|
+
batchingIntervalMs = 0;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
let maxBufferSize = config.maxBufferSize;
|
|
114
|
+
if (maxBufferSize !== undefined) {
|
|
115
|
+
if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) {
|
|
116
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
117
|
+
console.warn(`[NitroSse] Invalid maxBufferSize (${maxBufferSize}). Resetting to default 1000.`);
|
|
118
|
+
}
|
|
119
|
+
maxBufferSize = 1000;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
let retryIntervalMs = config.retryIntervalMs;
|
|
123
|
+
let maxRetryIntervalMs = config.maxRetryIntervalMs;
|
|
124
|
+
if (retryIntervalMs !== undefined) {
|
|
125
|
+
if (!Number.isFinite(retryIntervalMs) || retryIntervalMs < 0) {
|
|
126
|
+
retryIntervalMs = 1000;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (maxRetryIntervalMs !== undefined) {
|
|
130
|
+
if (!Number.isFinite(maxRetryIntervalMs) || maxRetryIntervalMs < 0) {
|
|
131
|
+
maxRetryIntervalMs = 30000;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (retryIntervalMs !== undefined && maxRetryIntervalMs !== undefined && retryIntervalMs > maxRetryIntervalMs) {
|
|
135
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
136
|
+
console.warn(`[NitroSse] retryIntervalMs (${retryIntervalMs}) cannot exceed maxRetryIntervalMs (${maxRetryIntervalMs}). Clamping retryIntervalMs.`);
|
|
137
|
+
}
|
|
138
|
+
retryIntervalMs = maxRetryIntervalMs;
|
|
139
|
+
}
|
|
140
|
+
let jitterFactor = config.jitterFactor;
|
|
141
|
+
if (jitterFactor !== undefined) {
|
|
142
|
+
if (!Number.isFinite(jitterFactor) || jitterFactor < 0 || jitterFactor > 1) {
|
|
143
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
144
|
+
console.warn(`[NitroSse] Invalid jitterFactor (${jitterFactor}). Clamping between 0.0 and 1.0.`);
|
|
145
|
+
}
|
|
146
|
+
jitterFactor = Math.max(0, Math.min(1, Number.isFinite(jitterFactor) ? jitterFactor : 0.5));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
let maxReconnectAttempts = config.maxReconnectAttempts;
|
|
150
|
+
if (maxReconnectAttempts !== undefined) {
|
|
151
|
+
if (!Number.isFinite(maxReconnectAttempts) || maxReconnectAttempts < -1) {
|
|
152
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
153
|
+
console.warn(`[NitroSse] Invalid maxReconnectAttempts (${maxReconnectAttempts}). Defaulting to -1 (infinite).`);
|
|
154
|
+
}
|
|
155
|
+
maxReconnectAttempts = -1;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
let maxAuthRetries = config.maxAuthRetries;
|
|
159
|
+
if (maxAuthRetries !== undefined) {
|
|
160
|
+
if (!Number.isFinite(maxAuthRetries) || maxAuthRetries < 0) {
|
|
161
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
162
|
+
console.warn(`[NitroSse] Invalid maxAuthRetries (${maxAuthRetries}). Defaulting to 3.`);
|
|
163
|
+
}
|
|
164
|
+
maxAuthRetries = 3;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (config.mock !== undefined) {
|
|
168
|
+
if (!config.mock || typeof config.mock !== 'object') {
|
|
169
|
+
throw new NitroSseValidationError('[NitroSse] Invalid mock config: Expected an object.', 'INVALID_CONFIG', {
|
|
170
|
+
received: config.mock
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
const mode = config.mock.mode;
|
|
174
|
+
if (mode !== 'replace' && mode !== 'inject') {
|
|
175
|
+
throw new NitroSseValidationError(`[NitroSse] Invalid mock config: 'mode' must be 'replace' or 'inject', received '${String(mode)}'.`, 'INVALID_CONFIG', {
|
|
176
|
+
received: mode
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
if (!Array.isArray(config.mock.data)) {
|
|
180
|
+
throw new NitroSseValidationError("[NitroSse] Invalid mock config: 'data' must be an array of mock events.", 'INVALID_CONFIG', {
|
|
181
|
+
received: typeof config.mock.data
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return {
|
|
186
|
+
...config,
|
|
187
|
+
url: trimmedUrl,
|
|
188
|
+
...(lowerMethod !== undefined ? {
|
|
189
|
+
method: lowerMethod
|
|
190
|
+
} : {}),
|
|
191
|
+
...(connectionTimeoutMs !== undefined ? {
|
|
192
|
+
connectionTimeoutMs
|
|
193
|
+
} : {}),
|
|
194
|
+
...(readTimeoutMs !== undefined ? {
|
|
195
|
+
readTimeoutMs
|
|
196
|
+
} : {}),
|
|
197
|
+
...(batchingIntervalMs !== undefined ? {
|
|
198
|
+
batchingIntervalMs
|
|
199
|
+
} : {}),
|
|
200
|
+
...(maxBufferSize !== undefined ? {
|
|
201
|
+
maxBufferSize
|
|
202
|
+
} : {}),
|
|
203
|
+
...(retryIntervalMs !== undefined ? {
|
|
204
|
+
retryIntervalMs
|
|
205
|
+
} : {}),
|
|
206
|
+
...(maxRetryIntervalMs !== undefined ? {
|
|
207
|
+
maxRetryIntervalMs
|
|
208
|
+
} : {}),
|
|
209
|
+
...(jitterFactor !== undefined ? {
|
|
210
|
+
jitterFactor
|
|
211
|
+
} : {}),
|
|
212
|
+
...(maxReconnectAttempts !== undefined ? {
|
|
213
|
+
maxReconnectAttempts
|
|
214
|
+
} : {}),
|
|
215
|
+
...(maxAuthRetries !== undefined ? {
|
|
216
|
+
maxAuthRetries
|
|
217
|
+
} : {})
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Public facade and typed event emitter for NitroSse, delegating streaming execution to an SseDriver strategy.
|
|
223
|
+
*/
|
|
3
224
|
export class NitroSseClient {
|
|
4
225
|
_listeners = new Map();
|
|
5
|
-
|
|
226
|
+
_isDisposed = false;
|
|
227
|
+
_pendingHeaders = {};
|
|
6
228
|
constructor(native) {
|
|
7
229
|
this._native = native;
|
|
230
|
+
this._driver = new NativeDriver(native, events => this._dispatchEvents(events));
|
|
8
231
|
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
statusCode: 200
|
|
16
|
-
};
|
|
17
|
-
this._legacyCallback?.([stateEvent]);
|
|
18
|
-
this._emit('state', stateEvent);
|
|
232
|
+
get isDisposed() {
|
|
233
|
+
return this._isDisposed;
|
|
234
|
+
}
|
|
235
|
+
_checkDisposed() {
|
|
236
|
+
if (this._isDisposed) {
|
|
237
|
+
throw new NitroSseDisposedError();
|
|
19
238
|
}
|
|
20
239
|
}
|
|
21
240
|
setup(config, onEvent) {
|
|
241
|
+
this._checkDisposed();
|
|
242
|
+
if (onEvent !== undefined && typeof onEvent !== 'function') {
|
|
243
|
+
throw new NitroSseValidationError("[NitroSse] setup: 'onEvent' must be a function.", 'INVALID_ARGUMENT', {
|
|
244
|
+
received: typeof onEvent
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
const validatedConfig = validateConfig(config);
|
|
248
|
+
if (this.isConnected()) {
|
|
249
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
250
|
+
console.warn('[NitroSse] setup() called while connection is active; stopping previous stream before reconfiguring.');
|
|
251
|
+
}
|
|
252
|
+
this._driver?.stop();
|
|
253
|
+
}
|
|
254
|
+
const hasHeaders = Object.keys(this._pendingHeaders).length > 0 || validatedConfig.headers !== undefined;
|
|
255
|
+
const cleanHeaders = hasHeaders ? sanitizeHeaders({
|
|
256
|
+
...this._pendingHeaders,
|
|
257
|
+
...validatedConfig.headers
|
|
258
|
+
}) : undefined;
|
|
259
|
+
const rawOnBeforeRequest = validatedConfig.onBeforeRequest;
|
|
260
|
+
const safeOnBeforeRequest = rawOnBeforeRequest ? async () => {
|
|
261
|
+
try {
|
|
262
|
+
const h = await rawOnBeforeRequest();
|
|
263
|
+
if (h && typeof h === 'object' && !Array.isArray(h)) {
|
|
264
|
+
return sanitizeHeaders(h);
|
|
265
|
+
}
|
|
266
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__ && h !== undefined && h !== null) {
|
|
267
|
+
console.warn('[NitroSse] onBeforeRequest returned an invalid headers value (expected an object):', h);
|
|
268
|
+
}
|
|
269
|
+
return {};
|
|
270
|
+
} catch (err) {
|
|
271
|
+
console.error('[NitroSse] Error in onBeforeRequest interceptor:', err);
|
|
272
|
+
throw err;
|
|
273
|
+
}
|
|
274
|
+
} : undefined;
|
|
22
275
|
this._config = {
|
|
23
|
-
...
|
|
276
|
+
...validatedConfig,
|
|
277
|
+
...(cleanHeaders !== undefined ? {
|
|
278
|
+
headers: cleanHeaders
|
|
279
|
+
} : {}),
|
|
280
|
+
...(safeOnBeforeRequest !== undefined ? {
|
|
281
|
+
onBeforeRequest: safeOnBeforeRequest
|
|
282
|
+
} : {})
|
|
24
283
|
};
|
|
284
|
+
this._pendingHeaders = {};
|
|
25
285
|
this._legacyCallback = onEvent;
|
|
26
|
-
this._mockState = undefined;
|
|
27
286
|
const isDev = typeof __DEV__ !== 'undefined' ? __DEV__ === true : false;
|
|
287
|
+
const mockConfig = isDev ? this._config.mock : undefined;
|
|
28
288
|
if (!isDev) {
|
|
29
289
|
delete this._config.mock;
|
|
30
290
|
}
|
|
31
|
-
if (
|
|
32
|
-
console.warn('\n' + '=================================================================\n' + '⚠️ [react-native-nitro-sse] WARNING: MOCK STREAMING IS ENABLED! ⚠️\n' + ` Mode: ${
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
this.
|
|
291
|
+
if (mockConfig) {
|
|
292
|
+
console.warn('\n' + '=================================================================\n' + '⚠️ [react-native-nitro-sse] WARNING: MOCK STREAMING IS ENABLED! ⚠️\n' + ` Mode: ${mockConfig.mode.toUpperCase()} | Speed: ${mockConfig.eventsPerSecond ?? 1} events/sec\n` + ' Please ensure mocking is disabled before building for production!\n' + '=================================================================\n');
|
|
293
|
+
const mockEngine = new MockSseEngine(mockConfig, events => {
|
|
294
|
+
this._dispatchEvents(events);
|
|
295
|
+
});
|
|
296
|
+
this._driver = mockConfig.mode === 'replace' ? new MockReplaceDriver(mockEngine) : new MockInjectDriver(this._native, mockEngine);
|
|
297
|
+
} else {
|
|
298
|
+
this._driver = new NativeDriver(this._native, events => this._dispatchEvents(events));
|
|
37
299
|
}
|
|
38
300
|
|
|
39
|
-
//
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
for (const event of events) {
|
|
46
|
-
// Dispatch basic types: 'open', 'message', 'error', 'close', 'heartbeat'
|
|
47
|
-
this._emit(event.type, event);
|
|
48
|
-
|
|
49
|
-
// Dispatch by SSE event name if it's different from the type
|
|
50
|
-
// e.g., if type is 'message' but event name is 'update'
|
|
51
|
-
if (event.event && event.event !== event.type) {
|
|
52
|
-
this._emit(event.event, event);
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
});
|
|
301
|
+
// Wrap the native setup to dispatch events to typed listeners when native streaming is active
|
|
302
|
+
if (mockConfig?.mode !== 'replace') {
|
|
303
|
+
this._native.setup(this._config, events => {
|
|
304
|
+
this._dispatchEvents(events);
|
|
305
|
+
});
|
|
306
|
+
}
|
|
56
307
|
}
|
|
57
308
|
addEventListener(type, listener) {
|
|
58
|
-
|
|
59
|
-
|
|
309
|
+
this._checkDisposed();
|
|
310
|
+
if (typeof type !== 'string' || !type.trim()) {
|
|
311
|
+
throw new NitroSseValidationError("[NitroSse] addEventListener: 'type' must be a non-empty string.", 'INVALID_ARGUMENT', {
|
|
312
|
+
received: type
|
|
313
|
+
});
|
|
60
314
|
}
|
|
61
|
-
|
|
315
|
+
if (typeof listener !== 'function') {
|
|
316
|
+
throw new NitroSseValidationError("[NitroSse] addEventListener: 'listener' must be a function.", 'INVALID_ARGUMENT', {
|
|
317
|
+
received: typeof listener
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
const cleanType = type.trim();
|
|
321
|
+
if (!this._listeners.has(cleanType)) {
|
|
322
|
+
this._listeners.set(cleanType, new Set());
|
|
323
|
+
}
|
|
324
|
+
this._listeners.get(cleanType).add(listener);
|
|
62
325
|
}
|
|
63
326
|
removeEventListener(type, listener) {
|
|
64
|
-
this.
|
|
327
|
+
this._checkDisposed();
|
|
328
|
+
if (typeof type !== 'string' || typeof listener !== 'function') {
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
this._listeners.get(type.trim())?.delete(listener);
|
|
332
|
+
}
|
|
333
|
+
removeAllEventListeners(type) {
|
|
334
|
+
this._checkDisposed();
|
|
335
|
+
if (type !== undefined) {
|
|
336
|
+
if (typeof type === 'string' && type.trim()) {
|
|
337
|
+
this._listeners.delete(type.trim());
|
|
338
|
+
}
|
|
339
|
+
} else {
|
|
340
|
+
this._listeners.clear();
|
|
341
|
+
}
|
|
65
342
|
}
|
|
66
343
|
_emit(type, event) {
|
|
67
344
|
const listeners = this._listeners.get(type);
|
|
68
|
-
if (listeners)
|
|
69
|
-
|
|
345
|
+
if (!listeners || listeners.size === 0) return;
|
|
346
|
+
|
|
347
|
+
// Fast-path for the most common case (single listener)
|
|
348
|
+
if (listeners.size === 1) {
|
|
349
|
+
for (const listener of listeners) {
|
|
70
350
|
try {
|
|
71
351
|
listener(event);
|
|
72
352
|
} catch (e) {
|
|
73
353
|
console.error(`[NitroSse] Error in event listener for "${type}":`, e);
|
|
74
354
|
}
|
|
75
|
-
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
76
357
|
}
|
|
77
|
-
}
|
|
78
|
-
_createSseEvent(rawMock) {
|
|
79
|
-
return {
|
|
80
|
-
type: rawMock.type ?? 'message',
|
|
81
|
-
data: rawMock.data,
|
|
82
|
-
parsedData: rawMock.parsedData,
|
|
83
|
-
id: rawMock.id,
|
|
84
|
-
event: rawMock.event,
|
|
85
|
-
message: rawMock.message,
|
|
86
|
-
statusCode: rawMock.statusCode ?? 200,
|
|
87
|
-
retry: rawMock.retry,
|
|
88
|
-
state: rawMock.state
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
start() {
|
|
92
|
-
if (this._mockIntervalId) {
|
|
93
|
-
clearTimeout(this._mockIntervalId);
|
|
94
|
-
this._mockIntervalId = undefined;
|
|
95
|
-
}
|
|
96
|
-
if (this._config?.mock) {
|
|
97
|
-
const {
|
|
98
|
-
mode,
|
|
99
|
-
data,
|
|
100
|
-
eventsPerSecond = 1,
|
|
101
|
-
loop = false,
|
|
102
|
-
errorRate = 0
|
|
103
|
-
} = this._config.mock;
|
|
104
|
-
this._mockIndex = 0;
|
|
105
358
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
359
|
+
// Multi-listener path: snapshot count to skip listeners added mid-iteration
|
|
360
|
+
const snapshot = listeners.size;
|
|
361
|
+
let i = 0;
|
|
362
|
+
for (const listener of listeners) {
|
|
363
|
+
if (i++ >= snapshot) break;
|
|
364
|
+
try {
|
|
365
|
+
listener(event);
|
|
366
|
+
} catch (e) {
|
|
367
|
+
console.error(`[NitroSse] Error in event listener for "${type}":`, e);
|
|
110
368
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
_dispatchEvents(events) {
|
|
372
|
+
if (this._isDisposed || !Array.isArray(events)) return;
|
|
373
|
+
try {
|
|
374
|
+
this._legacyCallback?.(events);
|
|
375
|
+
} catch (e) {
|
|
376
|
+
console.error('[NitroSse] Error in legacy onEvent callback:', e);
|
|
377
|
+
}
|
|
378
|
+
for (const event of events) {
|
|
379
|
+
if (!event || typeof event !== 'object') continue;
|
|
380
|
+
if (event.type) {
|
|
381
|
+
this._emit(event.type, event);
|
|
118
382
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
// We batch events together in chunks if the calculated interval is under 10ms.
|
|
122
|
-
const batchSize = Math.max(1, Math.round(validatedEventsPerSecond / 100)); // chunk size for 10ms intervals
|
|
123
|
-
const intervalMs = Math.max(10, delayMs * batchSize);
|
|
124
|
-
const scheduleNext = () => {
|
|
125
|
-
if (this._mockIndex >= data.length) {
|
|
126
|
-
if (loop && data.length > 0) {
|
|
127
|
-
this._mockIndex = 0;
|
|
128
|
-
} else {
|
|
129
|
-
if (this._mockIntervalId) {
|
|
130
|
-
clearTimeout(this._mockIntervalId);
|
|
131
|
-
this._mockIntervalId = undefined;
|
|
132
|
-
}
|
|
133
|
-
if (mode === 'replace') {
|
|
134
|
-
this._setMockState('closed');
|
|
135
|
-
}
|
|
136
|
-
const closeEvent = {
|
|
137
|
-
type: 'close',
|
|
138
|
-
statusCode: 200
|
|
139
|
-
};
|
|
140
|
-
this._legacyCallback?.([closeEvent]);
|
|
141
|
-
this._emit('close', closeEvent);
|
|
142
|
-
return;
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
// Simulate connection drops
|
|
147
|
-
if (validatedErrorRate && Math.random() < validatedErrorRate) {
|
|
148
|
-
if (mode === 'replace') {
|
|
149
|
-
this._setMockState('reconnecting');
|
|
150
|
-
}
|
|
151
|
-
const errorEvent = {
|
|
152
|
-
type: 'error',
|
|
153
|
-
message: 'Mock Connection Drop (Simulated Error)',
|
|
154
|
-
statusCode: 500
|
|
155
|
-
};
|
|
156
|
-
this._legacyCallback?.([errorEvent]);
|
|
157
|
-
this._emit('error', errorEvent);
|
|
158
|
-
|
|
159
|
-
// Retry / reconnect delay simulator (e.g. 2000ms)
|
|
160
|
-
this._mockIntervalId = setTimeout(scheduleNext, 2000);
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
const currentItem = data[this._mockIndex];
|
|
164
|
-
const hasCustomDelay = currentItem && typeof currentItem.delayMs === 'number';
|
|
165
|
-
const batch = [];
|
|
166
|
-
if (hasCustomDelay) {
|
|
167
|
-
const rawMock = data[this._mockIndex++];
|
|
168
|
-
if (rawMock) {
|
|
169
|
-
batch.push(this._createSseEvent(rawMock));
|
|
170
|
-
}
|
|
171
|
-
} else {
|
|
172
|
-
for (let i = 0; i < batchSize && this._mockIndex < data.length; i++) {
|
|
173
|
-
const nextItem = data[this._mockIndex];
|
|
174
|
-
if (nextItem && typeof nextItem.delayMs === 'number') {
|
|
175
|
-
break;
|
|
176
|
-
}
|
|
177
|
-
const rawMock = data[this._mockIndex++];
|
|
178
|
-
if (rawMock) {
|
|
179
|
-
batch.push(this._createSseEvent(rawMock));
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
if (batch.length > 0) {
|
|
184
|
-
if (mode === 'replace') {
|
|
185
|
-
this._setMockState('open');
|
|
186
|
-
}
|
|
187
|
-
// 1. Call legacy batch callback if provided
|
|
188
|
-
this._legacyCallback?.(batch);
|
|
189
|
-
|
|
190
|
-
// 2. Dispatch individual events to registered listeners
|
|
191
|
-
for (const event of batch) {
|
|
192
|
-
this._emit(event.type, event);
|
|
193
|
-
if (event.event && event.event !== event.type) {
|
|
194
|
-
this._emit(event.event, event);
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
const nextDelay = hasCustomDelay ? currentItem.delayMs : intervalMs;
|
|
199
|
-
this._mockIntervalId = setTimeout(scheduleNext, nextDelay);
|
|
200
|
-
};
|
|
201
|
-
const firstItem = data[0];
|
|
202
|
-
const firstDelay = firstItem && typeof firstItem.delayMs === 'number' ? firstItem.delayMs : intervalMs;
|
|
203
|
-
if (mode === 'replace') {
|
|
204
|
-
this._setMockState('connecting');
|
|
205
|
-
this._setMockState('open');
|
|
206
|
-
|
|
207
|
-
// Emit simulated open event
|
|
208
|
-
const openEvent = {
|
|
209
|
-
type: 'open',
|
|
210
|
-
statusCode: 200
|
|
211
|
-
};
|
|
212
|
-
this._legacyCallback?.([openEvent]);
|
|
213
|
-
this._emit('open', openEvent);
|
|
214
|
-
this._mockIntervalId = setTimeout(scheduleNext, firstDelay);
|
|
215
|
-
return; // Skip native start
|
|
216
|
-
} else if (mode === 'inject') {
|
|
217
|
-
this._mockIntervalId = setTimeout(scheduleNext, firstDelay);
|
|
383
|
+
if (event.event && event.event !== event.type) {
|
|
384
|
+
this._emit(event.event, event);
|
|
218
385
|
}
|
|
219
386
|
}
|
|
220
|
-
this._native.start();
|
|
221
387
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
}
|
|
227
|
-
if (this._config?.mock?.mode === 'replace') {
|
|
228
|
-
this._setMockState('closed');
|
|
388
|
+
start() {
|
|
389
|
+
this._checkDisposed();
|
|
390
|
+
if (!this._config) {
|
|
391
|
+
throw new NitroSseStateError('[NitroSse] Cannot start SSE stream: client is not configured. Call setup(config) first.');
|
|
229
392
|
}
|
|
230
|
-
this.
|
|
393
|
+
this._driver.start();
|
|
394
|
+
}
|
|
395
|
+
stop() {
|
|
396
|
+
this._checkDisposed();
|
|
397
|
+
this._driver.stop();
|
|
231
398
|
}
|
|
232
399
|
restart() {
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
} else {
|
|
237
|
-
this._native.restart();
|
|
400
|
+
this._checkDisposed();
|
|
401
|
+
if (!this._config) {
|
|
402
|
+
throw new NitroSseStateError('[NitroSse] Cannot restart SSE stream: client is not configured. Call setup(config) first.');
|
|
238
403
|
}
|
|
404
|
+
this._driver.restart();
|
|
239
405
|
}
|
|
240
406
|
flush() {
|
|
241
|
-
this.
|
|
407
|
+
this._checkDisposed();
|
|
408
|
+
this._driver.flush();
|
|
242
409
|
}
|
|
243
410
|
isConnected() {
|
|
244
|
-
if (this.
|
|
245
|
-
|
|
246
|
-
}
|
|
247
|
-
return this._native.isConnected();
|
|
411
|
+
if (this._isDisposed) return false;
|
|
412
|
+
return this._driver.isConnected();
|
|
248
413
|
}
|
|
249
414
|
getStats() {
|
|
250
|
-
if (this.
|
|
415
|
+
if (this._isDisposed) {
|
|
251
416
|
return {
|
|
252
|
-
totalBytesReceived:
|
|
417
|
+
totalBytesReceived: 0,
|
|
253
418
|
reconnectCount: 0
|
|
254
419
|
};
|
|
255
420
|
}
|
|
256
|
-
return this.
|
|
421
|
+
return this._driver.getStats();
|
|
257
422
|
}
|
|
258
423
|
getState() {
|
|
259
|
-
if (this.
|
|
260
|
-
|
|
261
|
-
}
|
|
262
|
-
return this._native.getState();
|
|
424
|
+
if (this._isDisposed) return 'closed';
|
|
425
|
+
return this._driver.getState();
|
|
263
426
|
}
|
|
264
427
|
updateHeaders(headers) {
|
|
265
|
-
this.
|
|
428
|
+
this._checkDisposed();
|
|
429
|
+
if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
|
|
430
|
+
throw new NitroSseValidationError("[NitroSse] updateHeaders: 'headers' must be an object of key-value pairs.", 'INVALID_ARGUMENT', {
|
|
431
|
+
received: headers
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
const clean = sanitizeHeaders(headers);
|
|
435
|
+
if (!this._config) {
|
|
436
|
+
this._pendingHeaders = {
|
|
437
|
+
...this._pendingHeaders,
|
|
438
|
+
...clean
|
|
439
|
+
};
|
|
440
|
+
this._driver.updateHeaders(clean);
|
|
441
|
+
} else {
|
|
442
|
+
this._config.headers = {
|
|
443
|
+
...this._config.headers,
|
|
444
|
+
...clean
|
|
445
|
+
};
|
|
446
|
+
this._driver.updateHeaders(this._config.headers);
|
|
447
|
+
}
|
|
266
448
|
}
|
|
267
449
|
setLastProcessedId(id) {
|
|
268
|
-
this.
|
|
450
|
+
this._checkDisposed();
|
|
451
|
+
if (typeof id !== 'string') {
|
|
452
|
+
throw new NitroSseValidationError("[NitroSse] setLastProcessedId: 'id' must be a string.", 'INVALID_ARGUMENT', {
|
|
453
|
+
received: id
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
this._driver.setLastProcessedId(id);
|
|
269
457
|
}
|
|
270
458
|
injectMockEvent(event) {
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
459
|
+
this._checkDisposed();
|
|
460
|
+
if (!event || typeof event !== 'object' || Array.isArray(event)) {
|
|
461
|
+
throw new NitroSseValidationError("[NitroSse] injectMockEvent: 'event' must be an object.", 'INVALID_ARGUMENT', {
|
|
462
|
+
received: event
|
|
463
|
+
});
|
|
276
464
|
}
|
|
465
|
+
this._driver.injectMockEvent(event);
|
|
466
|
+
}
|
|
467
|
+
dispose() {
|
|
468
|
+
if (this._isDisposed) return;
|
|
469
|
+
this._isDisposed = true;
|
|
470
|
+
this._listeners.clear();
|
|
471
|
+
this._legacyCallback = undefined;
|
|
472
|
+
this._pendingHeaders = {};
|
|
473
|
+
this._driver?.dispose();
|
|
277
474
|
}
|
|
278
475
|
}
|
|
279
476
|
//# sourceMappingURL=NitroSseClient.js.map
|