MCPcopy Create free account
hub / github.com/Effect-TS/effect / makeParser

Function makeParser

packages/effect/src/unstable/encoding/Sse.ts:250–404  ·  view source on GitHub ↗
(onParse: (event: AnyEvent) => void, options?: DecodeOptions)

Source from the content-addressed store, hash-verified

248 * @since 4.0.0
249 */
250export function makeParser(onParse: (event: AnyEvent) => void, options?: DecodeOptions): Parser {
251 const maxEventSize = options?.maxEventSize ?? defaultMaxEventSize
252
253 // Processing state
254 let isFirstChunk: boolean
255 let buffer: string
256 let startingPosition: number
257 let startingFieldLength: number
258 let discardTrailingNewline: boolean
259
260 // Event state
261 let lastEventId: string | undefined
262 let eventName: string | undefined
263 let data: string
264
265 reset()
266 return { feed, reset }
267
268 function reset(): void {
269 isFirstChunk = true
270 buffer = ""
271 startingPosition = 0
272 startingFieldLength = -1
273 discardTrailingNewline = false
274
275 lastEventId = undefined
276 eventName = undefined
277 data = ""
278 }
279
280 function feed(chunk: string): SseError | undefined {
281 buffer = buffer ? buffer + chunk : chunk
282
283 // Strip any UTF-8 byte order mark (BOM) at the start of the stream.
284 // Note that we do not strip any non - UTF8 BOM, as eventsource streams are
285 // always decoded as UTF8 as per the specification.
286 if (isFirstChunk && buffer.startsWith(BOM)) {
287 buffer = buffer.slice(BOM.length)
288 }
289
290 isFirstChunk = false
291
292 // Set up chunk-specific processing state
293 const length = buffer.length
294 let position = 0
295
296 // Read the current buffer byte by byte
297 while (position < length) {
298 // EventSource allows for carriage return + line feed, which means we
299 // need to ignore a linefeed character if the previous character was a
300 // carriage return
301 // @todo refactor to reduce nesting, consider checking previous byte?
302 // @todo but consider multiple chunks etc
303 if (discardTrailingNewline) {
304 if (buffer[position] === "\n") {
305 ++position
306 }
307 discardTrailingNewline = false

Callers 1

decodeFunction · 0.70

Calls 1

resetFunction · 0.70

Tested by

no test coverage detected