1
>
/*---------------------------------------------------------------------------------------------
sseParser.ts
2
>
* Copyright (c) Microsoft Corporation. All rights reserved.
3
>
* Licensed under the MIT License. See License.txt in the project root for license information.
4
>
*--------------------------------------------------------------------------------------------*/
5
>
6
>
/**
7
>
* Parser for Server-Sent Events (SSE) streams according to the HTML specification.
8
>
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
9
>
*/
10
>
11
>
/**
12
>
* Represents an event dispatched from an SSE stream.
13
>
*/
14
>
export interface ISSEEvent {
15
>
/**
16
>
* The event type. If not specified, the type is "message".
17
>
*/
18
>
type: string;
19
>
20
>
/**
21
>
* The event data.
22
>
*/
23
>
data: string;
24
>
25
>
/**
26
>
* The last event ID, used for reconnection.
27
>
*/
28
>
id?: string;
29
>
30
>
/**
31
>
* Reconnection time in milliseconds.
32
>
*/
33
>
retry?: number;
34
>
}
35
>
36
>
/**
37
>
* Callback function type for event dispatch.
38
>
*/
39
>
export type SSEEventHandler = (event: ISSEEvent) => void;
40
>
41
>
const enum Chr {
42
>
CR = 13, // '\r'
43
>
LF = 10, // '\n'
44
>
COLON = 58, // ':'
45
>
SPACE = 32, // ' '
46
>
}
47
>
48
>
/**
49
>
* Parser for Server-Sent Events (SSE) streams.
50
>
*/
51
>
export class SSEParser {
52
>
private dataBuffer = '';
53
>
private eventTypeBuffer = '';
54
>
private currentEventId?: string;
55
>
private lastEventIdBuffer?: string;
56
>
private reconnectionTime?: number;
57
>
private buffer: Uint8Array[] = [];
58
>
private endedOnCR = false;
59
>
private readonly onEventHandler: SSEEventHandler;
60
>
private readonly decoder: TextDecoder;
61
>
/**
62
>
* Creates a new SSE parser.
63
>
* @param onEvent The callback to invoke when an event is dispatched.
64
>
*/
65
>
constructor(onEvent: SSEEventHandler) {
66
this.onEventHandler = onEvent;
67
this.decoder = new TextDecoder('utf-8');
68
}
70
>
/**
71
>
* Gets the last event ID received by this parser.
72
>
*/
73
>
public getLastEventId(): string | undefined {
74
return this.lastEventIdBuffer;
75
}
77
>
* Gets the reconnection time in milliseconds, if one was specified by the server.
78
>
*/
79
>
public getReconnectionTime(): number | undefined {
80
return this.reconnectionTime;
81
}
83
>
/**
84
>
* Feeds a chunk of the SSE stream to the parser.
85
>
* @param chunk The chunk to parse as a Uint8Array of UTF-8 encoded data.
86
>
*/
87
>
public feed(chunk: Uint8Array): void {
88
if (chunk.length === 0) {
89
return;