@fastify/sse 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @fastify/sse
2
2
 
3
3
  [![NPM Version](https://img.shields.io/npm/v/@fastify/sse.svg)](https://npmjs.org/package/@fastify/sse)
4
- [![CI](https://github.com/fastify/fastify-sse/workflows/CI/badge.svg)](https://github.com/fastify/fastify-sse/actions)
4
+ [![CI](https://github.com/fastify/sse/workflows/CI/badge.svg)](https://github.com/fastify/sse/actions)
5
5
 
6
6
  Server-Sent Events plugin for Fastify. Provides first-class SSE support with clean API integration, session management, and streaming capabilities.
7
7
 
package/index.js CHANGED
@@ -89,6 +89,7 @@ class SSEContext {
89
89
  this._lastEventId = options.lastEventId || null
90
90
  this._isConnected = true
91
91
  this._keepAlive = false
92
+ this._headersSent = false
92
93
  this.heartbeatTimer = null
93
94
  this.closeCallbacks = []
94
95
  this.serializer = options.serializer
@@ -99,24 +100,49 @@ class SSEContext {
99
100
  this.cleanup()
100
101
  })
101
102
 
103
+ // Handle errors on the raw response to prevent uncaught exceptions
104
+ this.reply.raw.on('error', (error) => {
105
+ // Client disconnection is expected behavior, handle gracefully
106
+ this._isConnected = false
107
+ this.cleanup()
108
+ // Log as info since client disconnections are normal
109
+ this.reply.log.info({ err: error }, 'SSE connection closed')
110
+ })
111
+
102
112
  // Start heartbeat if enabled
103
113
  if (options.heartbeatInterval > 0) {
104
114
  this.startHeartbeat(options.heartbeatInterval)
105
115
  }
106
116
  }
107
117
 
118
+ /**
119
+ * Gets the last event ID from the client's Last-Event-ID header.
120
+ * @returns {string|null} The last event ID or null if not present
121
+ */
108
122
  get lastEventId () {
109
123
  return this._lastEventId
110
124
  }
111
125
 
126
+ /**
127
+ * Checks if the SSE connection is still active.
128
+ * @returns {boolean} True if connected, false otherwise
129
+ */
112
130
  get isConnected () {
113
131
  return this._isConnected
114
132
  }
115
133
 
134
+ /**
135
+ * Marks the connection to be kept alive after the handler completes.
136
+ * Without calling this, the connection will close after the handler returns.
137
+ */
116
138
  keepAlive () {
117
139
  this._keepAlive = true
118
140
  }
119
141
 
142
+ /**
143
+ * Closes the SSE connection and performs cleanup.
144
+ * Safe to call multiple times.
145
+ */
120
146
  close () {
121
147
  if (!this._isConnected) return
122
148
 
@@ -125,16 +151,51 @@ class SSEContext {
125
151
  this.reply.raw.end()
126
152
  }
127
153
 
154
+ /**
155
+ * Registers a callback to be called when the connection closes.
156
+ * @param {Function} callback - Function to call on connection close
157
+ */
128
158
  onClose (callback) {
129
159
  this.closeCallbacks.push(callback)
130
160
  }
131
161
 
162
+ /**
163
+ * Executes a callback with the last event ID for replay functionality.
164
+ * Only calls the callback if a last event ID exists.
165
+ * @param {Function} callback - Async function that receives the last event ID
166
+ */
132
167
  async replay (callback) {
133
168
  if (!this._lastEventId) return
134
169
 
135
170
  await callback(this._lastEventId)
136
171
  }
137
172
 
173
+ /**
174
+ * Sends HTTP headers for the SSE response if not already sent.
175
+ * This method ensures headers set via reply.header() are transferred
176
+ * to the raw response before calling writeHead(200).
177
+ * Called automatically before the first SSE data is sent.
178
+ * @private
179
+ */
180
+ sendHeaders () {
181
+ if (!this._headersSent) {
182
+ // Get any headers set via reply.header() and transfer to raw response
183
+ const replyHeaders = this.reply.getHeaders()
184
+ for (const [name, value] of Object.entries(replyHeaders)) {
185
+ this.reply.raw.setHeader(name, value)
186
+ }
187
+
188
+ this.reply.raw.writeHead(200)
189
+ this._headersSent = true
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Sends SSE data from various source types.
195
+ * @param {string|Buffer|Object|ReadableStream|AsyncIterable} source - The data source to send
196
+ * @throws {Error} If connection is closed
197
+ * @throws {TypeError} If source type is invalid
198
+ */
138
199
  async send (source) {
139
200
  if (!this._isConnected) {
140
201
  throw new Error('SSE connection is closed')
@@ -149,8 +210,22 @@ class SSEContext {
149
210
 
150
211
  // Handle Readable stream
151
212
  if (source instanceof Readable) {
213
+ this.sendHeaders()
214
+
152
215
  const transform = createSSETransformStream({ serializer: this.serializer })
153
- await pipeline(source, transform, this.reply.raw, { end: false })
216
+ try {
217
+ await pipeline(source, transform, this.reply.raw, { end: false })
218
+ } catch (error) {
219
+ // Distinguish between expected disconnection errors and unexpected errors
220
+ this._isConnected = false
221
+ this.cleanup()
222
+ if (error && (error.code === 'ECONNRESET' || error.code === 'EPIPE')) {
223
+ this.reply.log.info({ err: error }, 'SSE stream ended (client disconnected)')
224
+ } else {
225
+ this.reply.log.error({ err: error }, 'Unexpected error in SSE stream')
226
+ }
227
+ return
228
+ }
154
229
  return
155
230
  }
156
231
 
@@ -167,14 +242,35 @@ class SSEContext {
167
242
  throw new TypeError('Invalid SSE source type')
168
243
  }
169
244
 
245
+ /**
246
+ * Creates a transform stream for SSE formatting.
247
+ * The returned stream automatically sends headers on first write.
248
+ * @returns {Transform} A transform stream that formats data as SSE
249
+ * @throws {Error} If connection is closed
250
+ */
170
251
  stream () {
171
252
  if (!this._isConnected) {
172
253
  throw new Error('SSE connection is closed')
173
254
  }
174
255
 
175
- return createSSETransformStream({ serializer: this.serializer })
256
+ const transform = createSSETransformStream({ serializer: this.serializer })
257
+
258
+ // Wrap the transform to send headers on first write
259
+ const originalWrite = transform._write
260
+ transform._write = (chunk, encoding, callback) => {
261
+ this.sendHeaders()
262
+ originalWrite.call(transform, chunk, encoding, callback)
263
+ }
264
+
265
+ return transform
176
266
  }
177
267
 
268
+ /**
269
+ * Writes data to the response stream with backpressure handling.
270
+ * @param {string|Buffer} data - The data to write
271
+ * @returns {Promise<void>} Resolves when data is written
272
+ * @private
273
+ */
178
274
  writeToStream (data) {
179
275
  return new Promise((resolve, reject) => {
180
276
  if (!this._isConnected) {
@@ -182,6 +278,9 @@ class SSEContext {
182
278
  return
183
279
  }
184
280
 
281
+ // Send headers on first write
282
+ this.sendHeaders()
283
+
185
284
  const canWrite = this.reply.raw.write(data)
186
285
 
187
286
  if (canWrite) {
@@ -195,7 +294,11 @@ class SSEContext {
195
294
 
196
295
  const onError = (err) => {
197
296
  this.reply.raw.off('drain', onDrain)
198
- reject(err)
297
+ // Handle all errors gracefully - client disconnection is normal
298
+ this._isConnected = false
299
+ this.cleanup()
300
+ this.reply.log.info({ err }, 'SSE write ended')
301
+ resolve() // Resolve instead of reject for graceful handling
199
302
  }
200
303
 
201
304
  this.reply.raw.once('drain', onDrain)
@@ -204,9 +307,15 @@ class SSEContext {
204
307
  })
205
308
  }
206
309
 
310
+ /**
311
+ * Starts sending periodic heartbeat messages to keep the connection alive.
312
+ * @param {number} interval - Heartbeat interval in milliseconds
313
+ * @private
314
+ */
207
315
  startHeartbeat (interval) {
208
316
  this.heartbeatTimer = setInterval(() => {
209
317
  if (this._isConnected) {
318
+ this.sendHeaders()
210
319
  this.reply.raw.write(': heartbeat\n\n')
211
320
  } else {
212
321
  this.stopHeartbeat()
@@ -217,6 +326,10 @@ class SSEContext {
217
326
  this.heartbeatTimer.unref()
218
327
  }
219
328
 
329
+ /**
330
+ * Stops the heartbeat timer.
331
+ * @private
332
+ */
220
333
  stopHeartbeat () {
221
334
  if (this.heartbeatTimer) {
222
335
  clearInterval(this.heartbeatTimer)
@@ -224,6 +337,11 @@ class SSEContext {
224
337
  }
225
338
  }
226
339
 
340
+ /**
341
+ * Performs cleanup operations when the connection closes.
342
+ * Stops heartbeat and executes all registered close callbacks.
343
+ * @private
344
+ */
227
345
  cleanup () {
228
346
  this.stopHeartbeat()
229
347
 
@@ -240,12 +358,24 @@ class SSEContext {
240
358
  this.closeCallbacks = []
241
359
  }
242
360
 
361
+ /**
362
+ * Checks if a value is a valid SSE message object.
363
+ * @param {*} value - The value to check
364
+ * @returns {boolean} True if value is an SSE message object
365
+ * @private
366
+ */
243
367
  isSSEMessage (value) {
244
368
  return typeof value === 'object' &&
245
369
  value !== null &&
246
370
  'data' in value
247
371
  }
248
372
 
373
+ /**
374
+ * Checks if a value is an async iterable.
375
+ * @param {*} value - The value to check
376
+ * @returns {boolean} True if value is async iterable
377
+ * @private
378
+ */
249
379
  isAsyncIterable (value) {
250
380
  return value != null &&
251
381
  typeof value[Symbol.asyncIterator] === 'function'
@@ -314,10 +444,8 @@ async function fastifySSE (fastify, opts) {
314
444
  get () { return this[SSE_DECORATOR] }
315
445
  })
316
446
 
317
- // Send 200 OK
318
- reply.raw.writeHead(200)
319
-
320
447
  // Call original handler with SSE-enabled reply
448
+ // Note: Headers will be sent on first SSE send
321
449
  try {
322
450
  await originalHandler.call(this, request, reply)
323
451
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fastify/sse",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Server-Sent Events plugin for Fastify",
5
5
  "main": "index.js",
6
6
  "types": "types/index.d.ts",
@@ -24,12 +24,12 @@
24
24
  "license": "MIT",
25
25
  "repository": {
26
26
  "type": "git",
27
- "url": "https://github.com/fastify/fastify-sse.git"
27
+ "url": "https://github.com/fastify/sse.git"
28
28
  },
29
29
  "bugs": {
30
- "url": "https://github.com/fastify/fastify-sse/issues"
30
+ "url": "https://github.com/fastify/sse/issues"
31
31
  },
32
- "homepage": "https://github.com/fastify/fastify-sse#readme",
32
+ "homepage": "https://github.com/fastify/sse#readme",
33
33
  "peerDependencies": {
34
34
  "fastify": "^5.x"
35
35
  },
@@ -40,11 +40,12 @@
40
40
  "@types/node": "^24.3.0",
41
41
  "eslint": "^9.0.0",
42
42
  "fastify": "^5.0.0",
43
- "neostandard": "^0.11.0",
43
+ "neostandard": "^0.12.2",
44
44
  "tsd": "^0.33.0",
45
- "typescript": "^5.9.2"
45
+ "typescript": "^5.9.2",
46
+ "undici": "^7.15.0"
46
47
  },
47
48
  "engines": {
48
- "node": ">=18.0.0"
49
+ "node": ">=20"
49
50
  }
50
51
  }
@@ -0,0 +1,160 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('node:test')
4
+ const { strict: assert } = require('node:assert')
5
+ const { setTimeout: sleep } = require('node:timers/promises')
6
+ const Fastify = require('fastify')
7
+ const { request } = require('undici')
8
+
9
+ test('handles body.destroy() without uncaught exception', async (t) => {
10
+ const app = Fastify({ logger: false })
11
+
12
+ t.after(async () => {
13
+ await app.close()
14
+ })
15
+
16
+ // Register @fastify/sse plugin
17
+ await app.register(require('../index.js'))
18
+
19
+ // Simple SSE endpoint that sends data and keeps alive
20
+ app.get('/sse', { sse: true }, async (request, reply) => {
21
+ reply.sse.send({ data: 'connected' })
22
+ // Don't keep alive - let it close naturally
23
+ })
24
+
25
+ await app.listen({ port: 0 })
26
+ const baseUrl = `http://localhost:${app.server.address().port}`
27
+
28
+ // Create SSE connection using undici
29
+ const sseResponse = await request(`${baseUrl}/sse`, {
30
+ method: 'GET',
31
+ headers: {
32
+ Accept: 'text/event-stream'
33
+ }
34
+ })
35
+
36
+ assert.strictEqual(sseResponse.statusCode, 200)
37
+ assert.strictEqual(sseResponse.headers['content-type'], 'text/event-stream')
38
+
39
+ // Start consuming the body
40
+ sseResponse.body.on('data', () => {})
41
+
42
+ // Wait for connection to be established
43
+ await sleep(50)
44
+
45
+ // Destroy the body - should not cause uncaught exception
46
+ sseResponse.body.destroy()
47
+
48
+ // Wait to ensure no uncaught exceptions occur
49
+ await sleep(100)
50
+ })
51
+
52
+ test('handles body.destroy() with keepAlive connection', async (t) => {
53
+ const app = Fastify({ logger: false })
54
+
55
+ t.after(async () => {
56
+ await app.close()
57
+ })
58
+
59
+ // Register @fastify/sse plugin
60
+ await app.register(require('../index.js'))
61
+
62
+ // SSE endpoint that keeps connection alive
63
+ app.get('/sse', { sse: true }, async (request, reply) => {
64
+ reply.sse.send({ data: 'connected' })
65
+ reply.sse.keepAlive()
66
+ })
67
+
68
+ await app.listen({ port: 0 })
69
+ const baseUrl = `http://localhost:${app.server.address().port}`
70
+
71
+ // Create SSE connection using undici
72
+ const sseResponse = await request(`${baseUrl}/sse`, {
73
+ method: 'GET',
74
+ headers: {
75
+ Accept: 'text/event-stream'
76
+ }
77
+ })
78
+
79
+ assert.strictEqual(sseResponse.statusCode, 200)
80
+ assert.strictEqual(sseResponse.headers['content-type'], 'text/event-stream')
81
+
82
+ // Start consuming the body
83
+ sseResponse.body.on('data', () => {})
84
+
85
+ // Wait for connection to be established
86
+ await sleep(50)
87
+
88
+ // Destroy the body - should not cause uncaught exception
89
+ sseResponse.body.destroy()
90
+
91
+ // Wait to ensure no uncaught exceptions occur
92
+ await sleep(100)
93
+ })
94
+
95
+ test('handles body.destroy() with streaming data', async (t) => {
96
+ const app = Fastify({ logger: false })
97
+
98
+ t.after(async () => {
99
+ await app.close()
100
+ })
101
+
102
+ // Register @fastify/sse plugin
103
+ await app.register(require('../index.js'))
104
+
105
+ // SSE endpoint that streams data
106
+ app.get('/sse', { sse: true }, async (request, reply) => {
107
+ reply.sse.keepAlive()
108
+
109
+ // Send initial message immediately
110
+ await reply.sse.send({ data: 'connected' })
111
+
112
+ // Stream data periodically
113
+ const interval = setInterval(async () => {
114
+ if (reply.sse.isConnected) {
115
+ try {
116
+ await reply.sse.send({ data: 'ping' })
117
+ } catch (e) {
118
+ // Connection closed
119
+ clearInterval(interval)
120
+ }
121
+ } else {
122
+ clearInterval(interval)
123
+ }
124
+ }, 100)
125
+
126
+ reply.sse.onClose(() => {
127
+ clearInterval(interval)
128
+ })
129
+ })
130
+
131
+ await app.listen({ port: 0 })
132
+ const baseUrl = `http://localhost:${app.server.address().port}`
133
+
134
+ // Create SSE connection using undici
135
+ const sseResponse = await request(`${baseUrl}/sse`, {
136
+ method: 'GET',
137
+ headers: {
138
+ Accept: 'text/event-stream'
139
+ }
140
+ })
141
+
142
+ assert.strictEqual(sseResponse.statusCode, 200)
143
+ assert.strictEqual(sseResponse.headers['content-type'], 'text/event-stream')
144
+
145
+ // Start consuming the body
146
+ let dataReceived = false
147
+ sseResponse.body.on('data', (chunk) => {
148
+ dataReceived = true
149
+ })
150
+
151
+ // Wait for some data to be received
152
+ await sleep(100)
153
+ assert.ok(dataReceived, 'Should have received some data')
154
+
155
+ // Destroy the body while streaming - should not cause uncaught exception
156
+ sseResponse.body.destroy()
157
+
158
+ // Wait to ensure no uncaught exceptions occur
159
+ await sleep(100)
160
+ })
@@ -0,0 +1,126 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('node:test')
4
+ const { strict: assert } = require('node:assert')
5
+ const Fastify = require('fastify')
6
+ const fastifySSE = require('../index.js')
7
+
8
+ test('should allow setting custom headers in SSE responses', async (t) => {
9
+ const fastify = Fastify({ logger: false })
10
+
11
+ t.after(async () => {
12
+ await fastify.close()
13
+ })
14
+
15
+ await fastify.register(fastifySSE)
16
+
17
+ fastify.get('/events', { sse: true }, async (request, reply) => {
18
+ // Set custom headers before sending SSE data
19
+ reply.raw.setHeader('X-Session-ID', '12345')
20
+ reply.raw.setHeader('X-API-Version', '1.0')
21
+ reply.raw.setHeader('X-Custom-Header', 'test-value')
22
+
23
+ await reply.sse.send({ data: 'hello' })
24
+ })
25
+
26
+ await fastify.listen({ port: 0 })
27
+
28
+ const response = await fastify.inject({
29
+ method: 'GET',
30
+ url: '/events',
31
+ headers: {
32
+ accept: 'text/event-stream'
33
+ }
34
+ })
35
+
36
+ assert.strictEqual(response.statusCode, 200)
37
+ assert.strictEqual(response.headers['content-type'], 'text/event-stream')
38
+
39
+ // Check that custom headers are present
40
+ assert.strictEqual(response.headers['x-session-id'], '12345')
41
+ assert.strictEqual(response.headers['x-api-version'], '1.0')
42
+ assert.strictEqual(response.headers['x-custom-header'], 'test-value')
43
+
44
+ const body = response.body
45
+ assert.ok(body.includes('data: "hello"'))
46
+ })
47
+
48
+ test('should allow setting headers via reply.header() method', async (t) => {
49
+ const fastify = Fastify({ logger: false })
50
+
51
+ t.after(async () => {
52
+ await fastify.close()
53
+ })
54
+
55
+ await fastify.register(fastifySSE)
56
+
57
+ fastify.get('/events', { sse: true }, async (request, reply) => {
58
+ // Use Fastify's header method
59
+ reply.header('X-Request-ID', 'req-123')
60
+ reply.header('X-User-ID', 'user-456')
61
+
62
+ await reply.sse.send({ data: 'test' })
63
+ })
64
+
65
+ await fastify.listen({ port: 0 })
66
+
67
+ const response = await fastify.inject({
68
+ method: 'GET',
69
+ url: '/events',
70
+ headers: {
71
+ accept: 'text/event-stream'
72
+ }
73
+ })
74
+
75
+ assert.strictEqual(response.statusCode, 200)
76
+
77
+ // Check that headers set via reply.header() are present
78
+ assert.strictEqual(response.headers['x-request-id'], 'req-123')
79
+ assert.strictEqual(response.headers['x-user-id'], 'user-456')
80
+ })
81
+
82
+ test('should allow setting headers in preHandler hook', async (t) => {
83
+ const fastify = Fastify({ logger: false })
84
+
85
+ t.after(async () => {
86
+ await fastify.close()
87
+ })
88
+
89
+ await fastify.register(fastifySSE)
90
+
91
+ fastify.get('/events', {
92
+ sse: true,
93
+ preHandler: async (request, reply) => {
94
+ // Set headers in preHandler using both methods
95
+ reply.header('X-PreHandler-ID', 'pre-123')
96
+ reply.raw.setHeader('X-PreHandler-Raw', 'raw-456')
97
+ }
98
+ }, async (request, reply) => {
99
+ // Also set headers in handler
100
+ reply.header('X-Handler-ID', 'handler-789')
101
+
102
+ await reply.sse.send({ data: 'prehandler test' })
103
+ })
104
+
105
+ await fastify.listen({ port: 0 })
106
+
107
+ const response = await fastify.inject({
108
+ method: 'GET',
109
+ url: '/events',
110
+ headers: {
111
+ accept: 'text/event-stream'
112
+ }
113
+ })
114
+
115
+ assert.strictEqual(response.statusCode, 200)
116
+
117
+ // Check that headers set in preHandler are present
118
+ assert.strictEqual(response.headers['x-prehandler-id'], 'pre-123')
119
+ assert.strictEqual(response.headers['x-prehandler-raw'], 'raw-456')
120
+
121
+ // Check that headers set in handler are also present
122
+ assert.strictEqual(response.headers['x-handler-id'], 'handler-789')
123
+
124
+ const body = response.body
125
+ assert.ok(body.includes('data: "prehandler test"'))
126
+ })
@@ -1,9 +0,0 @@
1
- {
2
- "permissions": {
3
- "allow": [
4
- "Bash(node:*)"
5
- ],
6
- "deny": [],
7
- "ask": []
8
- }
9
- }