forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsse-parser.ts
More file actions
71 lines (62 loc) · 2.1 KB
/
Copy pathsse-parser.ts
File metadata and controls
71 lines (62 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Framework-agnostic parsing helpers for the text/event-stream (SSE) wire
* format emitted by the backend's `@Sse()` endpoints. Kept dependency-free
* so it can be unit tested without any React Native runtime.
*/
export interface ParsedSseEvent {
event: string | null;
data: string;
id: string | null;
}
interface ParseResult {
events: ParsedSseEvent[];
rest: string;
}
/**
* Parses as many complete SSE frames (terminated by a blank line) as are
* present in `buffer`. Returns the parsed events plus whatever incomplete
* trailing text should be retained for the next chunk.
*/
export function parseSseBuffer(buffer: string): ParseResult {
const normalized = buffer.replace(/\r\n/g, "\n");
const frames = normalized.split("\n\n");
// The last element is either "" (buffer ended on a blank line) or an
// incomplete frame awaiting more data.
const rest = frames.pop() ?? "";
const events: ParsedSseEvent[] = [];
for (const frame of frames) {
if (frame.trim().length === 0) continue;
const parsed = parseSseFrame(frame);
if (parsed) events.push(parsed);
}
return { events, rest };
}
function parseSseFrame(frame: string): ParsedSseEvent | null {
const dataLines: string[] = [];
let event: string | null = null;
let id: string | null = null;
for (const line of frame.split("\n")) {
if (line.startsWith(":")) continue; // comment / keep-alive
if (line.startsWith("data:")) {
dataLines.push(line.slice(5).replace(/^ /, ""));
} else if (line.startsWith("event:")) {
event = line.slice(6).replace(/^ /, "");
} else if (line.startsWith("id:")) {
id = line.slice(3).replace(/^ /, "");
}
}
if (dataLines.length === 0) return null;
return { event, data: dataLines.join("\n"), id };
}
/**
* Exponential backoff with a hard cap and no jitter, used to space out SSE
* reconnect attempts. `attempt` is 0-indexed (first retry = attempt 0).
*/
export function nextReconnectDelayMs(
attempt: number,
baseMs = 1000,
maxMs = 30000,
): number {
const uncapped = baseMs * Math.pow(2, Math.max(0, attempt));
return Math.min(uncapped, maxMs);
}