Enhance message parsing to preserve newlines from empty data fields
Fix: Preserve newlines from empty data fields in Server-Sent Events parsing
Issue:#50
Description
Problem
The current implementation of the Server-Sent Events (SSE) parser incorrectly handles empty data fields. When multiple consecutive empty data: fields are encountered, the parser was not preserving the newline characters that should be added for each empty field, causing data loss and incorrect message formatting.
According to the Server-Sent Events specification, each data: field should append its value to the data buffer followed by a single U+000A LINE FEED (LF) character. This means that empty data: fields should still contribute a newline character to the final message data.
Solution
Modified the getMessages function in src/parse.ts to properly handle empty data fields by ensuring that each data: field (including empty ones) contributes a newline character to the message data buffer.
Key changes:
- Updated the data field processing logic to always append a newline character (
\n) after each data field value, regardless of whether the value is empty - Added comprehensive test coverage for this edge case in
src/parse.spec.ts
Example
Before (incorrect behavior):
event: message
data:
data:
data: foo
Would result in: data: "foo" (missing newlines from empty data fields)
After (correct behavior):
event: message
data:
data:
data: foo
Results in: data: "\n\nfoo" (preserving newlines from empty data fields)
Testing
- Added test case
should preserve newlines from empty data fieldsto verify the fix - All existing tests continue to pass
- Updated test configuration in
jasmine.jsonto point to the correct spec directory
Impact
This fix ensures full compliance with the Server-Sent Events specification and prevents data loss when processing SSE streams that contain empty data fields, which is a common pattern for formatting multi-line messages or creating visual spacing in SSE data.
Additional Information for the PR
Type of Change
- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Documentation update
Testing
- [x] I have added tests that prove my fix is effective or that my feature works
- [x] New and existing unit tests pass locally with my changes
- [x] Any dependent changes have been merged and published
Checklist
- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my own code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation (if applicable)
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my feature works
- [x] New and existing unit tests pass locally with my changes
@microsoft-github-policy-service agree