| 310 | } |
| 311 | |
| 312 | function feed(chunk: string): SseError | undefined { |
| 313 | // Empty chunks must not consume the leading BOM check below |
| 314 | if (chunk.length === 0) return |
| 315 | |
| 316 | // Strip a UTF-8 byte order mark (BOM) at the start of the stream |
| 317 | if (isFirstChunk && chunk.startsWith(BOM)) { |
| 318 | chunk = chunk.slice(BOM.length) |
| 319 | } |
| 320 | |
| 321 | isFirstChunk = false |
| 322 | |
| 323 | const length = chunk.length |
| 324 | const currentGeneration = generation |
| 325 | let position = 0 |
| 326 | |
| 327 | while (position < length) { |
| 328 | // Skip the LF of a CRLF, whose CR may have ended the previous chunk |
| 329 | if (discardTrailingNewline) { |
| 330 | discardTrailingNewline = false |
| 331 | if (chunk.charCodeAt(position) === LF) { |
| 332 | ++position |
| 333 | continue |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | let lineEnd = position |
| 338 | while (lineEnd < length) { |
| 339 | const code = chunk.charCodeAt(lineEnd) |
| 340 | if (code === CR || code === LF) break |
| 341 | ++lineEnd |
| 342 | } |
| 343 | |
| 344 | if (lineEnd === length) { |
| 345 | pending.push(chunk.slice(position)) |
| 346 | pendingLength += length - position |
| 347 | break |
| 348 | } |
| 349 | |
| 350 | discardTrailingNewline = chunk.charCodeAt(lineEnd) === CR |
| 351 | |
| 352 | let line = chunk.slice(position, lineEnd) |
| 353 | if (pending.length > 0) { |
| 354 | pending.push(line) |
| 355 | line = pending.join("") |
| 356 | pending = [] |
| 357 | pendingLength = 0 |
| 358 | } |
| 359 | parseLine(line) |
| 360 | |
| 361 | if (generation !== currentGeneration) { |
| 362 | // `onParse` reset the parser, so drop the rest of this chunk |
| 363 | return |
| 364 | } |
| 365 | |
| 366 | position = lineEnd + 1 |
| 367 | } |
| 368 | |
| 369 | if (pendingLength + data.length > maxEventSize) { |