@fastify/sse 0.1.0 → 0.2.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
@@ -105,18 +106,34 @@ class SSEContext {
105
106
  }
106
107
  }
107
108
 
109
+ /**
110
+ * Gets the last event ID from the client's Last-Event-ID header.
111
+ * @returns {string|null} The last event ID or null if not present
112
+ */
108
113
  get lastEventId () {
109
114
  return this._lastEventId
110
115
  }
111
116
 
117
+ /**
118
+ * Checks if the SSE connection is still active.
119
+ * @returns {boolean} True if connected, false otherwise
120
+ */
112
121
  get isConnected () {
113
122
  return this._isConnected
114
123
  }
115
124
 
125
+ /**
126
+ * Marks the connection to be kept alive after the handler completes.
127
+ * Without calling this, the connection will close after the handler returns.
128
+ */
116
129
  keepAlive () {
117
130
  this._keepAlive = true
118
131
  }
119
132
 
133
+ /**
134
+ * Closes the SSE connection and performs cleanup.
135
+ * Safe to call multiple times.
136
+ */
120
137
  close () {
121
138
  if (!this._isConnected) return
122
139
 
@@ -125,16 +142,51 @@ class SSEContext {
125
142
  this.reply.raw.end()
126
143
  }
127
144
 
145
+ /**
146
+ * Registers a callback to be called when the connection closes.
147
+ * @param {Function} callback - Function to call on connection close
148
+ */
128
149
  onClose (callback) {
129
150
  this.closeCallbacks.push(callback)
130
151
  }
131
152
 
153
+ /**
154
+ * Executes a callback with the last event ID for replay functionality.
155
+ * Only calls the callback if a last event ID exists.
156
+ * @param {Function} callback - Async function that receives the last event ID
157
+ */
132
158
  async replay (callback) {
133
159
  if (!this._lastEventId) return
134
160
 
135
161
  await callback(this._lastEventId)
136
162
  }
137
163
 
164
+ /**
165
+ * Sends HTTP headers for the SSE response if not already sent.
166
+ * This method ensures headers set via reply.header() are transferred
167
+ * to the raw response before calling writeHead(200).
168
+ * Called automatically before the first SSE data is sent.
169
+ * @private
170
+ */
171
+ sendHeaders () {
172
+ if (!this._headersSent) {
173
+ // Get any headers set via reply.header() and transfer to raw response
174
+ const replyHeaders = this.reply.getHeaders()
175
+ for (const [name, value] of Object.entries(replyHeaders)) {
176
+ this.reply.raw.setHeader(name, value)
177
+ }
178
+
179
+ this.reply.raw.writeHead(200)
180
+ this._headersSent = true
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Sends SSE data from various source types.
186
+ * @param {string|Buffer|Object|ReadableStream|AsyncIterable} source - The data source to send
187
+ * @throws {Error} If connection is closed
188
+ * @throws {TypeError} If source type is invalid
189
+ */
138
190
  async send (source) {
139
191
  if (!this._isConnected) {
140
192
  throw new Error('SSE connection is closed')
@@ -149,6 +201,8 @@ class SSEContext {
149
201
 
150
202
  // Handle Readable stream
151
203
  if (source instanceof Readable) {
204
+ this.sendHeaders()
205
+
152
206
  const transform = createSSETransformStream({ serializer: this.serializer })
153
207
  await pipeline(source, transform, this.reply.raw, { end: false })
154
208
  return
@@ -167,14 +221,35 @@ class SSEContext {
167
221
  throw new TypeError('Invalid SSE source type')
168
222
  }
169
223
 
224
+ /**
225
+ * Creates a transform stream for SSE formatting.
226
+ * The returned stream automatically sends headers on first write.
227
+ * @returns {Transform} A transform stream that formats data as SSE
228
+ * @throws {Error} If connection is closed
229
+ */
170
230
  stream () {
171
231
  if (!this._isConnected) {
172
232
  throw new Error('SSE connection is closed')
173
233
  }
174
234
 
175
- return createSSETransformStream({ serializer: this.serializer })
235
+ const transform = createSSETransformStream({ serializer: this.serializer })
236
+
237
+ // Wrap the transform to send headers on first write
238
+ const originalWrite = transform._write
239
+ transform._write = (chunk, encoding, callback) => {
240
+ this.sendHeaders()
241
+ originalWrite.call(transform, chunk, encoding, callback)
242
+ }
243
+
244
+ return transform
176
245
  }
177
246
 
247
+ /**
248
+ * Writes data to the response stream with backpressure handling.
249
+ * @param {string|Buffer} data - The data to write
250
+ * @returns {Promise<void>} Resolves when data is written
251
+ * @private
252
+ */
178
253
  writeToStream (data) {
179
254
  return new Promise((resolve, reject) => {
180
255
  if (!this._isConnected) {
@@ -182,6 +257,9 @@ class SSEContext {
182
257
  return
183
258
  }
184
259
 
260
+ // Send headers on first write
261
+ this.sendHeaders()
262
+
185
263
  const canWrite = this.reply.raw.write(data)
186
264
 
187
265
  if (canWrite) {
@@ -204,9 +282,15 @@ class SSEContext {
204
282
  })
205
283
  }
206
284
 
285
+ /**
286
+ * Starts sending periodic heartbeat messages to keep the connection alive.
287
+ * @param {number} interval - Heartbeat interval in milliseconds
288
+ * @private
289
+ */
207
290
  startHeartbeat (interval) {
208
291
  this.heartbeatTimer = setInterval(() => {
209
292
  if (this._isConnected) {
293
+ this.sendHeaders()
210
294
  this.reply.raw.write(': heartbeat\n\n')
211
295
  } else {
212
296
  this.stopHeartbeat()
@@ -217,6 +301,10 @@ class SSEContext {
217
301
  this.heartbeatTimer.unref()
218
302
  }
219
303
 
304
+ /**
305
+ * Stops the heartbeat timer.
306
+ * @private
307
+ */
220
308
  stopHeartbeat () {
221
309
  if (this.heartbeatTimer) {
222
310
  clearInterval(this.heartbeatTimer)
@@ -224,6 +312,11 @@ class SSEContext {
224
312
  }
225
313
  }
226
314
 
315
+ /**
316
+ * Performs cleanup operations when the connection closes.
317
+ * Stops heartbeat and executes all registered close callbacks.
318
+ * @private
319
+ */
227
320
  cleanup () {
228
321
  this.stopHeartbeat()
229
322
 
@@ -240,12 +333,24 @@ class SSEContext {
240
333
  this.closeCallbacks = []
241
334
  }
242
335
 
336
+ /**
337
+ * Checks if a value is a valid SSE message object.
338
+ * @param {*} value - The value to check
339
+ * @returns {boolean} True if value is an SSE message object
340
+ * @private
341
+ */
243
342
  isSSEMessage (value) {
244
343
  return typeof value === 'object' &&
245
344
  value !== null &&
246
345
  'data' in value
247
346
  }
248
347
 
348
+ /**
349
+ * Checks if a value is an async iterable.
350
+ * @param {*} value - The value to check
351
+ * @returns {boolean} True if value is async iterable
352
+ * @private
353
+ */
249
354
  isAsyncIterable (value) {
250
355
  return value != null &&
251
356
  typeof value[Symbol.asyncIterator] === 'function'
@@ -314,10 +419,8 @@ async function fastifySSE (fastify, opts) {
314
419
  get () { return this[SSE_DECORATOR] }
315
420
  })
316
421
 
317
- // Send 200 OK
318
- reply.raw.writeHead(200)
319
-
320
422
  // Call original handler with SSE-enabled reply
423
+ // Note: Headers will be sent on first SSE send
321
424
  try {
322
425
  await originalHandler.call(this, request, reply)
323
426
  } 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.2.0",
4
4
  "description": "Server-Sent Events plugin for Fastify",
5
5
  "main": "index.js",
6
6
  "types": "types/index.d.ts",
@@ -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
+ })