{"name":"eventsource-parser","version":"3.0.7","keywords":["eventsource","server-sent-events","sse"],"author":{"name":"Espen Hovlandsdal","email":"espen@hovlandsdal.com"},"license":"MIT","_id":"eventsource-parser@3.0.7","maintainers":[{"name":"rexxars","email":"espen@hovlandsdal.com"}],"homepage":"https://github.com/rexxars/eventsource-parser#readme","bugs":{"url":"https://github.com/rexxars/eventsource-parser/issues"},"dist":{"shasum":"65d2fd0e55fae5c3ba442c0f9b8c2fb5901145f1","tarball":"http://registry-npm.ywwl.com/eventsource-parser/download/eventsource-parser-3.0.7.tgz","fileCount":21,"integrity":"sha512-zwxwiQqexizSXFZV13zMiEtW1E3lv7RlUv+1f5FBiR4x7wFhEjm3aFTyYkZQWzyN08WnPdox015GoRH5D/E5YA==","signatures":[{"sig":"MEQCIDtBNSjTfYKCXONF5XckloStKRqtIVTOTNap/oY9t0aYAiAE4Kct5OCjMBTc8YK/IWHDPJVPMv+oczO/A1xcmtfZcQ==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/eventsource-parser@3.0.7","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":103275,"size":19469,"noattachment":false,"key":"/eventsource-parser/-/eventsource-parser-3.0.7.tgz"},"main":"./dist/index.cjs","type":"module","types":"./dist/index.d.ts","module":"./dist/index.js","engines":{"node":">=18.0.0"},"exports":{".":{"import":"./dist/index.js","source":"./src/index.ts","default":"./dist/index.js","require":"./dist/index.cjs"},"./stream":{"import":"./dist/stream.js","source":"./src/stream.ts","default":"./dist/stream.js","require":"./dist/stream.cjs"},"./package.json":"./package.json"},"gitHead":"3ea73f761f5d6fd97a97311e1f7e68eb212a85a9","scripts":{"knip":"knip","lint":"oxlint && tsc --noEmit","test":"npm run test:node","bench":"node --expose-gc --experimental-strip-types --no-warnings=ExperimentalWarning bench/parse.bench.ts","build":"pkg-utils build && pkg-utils --strict","check":"npm run clean && npm run format && npm run lint && npm run build && vitest run","clean":"rimraf dist coverage","format":"oxfmt","posttest":"npm run lint","prebuild":"npm run clean","test:bun":"bun test","test:deno":"deno run --allow-write --allow-net --allow-run --allow-sys --allow-ffi --allow-env --allow-read npm:vitest","test:node":"vitest --reporter=verbose","bundle-size":"node --experimental-strip-types --no-warnings=ExperimentalWarning scripts/bundle-size.ts","format:check":"oxfmt --check","prepublishOnly":"npm run build"},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"oidc:eb594077-29c4-46ad-bb43-576dad083e37"}},"repository":{"url":"git+ssh://git@github.com/rexxars/eventsource-parser.git","type":"git"},"_npmVersion":"11.12.1","description":"Streaming, source-agnostic EventSource/Server-Sent Events parser","directories":{},"sideEffects":false,"_nodeVersion":"24.14.1","browserslist":["node >= 18","chrome >= 71","safari >= 14.1","firefox >= 105","edge >= 79"],"_hasShrinkwrap":false,"devDependencies":{"knip":"^6.4.1","oxfmt":"^0.45.0","mitata":"^1.0.34","oxlint":"^1.60.0","rimraf":"^6.1.3","terser":"^5.46.1","vitest":"^4.1.4","typescript":"^5.9.3","@types/node":"^20.19.0","@sanity/tsconfig":"^2.1.0","semantic-release":"^25.0.3","@sanity/pkg-utils":"^10.4.15","eventsource-encoder":"^1.0.1","rollup-plugin-visualizer":"^6.0.3","@sanity/semantic-release-preset":"^6.0.0"},"_npmOperationalInternal":{"tmp":"tmp/eventsource-parser_3.0.7_1776460037175_0.7687342211021788","host":"s3://npm-registry-packages-npm-production"},"readme":"# eventsource-parser\n\n[![npm version](https://npmx.dev/api/registry/badge/version/eventsource-parser)](https://npmx.dev/package/eventsource-parser) [![num dependendencies](https://npmx.dev/api/registry/badge/dependencies/eventsource-parser)](https://npmx.dev/package/eventsource-parser) [![npm weekly downloads](https://npmx.dev/api/registry/badge/downloads-week/eventsource-parser)](https://npmx.dev/package/eventsource-parser) [![install size](https://npmx.dev/api/registry/badge/size/eventsource-parser)](https://npmx.dev/package/eventsource-parser)\n\nA streaming parser for [server-sent events/eventsource](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events), without any assumptions about how the actual stream of data is retrieved. It is intended to be a building block for [clients](https://github.com/rexxars/eventsource-client) and polyfills in javascript environments such as browsers, node.js and deno.\n\nIf you are looking for a modern client implementation, see [eventsource-client](https://github.com/rexxars/eventsource-client).\n\nYou create an instance of the parser, and _feed_ it chunks of data - partial or complete, and the parser emits parsed messages once it receives a complete message. A [TransformStream variant](#stream-usage) is also available for environments that support it (modern browsers, Node 22.12 and higher).\n\nOther modules in the EventSource family:\n\n- [eventsource](https://github.com/eventsource/eventsource): Cross-runtime polyfill for the WhatWG EventSource API.\n- [eventsource-encoder](https://github.com/rexxars/eventsource-encoder): encodes messages in the EventSource/Server-Sent Events format.\n- [eventsource-client](https://github.com/rexxars/eventsource-client): modern, feature rich eventsource client for browsers, node.js, bun, deno and other modern JavaScript environments.\n\n> [!NOTE]\n> Migrating from eventsource-parser 1.x/2.x? See the [migration guide](./MIGRATE-v3.md).\n\n## Installation\n\n```bash\nnpm install --save eventsource-parser\n```\n\n## Usage\n\n```ts\nimport {createParser, type EventSourceMessage} from 'eventsource-parser'\n\nfunction onEvent(event: EventSourceMessage) {\n  console.log('Received event!')\n  console.log('id: %s', event.id || '<none>')\n  console.log('event: %s', event.event || '<none>')\n  console.log('data: %s', event.data)\n}\n\nconst parser = createParser({onEvent})\nconst sseStream = getSomeReadableStream()\n\nfor await (const chunk of sseStream) {\n  parser.feed(chunk)\n}\n\n// If you want to re-use the parser for a new stream of events, make sure to reset it!\nparser.reset()\nconsole.log('Done!')\n```\n\n### Event IDs\n\nUse `onId` if you need to track event IDs for reconnection. The parser calls it once when a blank\nline ends a block containing a valid `id` field. It runs for blocks with or without `data`, and it\nruns before `onEvent` when the same block produces an event. An empty `id` field is reported as an\nempty string. An `id` field containing U+0000 is ignored.\n\n```ts\nlet lastEventId = ''\n\nconst parser = createParser({\n  onId(id) {\n    lastEventId = id\n  },\n  onEvent(event) {\n    // …\n  },\n})\n```\n\n### Retry intervals\n\nIf the server sends a `retry` field in the event stream, the parser will call any `onRetry` callback specified to the `createParser` function:\n\n```ts\nconst parser = createParser({\n  onRetry(retryInterval) {\n    console.log('Server requested retry interval of %dms', retryInterval)\n  },\n  onEvent(event) {\n    // …\n  },\n})\n```\n\n### Parse errors\n\nIf the parser encounters an error while parsing, it will call any `onError` callback provided to the `createParser` function:\n\n```ts\nimport {type ParseError} from 'eventsource-parser'\n\nconst parser = createParser({\n  onError(error: ParseError) {\n    console.error('Error parsing event:', error)\n    if (error.type === 'unknown-field') {\n      console.error('Field name:', error.field)\n      console.error('Field value:', error.value)\n      console.error('Line:', error.line)\n    } else if (error.type === 'invalid-retry') {\n      console.error('Invalid retry interval:', error.value)\n    }\n  },\n  onEvent(event) {\n    // …\n  },\n})\n```\n\nNote that `unknown-field` errors are emitted for completed invalid lines, not only data shaped as `field: value`. This is because the EventSource specification says to treat anything prior to a `:` as the field name. Incomplete lines that cannot become a valid SSE field may be discarded before completion to avoid unbounded buffering, in which case `onError` is not called and no `line`, `field`, or `value` is retained.\n\n> [!NOTE]\n> When encountering the end of a stream, calling `.reset({consume: true})` on the parser to flush any remaining data and reset the parser state. This will trigger the `onError` callback if the pending data has not already been discarded as an invalid line.\n\n### Comments\n\nThe parser will ignore comments (lines starting with `:`) by default. If you want to handle comments, you can provide an `onComment` callback to the `createParser` function:\n\n```ts\nconst parser = createParser({\n  onComment(comment) {\n    console.log('Received comment:', comment)\n  },\n  onEvent(event) {\n    // …\n  },\n})\n```\n\n> [!NOTE]\n> Leading whitespace is not stripped from comments, eg `: comment` will give ` comment` as the comment value, not `comment` (note the leading space).\n\n### Limiting buffered memory (`maxBufferSize`)\n\nBy default the parser buffers valid partial lines and event data until a server completes an event. A server (or proxy) that starts a valid field and never terminates the line, or that keeps appending `data:` lines without ever sending a blank line to dispatch the event, can therefore grow the parser's buffers without bound. Lines that cannot become valid SSE fields are discarded without buffering.\n\nPass a `maxBufferSize` (in characters) to `createParser` to cap this. If the combined size of the pending line buffer and the in-progress event's data buffer exceeds the limit, the parser emits a `ParseError` with `type: 'max-buffer-size-exceeded'` and becomes terminated: subsequent calls to `feed()` will throw until `reset()` is called.\n\n```ts\nconst parser = createParser({\n  maxBufferSize: 1024 * 1024, // 1 MB\n  onEvent(event) {\n    // …\n  },\n  onError(error) {\n    if (error.type === 'max-buffer-size-exceeded') {\n      // Stream peer is misbehaving — typically you'd close the connection.\n    }\n  },\n})\n```\n\nThe same option is available on the [stream variant](#stream-usage); the stream is always errored when this limit is exceeded, regardless of the `onError` setting (since the underlying parser is unrecoverable without a `reset()`).\n\n## Stream usage\n\n```ts\nimport {EventSourceParserStream} from 'eventsource-parser/stream'\n\nconst eventStream = response.body\n  .pipeThrough(new TextDecoderStream())\n  .pipeThrough(new EventSourceParserStream())\n```\n\nThe stream constructor accepts a subset of the `createParser` options (`onComment`, `onId`, `onRetry`, `maxBufferSize`) plus an `onError` that can either be a function or set to `'terminate'` to error the stream on parse errors. Events are delivered through the stream itself rather than via an `onEvent` callback:\n\n```ts\nnew EventSourceParserStream({\n  maxBufferSize: 1024 * 1024,\n  onError: 'terminate',\n})\n```\n\nNote that the TransformStream is exposed under a separate export (`eventsource-parser/stream`), in order to maximize compatibility with environments that do not have the `TransformStream` constructor available.\n\n## License\n\nMIT © [Espen Hovlandsdal](https://espen.codes/)\n","publish_time":1776460037307,"_cnpm_publish_time":1776460037307,"dist-tags":{"beta":"3.0.0-beta.0","latest":"4.1.3"}}