-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
parser.ts
138 lines (127 loc) · 4.14 KB
/
parser.ts
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/**
*
* parser
*
*/
import {
StreamMessage,
validateStreamEvent,
parseStreamData,
StreamEvent,
} from './common';
enum ControlChars {
NewLine = 10,
CarriageReturn = 13,
Space = 32,
Colon = 58,
}
/**
* HTTP response chunk parser for graphql-sse's event stream messages.
*
* Reference: https://github.com/Azure/fetch-event-source/blob/main/src/parse.ts
*
* @private
*/
export function createParser<ForID extends boolean>(): (
chunk: Uint8Array,
) => StreamMessage<ForID, StreamEvent>[] | void {
let buffer: Uint8Array | undefined;
let position: number; // current read position
let fieldLength: number; // length of the `field` portion of the line
let discardTrailingNewline = false;
let message = { event: '', data: '' };
let pending: StreamMessage<ForID, StreamEvent>[] = [];
const decoder = new TextDecoder();
return function parse(chunk) {
if (buffer === undefined) {
buffer = chunk;
position = 0;
fieldLength = -1;
} else {
const concat = new Uint8Array(buffer.length + chunk.length);
concat.set(buffer);
concat.set(chunk, buffer.length);
buffer = concat;
}
const bufLength = buffer.length;
let lineStart = 0; // index where the current line starts
while (position < bufLength) {
if (discardTrailingNewline) {
if (buffer[position] === ControlChars.NewLine) {
lineStart = ++position; // skip to next char
}
discardTrailingNewline = false;
}
// look forward until the end of line
let lineEnd = -1; // index of the \r or \n char
for (; position < bufLength && lineEnd === -1; ++position) {
switch (buffer[position]) {
case ControlChars.Colon:
if (fieldLength === -1) {
// first colon in line
fieldLength = position - lineStart;
}
break;
// \r case below should fallthrough to \n:
case ControlChars.CarriageReturn:
discardTrailingNewline = true;
// eslint-disable-next-line no-fallthrough
case ControlChars.NewLine:
lineEnd = position;
break;
}
}
if (lineEnd === -1) {
// end of the buffer but the line hasn't ended
break;
} else if (lineStart === lineEnd) {
// empty line denotes end of incoming message
if (message.event || message.data) {
// NOT a server ping (":\n\n")
if (!message.event) throw new Error('Missing message event');
const event = validateStreamEvent(message.event);
const data = parseStreamData<ForID, StreamEvent>(event, message.data);
pending.push({
event,
data,
});
message = { event: '', data: '' };
}
} else if (fieldLength > 0) {
// end of line indicates message
const line = buffer.subarray(lineStart, lineEnd);
// exclude comments and lines with no values
// line is of format "<field>:<value>" or "<field>: <value>"
// https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
const field = decoder.decode(line.subarray(0, fieldLength));
const valueOffset =
fieldLength + (line[fieldLength + 1] === ControlChars.Space ? 2 : 1);
const value = decoder.decode(line.subarray(valueOffset));
switch (field) {
case 'event':
message.event = value;
break;
case 'data':
// append the new value if the message has data
message.data = message.data ? message.data + '\n' + value : value;
break;
}
}
// next line
lineStart = position;
fieldLength = -1;
}
if (lineStart === bufLength) {
// finished reading
buffer = undefined;
const messages = [...pending];
pending = [];
return messages;
} else if (lineStart !== 0) {
// create a new view into buffer beginning at lineStart so we don't
// need to copy over the previous lines when we get the new chunk
buffer = buffer.subarray(lineStart);
position -= lineStart;
}
};
}