@fastify/sse 0.1.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.
@@ -0,0 +1,197 @@
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('Last-Event-ID header parsing', 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
+ assert.strictEqual(reply.sse.lastEventId, '42')
19
+ await reply.sse.send({ id: '43', data: 'next event' })
20
+ })
21
+
22
+ await fastify.listen({ port: 0 })
23
+
24
+ const response = await fastify.inject({
25
+ method: 'GET',
26
+ url: '/events',
27
+ headers: {
28
+ accept: 'text/event-stream',
29
+ 'last-event-id': '42'
30
+ }
31
+ })
32
+
33
+ assert.strictEqual(response.statusCode, 200)
34
+ const body = response.body
35
+ assert.ok(body.includes('id: 43'))
36
+ assert.ok(body.includes('data: "next event"'))
37
+ })
38
+
39
+ test('replay functionality', async (t) => {
40
+ const fastify = Fastify({ logger: false })
41
+
42
+ t.after(async () => {
43
+ await fastify.close()
44
+ })
45
+
46
+ await fastify.register(fastifySSE)
47
+
48
+ // Mock event store
49
+ const eventStore = new Map([
50
+ ['1', { id: '1', data: 'first' }],
51
+ ['2', { id: '2', data: 'second' }],
52
+ ['3', { id: '3', data: 'third' }]
53
+ ])
54
+
55
+ fastify.get('/events', { sse: true }, async (request, reply) => {
56
+ // Handle replay if lastEventId is present
57
+ await reply.sse.replay(async (lastEventId) => {
58
+ const lastId = parseInt(lastEventId)
59
+ for (const [id, event] of eventStore) {
60
+ if (parseInt(id) > lastId) {
61
+ await reply.sse.send(event)
62
+ }
63
+ }
64
+ })
65
+
66
+ // Send new event
67
+ await reply.sse.send({ id: '4', data: 'latest' })
68
+ })
69
+
70
+ await fastify.listen({ port: 0 })
71
+
72
+ const response = await fastify.inject({
73
+ method: 'GET',
74
+ url: '/events',
75
+ headers: {
76
+ accept: 'text/event-stream',
77
+ 'last-event-id': '1'
78
+ }
79
+ })
80
+
81
+ const body = response.body
82
+ // Should replay events 2 and 3, then send event 4
83
+ assert.ok(body.includes('id: 2'))
84
+ assert.ok(body.includes('data: "second"'))
85
+ assert.ok(body.includes('id: 3'))
86
+ assert.ok(body.includes('data: "third"'))
87
+ assert.ok(body.includes('id: 4'))
88
+ assert.ok(body.includes('data: "latest"'))
89
+ })
90
+
91
+ test('connection state during handler execution', async (t) => {
92
+ const fastify = Fastify({ logger: false })
93
+
94
+ t.after(async () => {
95
+ await fastify.close()
96
+ })
97
+
98
+ await fastify.register(fastifySSE)
99
+
100
+ let connectionStateInHandler = false
101
+
102
+ fastify.get('/events', { sse: true }, async (request, reply) => {
103
+ // Check connection state during handler execution
104
+ connectionStateInHandler = reply.sse.isConnected
105
+ await reply.sse.send({ data: 'connected' })
106
+ })
107
+
108
+ await fastify.listen({ port: 0 })
109
+
110
+ const response = await fastify.inject({
111
+ method: 'GET',
112
+ url: '/events',
113
+ headers: {
114
+ accept: 'text/event-stream'
115
+ }
116
+ })
117
+
118
+ assert.strictEqual(response.statusCode, 200)
119
+
120
+ // Connection should have been active during handler execution
121
+ assert.strictEqual(connectionStateInHandler, true)
122
+ })
123
+
124
+ test('SSE interface methods exist', async (t) => {
125
+ const fastify = Fastify({ logger: false })
126
+
127
+ t.after(async () => {
128
+ await fastify.close()
129
+ })
130
+
131
+ await fastify.register(fastifySSE)
132
+
133
+ let sseInterface
134
+
135
+ fastify.get('/events', { sse: true }, async (request, reply) => {
136
+ sseInterface = reply.sse
137
+
138
+ // Test interface methods exist
139
+ assert.strictEqual(typeof reply.sse.keepAlive, 'function')
140
+ assert.strictEqual(typeof reply.sse.close, 'function')
141
+ assert.strictEqual(typeof reply.sse.replay, 'function')
142
+ assert.strictEqual(typeof reply.sse.onClose, 'function')
143
+ assert.strictEqual(typeof reply.sse.isConnected, 'boolean')
144
+
145
+ await reply.sse.send({ data: 'test' })
146
+ })
147
+
148
+ await fastify.listen({ port: 0 })
149
+
150
+ const response = await fastify.inject({
151
+ method: 'GET',
152
+ url: '/events',
153
+ headers: {
154
+ accept: 'text/event-stream'
155
+ }
156
+ })
157
+
158
+ assert.strictEqual(response.statusCode, 200)
159
+ assert.ok(sseInterface)
160
+ })
161
+
162
+ test('error handling in async iterator', async (t) => {
163
+ const fastify = Fastify({ logger: false })
164
+
165
+ t.after(async () => {
166
+ await fastify.close()
167
+ })
168
+
169
+ await fastify.register(fastifySSE)
170
+
171
+ fastify.get('/error-stream', { sse: true }, async (request, reply) => {
172
+ async function * errorGenerator () {
173
+ yield { id: '1', data: 'before error' }
174
+ throw new Error('Stream error')
175
+ }
176
+
177
+ try {
178
+ await reply.sse.send(errorGenerator())
179
+ } catch (error) {
180
+ await reply.sse.send({ data: 'error handled' })
181
+ }
182
+ })
183
+
184
+ await fastify.listen({ port: 0 })
185
+
186
+ const response = await fastify.inject({
187
+ method: 'GET',
188
+ url: '/error-stream',
189
+ headers: {
190
+ accept: 'text/event-stream'
191
+ }
192
+ })
193
+
194
+ const body = response.body
195
+ assert.ok(body.includes('data: "before error"'))
196
+ assert.ok(body.includes('data: "error handled"'))
197
+ })
@@ -0,0 +1,192 @@
1
+ import { expectType, expectError, expectAssignable } from 'tsd'
2
+ import fastify, { FastifyInstance, FastifyReply, RouteShorthandOptions } from 'fastify'
3
+ import fastifySSE, { SSEPluginOptions, SSEMessage, SSESource, SSEReplyInterface } from '..'
4
+ import { Readable } from 'stream'
5
+
6
+ // Test plugin registration
7
+ const app: FastifyInstance = fastify()
8
+
9
+ // Test plugin options - app.register returns the app instance
10
+ expectAssignable<FastifyInstance>(app.register(fastifySSE))
11
+ expectAssignable<FastifyInstance>(app.register(fastifySSE, {}))
12
+ expectAssignable<FastifyInstance>(app.register(fastifySSE, {
13
+ heartbeatInterval: 10000
14
+ }))
15
+ expectAssignable<FastifyInstance>(app.register(fastifySSE, {
16
+ serializer: (data: any) => JSON.stringify(data)
17
+ }))
18
+ expectAssignable<FastifyInstance>(app.register(fastifySSE, {
19
+ heartbeatInterval: 0,
20
+ serializer: (data: any) => String(data)
21
+ }))
22
+
23
+ // Test invalid plugin options
24
+ expectError(app.register(fastifySSE, {
25
+ heartbeatInterval: 'invalid'
26
+ }))
27
+ expectError(app.register(fastifySSE, {
28
+ serializer: 123
29
+ }))
30
+ expectError(app.register(fastifySSE, {
31
+ unknownOption: true
32
+ }))
33
+
34
+ // Test route options
35
+ app.get('/sse', { sse: true }, async (request, reply) => {
36
+ expectType<SSEReplyInterface>(reply.sse)
37
+ return reply.sse.send({ data: 'test' })
38
+ })
39
+
40
+ app.get('/sse-with-options', {
41
+ sse: {
42
+ heartbeat: true,
43
+ serializer: (data: any) => JSON.stringify(data)
44
+ }
45
+ }, async (request, reply) => {
46
+ expectType<SSEReplyInterface>(reply.sse)
47
+ return reply.sse.send({ data: 'test' })
48
+ })
49
+
50
+ // Test SSE message types
51
+ const message: SSEMessage = {
52
+ data: 'test'
53
+ }
54
+
55
+ const fullMessage: SSEMessage = {
56
+ id: '123',
57
+ event: 'custom',
58
+ data: { foo: 'bar' },
59
+ retry: 5000
60
+ }
61
+
62
+ expectType<string | undefined>(message.id)
63
+ expectType<string | undefined>(message.event)
64
+ expectType<any>(message.data)
65
+ expectType<number | undefined>(message.retry)
66
+
67
+ // Test SSE sources
68
+ const stringSource: SSESource = 'hello'
69
+ const bufferSource: SSESource = Buffer.from('hello')
70
+ const messageSource: SSESource = { data: 'test' }
71
+ const streamSource: SSESource = new Readable()
72
+
73
+ async function* asyncGenerator(): AsyncIterable<SSEMessage> {
74
+ yield { data: 'test' }
75
+ }
76
+ const asyncIterableSource: SSESource = asyncGenerator()
77
+
78
+ // Test SSE reply interface
79
+ app.get('/test-reply', { sse: true }, async (request, reply) => {
80
+ // Test properties
81
+ expectType<string | null>(reply.sse.lastEventId)
82
+ expectType<boolean>(reply.sse.isConnected)
83
+
84
+ // Test send method with different sources
85
+ expectType<Promise<void>>(reply.sse.send('string'))
86
+ expectType<Promise<void>>(reply.sse.send(Buffer.from('buffer')))
87
+ expectType<Promise<void>>(reply.sse.send({ data: 'object' }))
88
+ expectType<Promise<void>>(reply.sse.send(new Readable()))
89
+ expectType<Promise<void>>(reply.sse.send(asyncGenerator()))
90
+
91
+ // Test stream method
92
+ expectType<NodeJS.WritableStream>(reply.sse.stream())
93
+
94
+ // Test keepAlive method
95
+ expectType<void>(reply.sse.keepAlive())
96
+
97
+ // Test close method
98
+ expectType<void>(reply.sse.close())
99
+
100
+ // Test replay method
101
+ expectType<Promise<void>>(reply.sse.replay(async (lastEventId: string) => {
102
+ console.log(lastEventId)
103
+ }))
104
+
105
+ // Test onClose method
106
+ expectType<void>(reply.sse.onClose(() => {
107
+ console.log('closed')
108
+ }))
109
+ })
110
+
111
+ // Test that reply.sse is available only on sse routes
112
+ app.get('/no-sse', async (request, reply) => {
113
+ // Note: reply.sse is added at runtime by the plugin, so we can't test its absence at compile time
114
+ // This is expected behavior for Fastify plugins that decorate at runtime
115
+ })
116
+
117
+ // Test complex SSE message scenarios
118
+ const complexMessage: SSEMessage = {
119
+ id: '456',
120
+ event: 'update',
121
+ data: {
122
+ nested: {
123
+ property: 'value',
124
+ array: [1, 2, 3]
125
+ }
126
+ },
127
+ retry: 10000
128
+ }
129
+
130
+ expectAssignable<SSESource>(complexMessage)
131
+
132
+ // Test async iterator types
133
+ async function* typedAsyncGenerator(): AsyncIterable<string> {
134
+ yield 'test'
135
+ }
136
+
137
+ async function* mixedAsyncGenerator(): AsyncIterable<SSEMessage | string | Buffer> {
138
+ yield { data: 'message' }
139
+ yield 'string'
140
+ yield Buffer.from('buffer')
141
+ }
142
+
143
+ expectAssignable<SSESource>(typedAsyncGenerator())
144
+ expectAssignable<SSESource>(mixedAsyncGenerator())
145
+
146
+ // Test plugin options interface
147
+ const pluginOptions: SSEPluginOptions = {
148
+ heartbeatInterval: 15000,
149
+ serializer: (data) => {
150
+ expectType<any>(data)
151
+ return JSON.stringify(data)
152
+ }
153
+ }
154
+
155
+ // Test serializer function type
156
+ const customSerializer = (data: any): string => {
157
+ if (typeof data === 'object') {
158
+ return JSON.stringify(data)
159
+ }
160
+ return String(data)
161
+ }
162
+
163
+ expectAssignable<SSEPluginOptions>({
164
+ serializer: customSerializer
165
+ })
166
+
167
+ // Test route options with boolean
168
+ const routeOptions1: RouteShorthandOptions = {
169
+ sse: true
170
+ }
171
+
172
+ const routeOptions2: RouteShorthandOptions = {
173
+ sse: false
174
+ }
175
+
176
+ const routeOptions3: RouteShorthandOptions = {
177
+ sse: {
178
+ heartbeat: false,
179
+ serializer: (data) => String(data)
180
+ }
181
+ }
182
+
183
+ // Test invalid route options - these tests verify type checking
184
+ expectError(app.get('/invalid', {
185
+ sse: 'invalid'
186
+ }, async (request, reply) => {}))
187
+
188
+ expectError(app.get('/invalid2', {
189
+ sse: {
190
+ unknownOption: true
191
+ }
192
+ }, async (request, reply) => {}))
package/types/.gitkeep ADDED
File without changes
@@ -0,0 +1,105 @@
1
+ import { Readable } from 'stream'
2
+ import { FastifyPluginAsync } from 'fastify'
3
+
4
+ declare module 'fastify' {
5
+ interface FastifyReply {
6
+ sse: SSEReplyInterface
7
+ }
8
+
9
+ interface RouteShorthandOptions {
10
+ sse?: boolean | {
11
+ heartbeat?: boolean
12
+ serializer?: (data: any) => string
13
+ }
14
+ }
15
+ }
16
+
17
+ export interface SSEPluginOptions {
18
+ /**
19
+ * Interval in milliseconds for sending heartbeat comments
20
+ * Set to 0 to disable heartbeats
21
+ * @default 30000
22
+ */
23
+ heartbeatInterval?: number
24
+
25
+ /**
26
+ * Default serializer for data payloads
27
+ * @default JSON.stringify
28
+ */
29
+ serializer?: (data: any) => string
30
+ }
31
+
32
+ export interface SSEMessage {
33
+ /**
34
+ * Event ID for client-side tracking
35
+ */
36
+ id?: string
37
+
38
+ /**
39
+ * Event type name
40
+ */
41
+ event?: string
42
+
43
+ /**
44
+ * Event data payload
45
+ */
46
+ data: any
47
+
48
+ /**
49
+ * Retry interval in milliseconds
50
+ */
51
+ retry?: number
52
+ }
53
+
54
+ export type SSESource =
55
+ | SSEMessage
56
+ | string
57
+ | Buffer
58
+ | Readable
59
+ | AsyncIterable<SSEMessage | string | Buffer>
60
+
61
+ export interface SSEReplyInterface {
62
+ /**
63
+ * Last Event ID sent by the client
64
+ */
65
+ readonly lastEventId: string | null
66
+
67
+ /**
68
+ * Send an SSE event or stream
69
+ */
70
+ send(source: SSESource): Promise<void>
71
+
72
+ /**
73
+ * Create a transform stream for pipeline operations
74
+ */
75
+ stream(): NodeJS.WritableStream
76
+
77
+ /**
78
+ * Keep the connection alive (prevent handler from closing it)
79
+ */
80
+ keepAlive(): void
81
+
82
+ /**
83
+ * Close the SSE connection
84
+ */
85
+ close(): void
86
+
87
+ /**
88
+ * Handle replay of events based on Last-Event-ID
89
+ */
90
+ replay(callback: (lastEventId: string) => Promise<void>): Promise<void>
91
+
92
+ /**
93
+ * Register a callback for when the connection closes
94
+ */
95
+ onClose(callback: () => void): void
96
+
97
+ /**
98
+ * Check if the connection is still active
99
+ */
100
+ readonly isConnected: boolean
101
+ }
102
+
103
+ declare const fastifySSE: FastifyPluginAsync<SSEPluginOptions>
104
+
105
+ export default fastifySSE