* Decodes a line of text and returns a ServerSentEvent object if a complete event is found. * @param line - The line of text to decode. * @returns A ServerSentEvent object if a complete event is found, otherwise null.
(line: string)
| 337 | * @returns A ServerSentEvent object if a complete event is found, otherwise null. |
| 338 | */ |
| 339 | decode(line: string) { |
| 340 | if (line.endsWith('\r')) { |
| 341 | line = line.substring(0, line.length - 1); |
| 342 | } |
| 343 | |
| 344 | if (!line) { |
| 345 | // empty line and we didn't previously encounter any messages |
| 346 | if (!this.event && !this.data.length) return null; |
| 347 | |
| 348 | const sse: ServerSentEvent = { |
| 349 | event: this.event, |
| 350 | data: this.data.join('\n'), |
| 351 | raw: this.chunks, |
| 352 | }; |
| 353 | |
| 354 | this.event = null; |
| 355 | this.data = []; |
| 356 | this.chunks = []; |
| 357 | |
| 358 | return sse; |
| 359 | } |
| 360 | |
| 361 | this.chunks.push(line); |
| 362 | |
| 363 | if (line.startsWith(':')) { |
| 364 | return null; |
| 365 | } |
| 366 | |
| 367 | let [fieldname, _, value] = partition(line, ':'); |
| 368 | |
| 369 | if (value.startsWith(' ')) { |
| 370 | value = value.substring(1); |
| 371 | } |
| 372 | |
| 373 | if (fieldname === 'event') { |
| 374 | this.event = value; |
| 375 | } else if (fieldname === 'data') { |
| 376 | this.data.push(value); |
| 377 | } |
| 378 | |
| 379 | return null; |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | /** |
no test coverage detected