@fastify/sse 0.4.0 → 0.5.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.
@@ -293,3 +293,267 @@ test('reply.sse.stream() for pipeline operations', async (t) => {
293
293
  assert.ok(body.includes('id: 3'))
294
294
  assert.ok(body.includes('data: "third"'))
295
295
  })
296
+
297
+ // -----------------------------------------------------------------------
298
+ // sse: 'only' (SSE-only routes)
299
+ // -----------------------------------------------------------------------
300
+
301
+ test("sse: 'only' admits SSE for */*", async (t) => {
302
+ const fastify = Fastify({ logger: false })
303
+ t.after(async () => { await fastify.close() })
304
+ await fastify.register(fastifySSE)
305
+
306
+ fastify.get('/events', { sse: 'only' }, async (request, reply) => {
307
+ await reply.sse.send({ data: 'hello' })
308
+ })
309
+
310
+ const response = await fastify.inject({
311
+ method: 'GET',
312
+ url: '/events',
313
+ headers: { accept: '*/*' }
314
+ })
315
+ assert.strictEqual(response.statusCode, 200)
316
+ assert.strictEqual(response.headers['content-type'], 'text/event-stream')
317
+ assert.ok(response.body.includes('data: "hello"'))
318
+ })
319
+
320
+ test("sse: 'only' admits SSE for missing Accept", async (t) => {
321
+ const fastify = Fastify({ logger: false })
322
+ t.after(async () => { await fastify.close() })
323
+ await fastify.register(fastifySSE)
324
+
325
+ fastify.get('/events', { sse: 'only' }, async (request, reply) => {
326
+ await reply.sse.send({ data: 'hello' })
327
+ })
328
+
329
+ const response = await fastify.inject({ method: 'GET', url: '/events' })
330
+ assert.strictEqual(response.statusCode, 200)
331
+ assert.strictEqual(response.headers['content-type'], 'text/event-stream')
332
+ assert.ok(response.body.includes('data: "hello"'))
333
+ })
334
+
335
+ test("sse: 'only' admits SSE for text/*", async (t) => {
336
+ const fastify = Fastify({ logger: false })
337
+ t.after(async () => { await fastify.close() })
338
+ await fastify.register(fastifySSE)
339
+
340
+ fastify.get('/events', { sse: 'only' }, async (request, reply) => {
341
+ await reply.sse.send({ data: 'hello' })
342
+ })
343
+
344
+ const response = await fastify.inject({
345
+ method: 'GET',
346
+ url: '/events',
347
+ headers: { accept: 'text/*' }
348
+ })
349
+ assert.strictEqual(response.headers['content-type'], 'text/event-stream')
350
+ })
351
+
352
+ test("sse: 'only' returns 406 when client explicitly refuses SSE", async (t) => {
353
+ const fastify = Fastify({ logger: false })
354
+ t.after(async () => { await fastify.close() })
355
+ await fastify.register(fastifySSE)
356
+
357
+ fastify.get('/events', { sse: 'only' }, async (request, reply) => {
358
+ await reply.sse.send({ data: 'hello' })
359
+ })
360
+
361
+ const response = await fastify.inject({
362
+ method: 'GET',
363
+ url: '/events',
364
+ headers: { accept: 'application/json' }
365
+ })
366
+ assert.strictEqual(response.statusCode, 406)
367
+ assert.strictEqual(response.headers['content-type'], 'application/json; charset=utf-8')
368
+ const body = JSON.parse(response.body)
369
+ assert.strictEqual(body.statusCode, 406)
370
+ assert.strictEqual(body.error, 'Not Acceptable')
371
+ assert.match(body.message, /text\/event-stream/)
372
+ })
373
+
374
+ test("sse: 'only' returns 406 when client sends text/event-stream;q=0", async (t) => {
375
+ const fastify = Fastify({ logger: false })
376
+ t.after(async () => { await fastify.close() })
377
+ await fastify.register(fastifySSE)
378
+
379
+ fastify.get('/events', { sse: 'only' }, async (request, reply) => {
380
+ await reply.sse.send({ data: 'hello' })
381
+ })
382
+
383
+ const response = await fastify.inject({
384
+ method: 'GET',
385
+ url: '/events',
386
+ headers: { accept: '*/*, text/event-stream;q=0' }
387
+ })
388
+ assert.strictEqual(response.statusCode, 406)
389
+ })
390
+
391
+ test("sse: { kind: 'only', heartbeat: false } object form is supported", async (t) => {
392
+ const fastify = Fastify({ logger: false })
393
+ t.after(async () => { await fastify.close() })
394
+ await fastify.register(fastifySSE)
395
+
396
+ fastify.get('/events', {
397
+ sse: { kind: 'only', heartbeat: false }
398
+ }, async (request, reply) => {
399
+ await reply.sse.send({ data: 'hello' })
400
+ })
401
+
402
+ const wildcard = await fastify.inject({
403
+ method: 'GET',
404
+ url: '/events',
405
+ headers: { accept: '*/*' }
406
+ })
407
+ assert.strictEqual(wildcard.headers['content-type'], 'text/event-stream')
408
+
409
+ const refused = await fastify.inject({
410
+ method: 'GET',
411
+ url: '/events',
412
+ headers: { accept: 'application/json' }
413
+ })
414
+ assert.strictEqual(refused.statusCode, 406)
415
+ })
416
+
417
+ // -----------------------------------------------------------------------
418
+ // sse: 'dual' (explicit dual-mode routes)
419
+ // -----------------------------------------------------------------------
420
+
421
+ test("sse: 'dual' routes only explicit text/event-stream to SSE", async (t) => {
422
+ const fastify = Fastify({ logger: false })
423
+ t.after(async () => { await fastify.close() })
424
+ await fastify.register(fastifySSE)
425
+
426
+ fastify.get('/data', { sse: 'dual' }, async (request, reply) => {
427
+ if (reply.sse) {
428
+ await reply.sse.send({ data: 'streamed' })
429
+ } else {
430
+ return { message: 'json' }
431
+ }
432
+ })
433
+
434
+ // */* → falls through to JSON
435
+ const wildcard = await fastify.inject({
436
+ method: 'GET',
437
+ url: '/data',
438
+ headers: { accept: '*/*' }
439
+ })
440
+ assert.strictEqual(wildcard.headers['content-type'], 'application/json; charset=utf-8')
441
+ assert.deepStrictEqual(JSON.parse(wildcard.body), { message: 'json' })
442
+
443
+ // missing → JSON
444
+ const missing = await fastify.inject({ method: 'GET', url: '/data' })
445
+ assert.deepStrictEqual(JSON.parse(missing.body), { message: 'json' })
446
+
447
+ // application/json → JSON
448
+ const jsonResponse = await fastify.inject({
449
+ method: 'GET',
450
+ url: '/data',
451
+ headers: { accept: 'application/json' }
452
+ })
453
+ assert.deepStrictEqual(JSON.parse(jsonResponse.body), { message: 'json' })
454
+
455
+ // text/event-stream → SSE
456
+ const explicit = await fastify.inject({
457
+ method: 'GET',
458
+ url: '/data',
459
+ headers: { accept: 'text/event-stream' }
460
+ })
461
+ assert.strictEqual(explicit.headers['content-type'], 'text/event-stream')
462
+ assert.ok(explicit.body.includes('data: "streamed"'))
463
+ })
464
+
465
+ // -----------------------------------------------------------------------
466
+ // sse: true (legacy back-compat + explanatory error on misuse)
467
+ // -----------------------------------------------------------------------
468
+
469
+ test("sse: true behaves like 'dual' for routing (back-compat)", async (t) => {
470
+ const fastify = Fastify({ logger: false })
471
+ t.after(async () => { await fastify.close() })
472
+ await fastify.register(fastifySSE)
473
+
474
+ fastify.get('/data', { sse: true }, async (request, reply) => {
475
+ const acceptHeader = request.headers.accept || ''
476
+ if (acceptHeader.includes('text/event-stream')) {
477
+ await reply.sse.send({ data: 'streamed' })
478
+ } else {
479
+ return { message: 'json' }
480
+ }
481
+ })
482
+
483
+ // */* → falls through (strict gate); handler returns JSON
484
+ const wildcard = await fastify.inject({
485
+ method: 'GET',
486
+ url: '/data',
487
+ headers: { accept: '*/*' }
488
+ })
489
+ assert.deepStrictEqual(JSON.parse(wildcard.body), { message: 'json' })
490
+
491
+ // text/event-stream → SSE
492
+ const explicit = await fastify.inject({
493
+ method: 'GET',
494
+ url: '/data',
495
+ headers: { accept: 'text/event-stream' }
496
+ })
497
+ assert.strictEqual(explicit.headers['content-type'], 'text/event-stream')
498
+ })
499
+
500
+ test('sse: true with SSE-only handler emits an explanatory error on misuse', async (t) => {
501
+ const fastify = Fastify({ logger: false })
502
+ t.after(async () => { await fastify.close() })
503
+ await fastify.register(fastifySSE)
504
+
505
+ // Handler is SSE-only — calls reply.sse.send unconditionally — but
506
+ // registered with the legacy `sse: true` flag. When a wildcard Accept
507
+ // arrives, the strict gate falls through, reply.sse is undefined, and the
508
+ // handler trips the TypeError. The plugin should rethrow with guidance to
509
+ // switch to `sse: 'only'`.
510
+ fastify.get('/events', { sse: true }, async (request, reply) => {
511
+ await reply.sse.send({ data: 'hello' })
512
+ })
513
+
514
+ const response = await fastify.inject({
515
+ method: 'GET',
516
+ url: '/events',
517
+ headers: { accept: '*/*' }
518
+ })
519
+
520
+ // The rethrown error reaches Fastify's default error handler.
521
+ assert.strictEqual(response.statusCode, 500)
522
+ assert.match(response.body, /sse: 'only'/)
523
+ })
524
+
525
+ test('sse: true with object form (no kind) is treated as legacy', async (t) => {
526
+ const fastify = Fastify({ logger: false })
527
+ t.after(async () => { await fastify.close() })
528
+ await fastify.register(fastifySSE)
529
+
530
+ // No `kind` field — back-compat with existing `{ heartbeat, serializer }` users.
531
+ fastify.get('/events', {
532
+ sse: { heartbeat: false }
533
+ }, async (request, reply) => {
534
+ const acceptHeader = request.headers.accept || ''
535
+ if (acceptHeader.includes('text/event-stream')) {
536
+ await reply.sse.send({ data: 'streamed' })
537
+ } else {
538
+ return { message: 'json' }
539
+ }
540
+ })
541
+
542
+ const wildcard = await fastify.inject({
543
+ method: 'GET',
544
+ url: '/events',
545
+ headers: { accept: '*/*' }
546
+ })
547
+ assert.deepStrictEqual(JSON.parse(wildcard.body), { message: 'json' })
548
+ })
549
+
550
+ test('unknown sse kind throws at registration', async (t) => {
551
+ const fastify = Fastify({ logger: false })
552
+ t.after(async () => { await fastify.close() })
553
+ await fastify.register(fastifySSE)
554
+
555
+ assert.throws(
556
+ () => fastify.get('/events', { sse: { kind: 'maybe' } }, async () => {}),
557
+ /unknown sse kind 'maybe'/
558
+ )
559
+ })
@@ -0,0 +1,50 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('node:test')
4
+ const { strict: assert } = require('node:assert')
5
+ const Fastify = require('fastify')
6
+
7
+ async function runTest (SSE, t) {
8
+ const fastify = Fastify({ logger: false })
9
+
10
+ t.after(async () => {
11
+ await fastify.close()
12
+ })
13
+
14
+ await fastify.register(SSE)
15
+ fastify.get('/events', { sse: true }, async (request, reply) => {
16
+ await reply.sse.send({ data: 'hello world' })
17
+ })
18
+
19
+ const response = await fastify.inject({
20
+ method: 'GET',
21
+ url: '/events',
22
+ headers: {
23
+ accept: 'text/event-stream'
24
+ }
25
+ })
26
+
27
+ assert.strictEqual(response.statusCode, 200)
28
+ assert.strictEqual(response.headers['content-type'], 'text/event-stream')
29
+ assert.strictEqual(response.headers['cache-control'], 'no-cache')
30
+ assert.strictEqual(response.headers.connection, 'keep-alive')
31
+
32
+ const { body: responseBody } = response
33
+ assert.ok(responseBody.includes('data: "hello world"'))
34
+ assert.ok(responseBody.endsWith('\n\n'))
35
+ }
36
+
37
+ test('module import', async (t) => {
38
+ const fastifySSE = require('../index.js')
39
+ await runTest(fastifySSE, t)
40
+ })
41
+
42
+ test('default import', async (t) => {
43
+ const { default: fastifySSE } = require('../index.js')
44
+ await runTest(fastifySSE, t)
45
+ })
46
+
47
+ test('named import', async (t) => {
48
+ const { fastifySSE } = require('../index.js')
49
+ await runTest(fastifySSE, t)
50
+ })
@@ -0,0 +1,205 @@
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
+ // `sse: 'manual'` attaches reply.sse without Accept-header negotiation and
9
+ // lets the handler decide at runtime whether to stream. This mirrors the way
10
+ // OpenAI-style / LLM APIs signal streaming through the request body rather
11
+ // than the Accept header.
12
+
13
+ test('manual mode streams when the handler chooses to (no Accept header)', async (t) => {
14
+ const fastify = Fastify({ logger: false })
15
+ t.after(() => fastify.close())
16
+
17
+ await fastify.register(fastifySSE)
18
+
19
+ fastify.post('/v1/chat', { sse: 'manual' }, async (request, reply) => {
20
+ if (request.body.stream) {
21
+ await reply.sse.send({ data: 'chunk-1' })
22
+ await reply.sse.send({ data: 'chunk-2' })
23
+ return
24
+ }
25
+ return { content: 'full response' }
26
+ })
27
+
28
+ const streamed = await fastify.inject({
29
+ method: 'POST',
30
+ url: '/v1/chat',
31
+ payload: { stream: true }
32
+ })
33
+
34
+ assert.strictEqual(streamed.statusCode, 200)
35
+ assert.strictEqual(streamed.headers['content-type'], 'text/event-stream')
36
+ assert.ok(streamed.body.includes('data: "chunk-1"'))
37
+ assert.ok(streamed.body.includes('data: "chunk-2"'))
38
+ })
39
+
40
+ test('manual mode falls back to a normal JSON response without streaming', async (t) => {
41
+ const fastify = Fastify({ logger: false })
42
+ t.after(() => fastify.close())
43
+
44
+ await fastify.register(fastifySSE)
45
+
46
+ fastify.post('/v1/chat', { sse: 'manual' }, async (request, reply) => {
47
+ if (request.body.stream) {
48
+ await reply.sse.send({ data: 'chunk' })
49
+ return
50
+ }
51
+ return { content: 'full response' }
52
+ })
53
+
54
+ const json = await fastify.inject({
55
+ method: 'POST',
56
+ url: '/v1/chat',
57
+ payload: { stream: false }
58
+ })
59
+
60
+ assert.strictEqual(json.statusCode, 200)
61
+ assert.match(json.headers['content-type'], /application\/json/)
62
+ assert.notStrictEqual(json.headers['content-type'], 'text/event-stream')
63
+ assert.deepStrictEqual(json.json(), { content: 'full response' })
64
+ })
65
+
66
+ test('manual mode streams regardless of an Accept header that refuses SSE', async (t) => {
67
+ const fastify = Fastify({ logger: false })
68
+ t.after(() => fastify.close())
69
+
70
+ await fastify.register(fastifySSE)
71
+
72
+ fastify.get('/events', { sse: 'manual' }, async (request, reply) => {
73
+ await reply.sse.send({ data: 'hello' })
74
+ })
75
+
76
+ // Accept: application/json would 406 on an `only` route and skip SSE on a
77
+ // `dual` route; `manual` ignores it entirely.
78
+ const response = await fastify.inject({
79
+ method: 'GET',
80
+ url: '/events',
81
+ headers: { accept: 'application/json' }
82
+ })
83
+
84
+ assert.strictEqual(response.statusCode, 200)
85
+ assert.strictEqual(response.headers['content-type'], 'text/event-stream')
86
+ assert.ok(response.body.includes('data: "hello"'))
87
+ })
88
+
89
+ test('manual mode closes the stream after the handler resolves', async (t) => {
90
+ const fastify = Fastify({ logger: false })
91
+ t.after(() => fastify.close())
92
+
93
+ await fastify.register(fastifySSE)
94
+
95
+ let closed = false
96
+ fastify.get('/events', { sse: 'manual' }, async (request, reply) => {
97
+ reply.sse.onClose(() => { closed = true })
98
+ await reply.sse.send({ data: 'one' })
99
+ })
100
+
101
+ const response = await fastify.inject({
102
+ method: 'GET',
103
+ url: '/events'
104
+ })
105
+
106
+ assert.strictEqual(response.statusCode, 200)
107
+ assert.ok(response.body.includes('data: "one"'))
108
+ // inject resolves only once the response stream has ended.
109
+ assert.strictEqual(closed, true)
110
+ })
111
+
112
+ test('manual mode closes the stream when the handler throws', async (t) => {
113
+ const fastify = Fastify({ logger: false })
114
+ t.after(() => fastify.close())
115
+
116
+ await fastify.register(fastifySSE)
117
+
118
+ let closed = false
119
+ fastify.get('/events', { sse: 'manual' }, async (request, reply) => {
120
+ reply.sse.onClose(() => { closed = true })
121
+ await reply.sse.send({ data: 'before error' })
122
+ throw new Error('boom')
123
+ })
124
+
125
+ const response = await fastify.inject({
126
+ method: 'GET',
127
+ url: '/events'
128
+ })
129
+
130
+ // Headers were already committed as SSE before the throw, so the partial
131
+ // stream is flushed and the connection is closed during cleanup.
132
+ assert.ok(response.body.includes('data: "before error"'))
133
+ assert.strictEqual(closed, true)
134
+ })
135
+
136
+ test('manual mode respects keepAlive() (no auto-close after handler)', async (t) => {
137
+ const fastify = Fastify({ logger: false })
138
+ t.after(() => fastify.close())
139
+
140
+ await fastify.register(fastifySSE)
141
+
142
+ fastify.get('/events', { sse: 'manual' }, async (request, reply) => {
143
+ reply.sse.keepAlive()
144
+ await reply.sse.send({ data: 'first' })
145
+
146
+ setTimeout(async () => {
147
+ await reply.sse.send({ data: 'second' })
148
+ reply.sse.close()
149
+ }, 30)
150
+ })
151
+
152
+ const response = await fastify.inject({
153
+ method: 'GET',
154
+ url: '/events'
155
+ })
156
+
157
+ assert.strictEqual(response.statusCode, 200)
158
+ assert.ok(response.body.includes('data: "first"'))
159
+ assert.ok(response.body.includes('data: "second"'))
160
+ })
161
+
162
+ test("manual mode via object form ({ kind: 'manual' })", async (t) => {
163
+ const fastify = Fastify({ logger: false })
164
+ t.after(() => fastify.close())
165
+
166
+ await fastify.register(fastifySSE)
167
+
168
+ fastify.get('/events', {
169
+ sse: { kind: 'manual', serializer: (data) => `CUSTOM:${JSON.stringify(data)}` }
170
+ }, async (request, reply) => {
171
+ await reply.sse.send({ data: 'test' })
172
+ })
173
+
174
+ const response = await fastify.inject({
175
+ method: 'GET',
176
+ url: '/events'
177
+ })
178
+
179
+ assert.strictEqual(response.statusCode, 200)
180
+ assert.ok(response.body.includes('CUSTOM:"test"'))
181
+ })
182
+
183
+ test('a non-SSE fallback response is not corrupted by a heartbeat', async (t) => {
184
+ const fastify = Fastify({ logger: false })
185
+ t.after(() => fastify.close())
186
+
187
+ // A 1ms heartbeat would fire during the handler if it were started eagerly.
188
+ await fastify.register(fastifySSE, { heartbeatInterval: 1 })
189
+
190
+ fastify.post('/v1/chat', { sse: 'manual' }, async (request, reply) => {
191
+ // Give the (deferred) heartbeat timer a chance to fire before returning.
192
+ await new Promise((resolve) => setTimeout(resolve, 20))
193
+ return { content: 'full response' }
194
+ })
195
+
196
+ const response = await fastify.inject({
197
+ method: 'POST',
198
+ url: '/v1/chat',
199
+ payload: { stream: false }
200
+ })
201
+
202
+ assert.strictEqual(response.statusCode, 200)
203
+ assert.match(response.headers['content-type'], /application\/json/)
204
+ assert.deepStrictEqual(response.json(), { content: 'full response' })
205
+ })
package/types/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Readable } from 'stream'
2
1
  import { FastifyPluginAsync } from 'fastify'
2
+ import { Readable } from 'stream'
3
3
 
4
4
  declare module 'fastify' {
5
5
  interface FastifyReply {
@@ -7,13 +7,44 @@ declare module 'fastify' {
7
7
  }
8
8
 
9
9
  interface RouteShorthandOptions {
10
- sse?: boolean | {
11
- heartbeat?: boolean
12
- serializer?: (data: any) => string
13
- }
10
+ sse?: SSERouteOptions
14
11
  }
15
12
  }
16
13
 
14
+ /**
15
+ * Declares how a route handles the SSE/non-SSE split.
16
+ *
17
+ * - `'only'` — SSE-only. Lenient gate: any spec-compliant Accept admits
18
+ * SSE. Clients that explicitly refuse SSE receive 406 Not Acceptable.
19
+ * - `'dual'` — Route serves both SSE and non-SSE on the same handler.
20
+ * Strict gate: only an explicit `text/event-stream` token admits SSE;
21
+ * the handler must branch on `reply.sse` to serve other clients.
22
+ * - `'manual'` — No Accept negotiation. `reply.sse` is always attached and
23
+ * the handler decides at runtime whether to stream (by calling
24
+ * `reply.sse.*`) or to return a normal response. Useful for streaming
25
+ * APIs that signal streaming via the request body (e.g. OpenAI-style
26
+ * `{ stream: true }`) rather than the Accept header. The connection is
27
+ * closed automatically when the handler resolves or throws.
28
+ */
29
+ export type SSERouteKind = 'only' | 'dual' | 'manual'
30
+
31
+ /**
32
+ * Per-route SSE options.
33
+ *
34
+ * Accepted values:
35
+ * - `true` — Back-compat. Routes like `'dual'` for gate behavior; on the
36
+ * fallback path the plugin rethrows with a message naming `'only'` as
37
+ * the fix if the handler tries to use `reply.sse`.
38
+ * - `'only'` / `'dual'` / `'manual'` — Shorthand for the matching kind.
39
+ * - Object form — Same kinds via `kind`, plus per-route option overrides.
40
+ * `kind` omitted = back-compat behavior, equivalent to `sse: true`.
41
+ */
42
+ export type SSERouteOptions = boolean | SSERouteKind | {
43
+ kind?: SSERouteKind
44
+ heartbeat?: boolean
45
+ serializer?: (data: any) => string
46
+ }
47
+
17
48
  export interface SSEPluginOptions {
18
49
  /**
19
50
  * Interval in milliseconds for sending heartbeat comments
@@ -51,10 +82,10 @@ export interface SSEMessage {
51
82
  retry?: number
52
83
  }
53
84
 
54
- export type SSESource =
55
- | SSEMessage
56
- | string
57
- | Buffer
85
+ export type SSESource =
86
+ | SSEMessage
87
+ | string
88
+ | Buffer
58
89
  | Readable
59
90
  | AsyncIterable<SSEMessage | string | Buffer>
60
91
 
@@ -114,6 +145,6 @@ export interface SSEReplyInterface {
114
145
  sendHeaders(): void
115
146
  }
116
147
 
117
- declare const fastifySSE: FastifyPluginAsync<SSEPluginOptions>
148
+ export declare const fastifySSE: FastifyPluginAsync<SSEPluginOptions>
118
149
 
119
- export default fastifySSE
150
+ export default fastifySSE