| 354 | } |
| 355 | |
| 356 | function parseEventStreamLine( |
| 357 | lineBuffer: string, |
| 358 | index: number, |
| 359 | fieldLength: number, |
| 360 | lineLength: number |
| 361 | ) { |
| 362 | if (lineLength === 0) { |
| 363 | // We reached the last line of this event |
| 364 | if (data.length > 0) { |
| 365 | onParse({ |
| 366 | _tag: "Event", |
| 367 | id: lastEventId, |
| 368 | event: eventName || "message", |
| 369 | data: data.slice(0, -1) // remove trailing newline |
| 370 | }) |
| 371 | data = "" |
| 372 | } |
| 373 | eventName = undefined |
| 374 | return |
| 375 | } |
| 376 | |
| 377 | const noValue = fieldLength < 0 |
| 378 | const field = lineBuffer.slice(index, index + (noValue ? lineLength : fieldLength)) |
| 379 | let step = 0 |
| 380 | |
| 381 | if (noValue) { |
| 382 | step = lineLength |
| 383 | } else if (lineBuffer[index + fieldLength + 1] === " ") { |
| 384 | step = fieldLength + 2 |
| 385 | } else { |
| 386 | step = fieldLength + 1 |
| 387 | } |
| 388 | |
| 389 | const position = index + step |
| 390 | const valueLength = lineLength - step |
| 391 | const value = lineBuffer.slice(position, position + valueLength).toString() |
| 392 | |
| 393 | if (field === "data") { |
| 394 | data += value ? `${value}\n` : "\n" |
| 395 | } else if (field === "event") { |
| 396 | eventName = value |
| 397 | } else if (field === "id" && !value.includes("\u0000")) { |
| 398 | lastEventId = value |
| 399 | } else if (field === "retry" && /^\d+$/.test(value)) { |
| 400 | const retry = parseInt(value, 10) |
| 401 | onParse(new Retry({ duration: Duration.millis(retry), lastEventId })) |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | const BOM = "\uFEFF" |