better-sse 0.14.1 → 0.15.1

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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2024 Matthew W.
3
+ Copyright (c) 2025 Matthew W.
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,15 +1,24 @@
1
1
  # Better SSE
2
2
 
3
3
  <p>
4
- <img src="https://img.shields.io/npm/v/better-sse?color=blue&style=flat-square" />
5
- <img src="https://img.shields.io/npm/l/better-sse?color=green&style=flat-square" />
6
- <img src="https://img.shields.io/npm/dt/better-sse?color=grey&style=flat-square" />
7
- <a href="https://github.com/MatthewWid/better-sse"><img src="https://img.shields.io/github/stars/MatthewWid/better-sse?style=social" /></a>
4
+ <a href="https://www.npmjs.com/package/better-sse">
5
+ <img src="https://img.shields.io/npm/v/better-sse?color=blue&style=flat-square" alt="npm" />
6
+ </a>
7
+ <a href="https://jsr.io/@mwid/better-sse">
8
+ <img src="https://jsr.io/badges/@mwid/better-sse" alt="jsr" />
9
+ </a>
10
+ <a href="https://github.com/MatthewWid/better-sse/blob/master/LICENSE">
11
+ <img src="https://img.shields.io/npm/l/better-sse?color=green&style=flat-square" alt="MIT license" />
12
+ </a>
13
+ <img src="https://img.shields.io/npm/dt/better-sse?color=grey&style=flat-square" alt="Downloads" />
14
+ <a href="https://github.com/MatthewWid/better-sse">
15
+ <img src="https://img.shields.io/github/stars/MatthewWid/better-sse?style=social" alt="GitHub stars" />
16
+ </a>
8
17
  </p>
9
18
 
10
- A dead simple, dependency-less, spec-compliant server-sent events implementation for Node, written in TypeScript.
19
+ A dead simple, dependency-less, spec-compliant server-sent events implementation written in TypeScript.
11
20
 
12
- This package aims to be the easiest to use, most compliant and most streamlined solution to server-sent events with Node that is framework-agnostic and feature-rich.
21
+ This package aims to be the easiest to use, most compliant and most streamlined solution to server-sent events that is framework-agnostic and feature-rich.
13
22
 
14
23
  Please consider starring the project [on GitHub ⭐](https://github.com/MatthewWid/better-sse).
15
24
 
@@ -21,106 +30,135 @@ Using SSE can allow for significant savings in bandwidth and battery life on por
21
30
 
22
31
  Compared to WebSockets it has comparable performance and bandwidth usage, especially over HTTP/2, and natively includes event ID generation and automatic reconnection when clients are disconnected.
23
32
 
33
+ Read the [Getting Started](https://matthewwid.github.io/better-sse/guides/getting-started/) guide for more.
34
+
24
35
  * [Comparison: Server-sent Events vs WebSockets vs Polling](https://medium.com/dailyjs/a-comparison-between-websockets-server-sent-events-and-polling-7a27c98cb1e3)
25
36
  * [WHATWG standards section for server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html)
26
37
  * [MDN guide to server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events)
38
+ * [Can I use... Server-sent events](https://caniuse.com/eventsource)
27
39
 
28
40
  ## Highlights
29
41
 
30
- * Compatible with all popular Node HTTP frameworks ([Express](https://nodejs.org/api/http.html), [Fastify](https://fastify.dev/), [Nest](https://nestjs.com/), [Next.js](https://nextjs.org/), etc.)
42
+ * Compatible with all popular HTTP frameworks ([Express](https://nodejs.org/api/http.html), [Hono](https://hono.dev/), [Fastify](https://fastify.dev/), [Nest](https://nestjs.com/), [Next.js](https://nextjs.org/), [Bun](https://bun.sh/docs/api/http), [Deno](https://docs.deno.com/runtime/fundamentals/http_server/), [etc.](https://matthewwid.github.io/better-sse/reference/recipes/))
31
43
  * Fully written in TypeScript (+ ships with types directly).
32
44
  * [Thoroughly tested](./src/Session.test.ts) (+ 100% code coverage!).
33
45
  * [Comprehensively documented](https://matthewwid.github.io/better-sse) with guides and API documentation.
34
46
  * [Channels](https://matthewwid.github.io/better-sse/guides/channels) allow you to broadcast events to many clients at once.
47
+ * [Event buffers](https://matthewwid.github.io/better-sse/guides/batching/) allow you to batch events for increased performance and lower bandwidth usage.
35
48
  * Configurable reconnection time, message serialization and data sanitization (with good defaults).
36
49
  * Trust or ignore the client-given last event ID.
37
50
  * Automatically send keep-alive pings to keep connections open.
38
51
  * Add or override the response status code and headers.
39
- * Send [individual fields](https://matthewwid.github.io/better-sse/guides/batching#send-individual-event-fields) of events or send [full events with simple helpers](https://matthewwid.github.io/better-sse/reference/api/#sessionpush-data-unknown-eventname-string-eventid-string--this).
40
52
  * Pipe [streams](https://nodejs.org/api/stream.html#stream_readable_streams) and [iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) directly from the server to the client as a series of events.
41
53
  * Support for popular EventSource polyfills [`event-source-polyfill`](https://www.npmjs.com/package/event-source-polyfill) and [`eventsource-polyfill`](https://www.npmjs.com/package/eventsource-polyfill).
42
54
 
43
- [See a comparison with other Node SSE libraries in the documentation.](https://matthewwid.github.io/better-sse/reference/comparison)
55
+ [See a comparison with other SSE libraries in the documentation.](https://matthewwid.github.io/better-sse/reference/comparison)
44
56
 
45
57
  # Installation
46
58
 
47
- ```bash
48
- # npm
59
+ Better SSE is published as a package on [npm](https://www.npmjs.com/package/better-sse) and the [JSR](https://jsr.io/@mwid/better-sse). You can install it with any package manager:
60
+
61
+ ```sh
49
62
  npm install better-sse
63
+ ```
50
64
 
51
- # Yarn
65
+ ```sh
52
66
  yarn add better-sse
67
+ ```
53
68
 
54
- # pnpm
69
+ ```sh
55
70
  pnpm add better-sse
56
71
  ```
57
72
 
73
+ ```sh
74
+ bun add better-sse
75
+ ```
76
+
77
+ ```sh
78
+ deno install jsr:@mwid/better-sse
79
+ ```
80
+
58
81
  _Better SSE ships with types built in. No need to install from DefinitelyTyped for TypeScript users!_
59
82
 
60
83
  # Usage
61
84
 
62
- The following example shows usage with [Express](http://expressjs.com/), but Better SSE works with any web-server framework that uses the underlying Node [HTTP module](https://nodejs.org/api/http.html).
85
+ The examples below show usage with [Express](http://expressjs.com/) and [Hono](https://hono.dev/), but Better SSE works with any web-server framework that uses the Node [HTTP module](https://nodejs.org/api/http.html) or the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
63
86
 
64
87
  See the [Recipes](https://matthewwid.github.io/better-sse/reference/recipes/) section of the documentation for use with other frameworks and libraries.
65
88
 
66
89
  ---
67
90
 
68
- Use [sessions](https://matthewwid.github.io/better-sse/reference/api/#sessionstate) to push events to clients:
91
+ Use [sessions](https://matthewwid.github.io/better-sse/guides/getting-started/#create-a-session) to push events to clients:
69
92
 
70
93
  ```typescript
71
- // Server
72
- import { createSession } from "better-sse";
94
+ // Server - Express
95
+ import { createSession } from "better-sse"
73
96
 
74
97
  app.get("/sse", async (req, res) => {
75
- const session = await createSession(req, res);
98
+ const session = await createSession(req, res)
99
+ session.push("Hello world!", "message")
100
+ })
101
+ ```
76
102
 
77
- session.push("Hello world!");
78
- });
103
+ ```typescript
104
+ // Server - Hono
105
+ import { createResponse } from "better-sse"
106
+
107
+ app.get("/sse", (c) =>
108
+ createResponse(c.req.raw, (session) => {
109
+ session.push("Hello world!", "message")
110
+ })
111
+ )
79
112
  ```
80
113
 
81
114
  ```typescript
82
115
  // Client
83
- const sse = new EventSource("/sse");
116
+ const eventSource = new EventSource("/sse")
84
117
 
85
- sse.addEventListener("message", ({ data }) => {
86
- console.log(JSON.parse(data));
87
- });
118
+ eventSource.addEventListener("message", ({ data })) => {
119
+ const contents = JSON.parse(data)
120
+ console.log(contents) // Hello world!
121
+ })
88
122
  ```
89
123
 
90
- Use [channels](https://matthewwid.github.io/better-sse/reference/api/#channelstate-sessionstate) to send events to many clients at once:
124
+ Use [channels](https://matthewwid.github.io/better-sse/guides/channels/#create-a-channel) to send events to many clients at once:
91
125
 
92
126
  ```typescript
93
- import { createSession, createChannel } from "better-sse";
127
+ import { createSession, createChannel } from "better-sse"
94
128
 
95
- const channel = createChannel();
129
+ const channel = createChannel()
96
130
 
97
131
  app.get("/sse", async (req, res) => {
98
- const session = await createSession(req, res);
132
+ const session = await createSession(req, res)
99
133
 
100
- channel.register(session);
134
+ channel.register(session)
101
135
 
102
- channel.broadcast("A user has joined.", "join-notification");
103
- });
136
+ channel.broadcast("A user has joined.", "join-notification")
137
+ })
104
138
  ```
105
139
 
106
- Loop over sync and async [iterables](https://matthewwid.github.io/better-sse/reference/api/#sessioniterate-iterable-iterable--asynciterable-options-object--promisevoid) and send each value as an event:
140
+ Use [batching](https://matthewwid.github.io/better-sse/guides/batching/) to send multiple events at once for improved performance and lower bandwidth usage:
107
141
 
108
142
  ```typescript
109
- const session = await createSession(req, res);
143
+ await session.batch(async (buffer) => {
144
+ await buffer.iterate(["My", "huge", "event", "list"])
145
+ })
146
+ ```
110
147
 
111
- const list = [1, 2, 3];
148
+ Loop over sync and async [iterables](https://matthewwid.github.io/better-sse/reference/api/#sessioniterate-iterable-iterable--asynciterable-options-object--promisevoid) and send each value as an event:
149
+
150
+ ```typescript
151
+ const iterable = [1, 2, 3]
112
152
 
113
- await session.iterate(list);
153
+ await session.iterate(iterable)
114
154
  ```
115
155
 
116
156
  Pipe [readable stream](https://matthewwid.github.io/better-sse/reference/api/#sessionstream-stream-readable-options-object--promiseboolean) data to the client as a stream of events:
117
157
 
118
158
  ```typescript
119
- const session = await createSession(req, res);
159
+ const stream = Readable.from([1, 2, 3])
120
160
 
121
- const stream = Readable.from([1, 2, 3]);
122
-
123
- await session.stream(stream);
161
+ await session.stream(stream)
124
162
  ```
125
163
 
126
164
  ---
@@ -141,29 +179,37 @@ For code or documentation changes [submit a pull request on GitHub](https://gith
141
179
 
142
180
  ## Local Development
143
181
 
144
- Install Node:
182
+ Install [Node](https://nodejs.org/en) (with [n](https://github.com/tj/n)):
145
183
 
146
184
  ```bash
147
185
  curl -L https://git.io/n-install | bash
148
186
  n auto
149
187
  ```
150
188
 
151
- Install pnpm:
189
+ Install dependencies (with [pnpm](https://pnpm.io/)):
152
190
 
153
191
  ```bash
154
192
  npm i -g pnpm
193
+ pnpm i
155
194
  ```
156
195
 
157
- Install dependencies:
196
+ Run tests (with [Vitest](https://vitest.dev/)):
158
197
 
159
198
  ```bash
160
- pnpm i
199
+ pnpm t
161
200
  ```
162
201
 
163
- Run tests:
202
+ Lint and format (with [Biome](https://biomejs.dev/)):
164
203
 
165
204
  ```bash
166
- pnpm t
205
+ pnpm lint
206
+ pnpm format
207
+ ```
208
+
209
+ Bundle for distribution (with [tsup](https://tsup.egoist.dev/)):
210
+
211
+ ```bash
212
+ pnpm build
167
213
  ```
168
214
 
169
215
  # License
package/build/index.d.mts CHANGED
@@ -1,9 +1,7 @@
1
- import * as stream from 'stream';
2
- import * as http from 'http';
3
- import { OutgoingHttpHeaders, IncomingMessage, ServerResponse } from 'http';
4
- import * as http2 from 'http2';
5
- import { Http2ServerRequest, Http2ServerResponse } from 'http2';
6
- import { EventEmitter } from 'events';
1
+ import { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { Http2ServerRequest, Http2ServerResponse } from 'node:http2';
3
+ import { Readable } from 'node:stream';
4
+ import { EventEmitter } from 'node:events';
7
5
 
8
6
  interface IterateOptions {
9
7
  /**
@@ -13,7 +11,9 @@ interface IterateOptions {
13
11
  */
14
12
  eventName?: string;
15
13
  }
14
+ type PushFromIterable = (iterable: Iterable<unknown> | AsyncIterable<unknown>, options?: IterateOptions) => Promise<void>;
16
15
 
16
+ type WebReadableStream = ReadableStream;
17
17
  interface StreamOptions {
18
18
  /**
19
19
  * Event name/type to be emitted when stream data is sent to the client.
@@ -22,17 +22,14 @@ interface StreamOptions {
22
22
  */
23
23
  eventName?: string;
24
24
  }
25
+ type PushFromStream = (stream: Readable | WebReadableStream, options?: StreamOptions) => Promise<boolean>;
26
+
27
+ type SanitizerFunction = (text: string) => string;
25
28
 
26
29
  /**
27
30
  * Serialize arbitrary data to a string that can be sent over the wire to the client.
28
31
  */
29
- interface SerializerFunction {
30
- (data: unknown): string;
31
- }
32
-
33
- interface SanitizerFunction {
34
- (text: string): string;
35
- }
32
+ type SerializerFunction = (data: unknown) => string;
36
33
 
37
34
  interface EventBufferOptions {
38
35
  /**
@@ -124,9 +121,9 @@ declare class EventBuffer {
124
121
  * @param stream - Readable stream to consume data from.
125
122
  * @param options - Event name to use for each event created.
126
123
  *
127
- * @returns A promise that resolves or rejects based on the success of the stream write finishing.
124
+ * @returns A promise that resolves with `true` or rejects based on the success of the stream write finishing.
128
125
  */
129
- stream: (stream: stream.Readable, options?: StreamOptions) => Promise<boolean>;
126
+ stream: PushFromStream;
130
127
  /**
131
128
  * Iterate over an iterable and write yielded values as events into the buffer.
132
129
  *
@@ -138,7 +135,7 @@ declare class EventBuffer {
138
135
  *
139
136
  * @returns A promise that resolves once all data has been successfully yielded from the iterable.
140
137
  */
141
- iterate: <DataType = unknown>(iterable: Iterable<DataType> | AsyncIterable<DataType>, options?: IterateOptions) => Promise<void>;
138
+ iterate: PushFromIterable;
142
139
  /**
143
140
  * Clear the contents of the buffer.
144
141
  */
@@ -218,7 +215,7 @@ interface SessionOptions<State = DefaultSessionState> extends Pick<EventBufferOp
218
215
  /**
219
216
  * Additional headers to be sent along with the response.
220
217
  */
221
- headers?: OutgoingHttpHeaders;
218
+ headers?: Record<string, string | string[] | undefined>;
222
219
  /**
223
220
  * Custom state for this session.
224
221
  *
@@ -239,15 +236,19 @@ interface SessionEvents extends EventMap {
239
236
  *
240
237
  * It extends from the {@link https://nodejs.org/api/events.html#events_class_eventemitter | EventEmitter} class.
241
238
  *
242
- * It emits the `connected` event after it has connected and sent all headers to the client, and the
243
- * `disconnected` event after the connection has been closed.
239
+ * It emits the `connected` event after it has connected and sent the response head to the client.
240
+ * It emits the `disconnected` event after the connection has been closed.
241
+ *
242
+ * When using the Fetch API, the session is considered connected only once the `ReadableStream` contained in the body
243
+ * of the `Response` returned by `getResponse` has began being consumed.
244
244
  *
245
- * Note that creating a new session will immediately send the initial status code and headers to the client.
246
- * Attempting to write additional headers after you have created a new session will result in an error.
245
+ * When using the Node HTTP APIs, the session will send the response with status code, headers and other preamble data ahead of time,
246
+ * allowing the session to connect and start pushing events immediately. As such, keep in mind that attempting
247
+ * to write additional headers after the session has been created will result in an error being thrown.
247
248
  *
248
- * @param req - The Node HTTP {@link https://nodejs.org/api/http.html#http_class_http_incomingmessage | ServerResponse} object.
249
- * @param res - The Node HTTP {@link https://nodejs.org/api/http.html#http_class_http_serverresponse | IncomingMessage} object.
250
- * @param options - Options given to the session instance.
249
+ * @param req - The Node HTTP/1 {@link https://nodejs.org/api/http.html#http_class_http_incomingmessage | ServerResponse}, HTTP/2 {@link https://nodejs.org/api/http2.html#class-http2http2serverrequest | Http2ServerRequest} or the Fetch API {@link https://developer.mozilla.org/en-US/docs/Web/API/Request | Request} object.
250
+ * @param res - The Node HTTP {@link https://nodejs.org/api/http.html#http_class_http_serverresponse | IncomingMessage}, HTTP/2 {@link https://nodejs.org/api/http2.html#class-http2http2serverresponse | Http2ServerResponse} or the Fetch API {@link https://developer.mozilla.org/en-US/docs/Web/API/Response | Response} object. Optional if using the Fetch API.
251
+ * @param options - Optional additional configuration for the session.
251
252
  */
252
253
  declare class Session<State = DefaultSessionState> extends TypedEmitter<SessionEvents> {
253
254
  /**
@@ -276,57 +277,45 @@ declare class Session<State = DefaultSessionState> extends TypedEmitter<SessionE
276
277
  */
277
278
  state: State;
278
279
  private buffer;
279
- /**
280
- * Raw HTTP request.
281
- */
282
- private req;
283
- /**
284
- * Raw HTTP response that is the minimal interface needed and forms the
285
- * intersection between the HTTP/1.1 and HTTP/2 server response interfaces.
286
- */
287
- private res;
288
- private serialize;
280
+ private connection;
289
281
  private sanitize;
290
- private trustClientEventId;
282
+ private serialize;
291
283
  private initialRetry;
292
284
  private keepAliveInterval;
293
285
  private keepAliveTimer?;
294
- private statusCode;
295
- private headers;
296
- constructor(req: IncomingMessage | Http2ServerRequest, res: ServerResponse | Http2ServerResponse, options?: SessionOptions<State>);
286
+ constructor(req: IncomingMessage, res: ServerResponse, options?: SessionOptions<State>);
287
+ constructor(req: Http2ServerRequest, res: Http2ServerResponse, options?: SessionOptions<State>);
288
+ constructor(req: Request, res?: Response, options?: SessionOptions<State>);
289
+ constructor(req: Request, options?: SessionOptions<State>);
297
290
  private initialize;
298
291
  private onDisconnected;
299
- private keepAlive;
300
- /**
301
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
302
- */
303
- event(type: string): this;
304
292
  /**
305
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
293
+ * Write an empty comment and flush it to the client.
306
294
  */
307
- data: (data: unknown) => this;
308
- /**
309
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
310
- */
311
- id: (id?: string) => this;
295
+ private keepAlive;
312
296
  /**
313
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
297
+ * Flush the contents of the internal buffer to the client and clear the buffer.
314
298
  */
315
- retry: (time: number) => this;
299
+ private flush;
316
300
  /**
317
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
318
- */
319
- comment: (text?: string) => this;
320
- /**
321
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
301
+ * Get a Request object representing the request of the underlying connection this session manages.
302
+ *
303
+ * When using the Fetch API, this will be the original Request object passed to the session constructor.
304
+ *
305
+ * When using the Node HTTP APIs, this will be a new Request object with status code and headers copied from the original request.
306
+ * When the originally given request or response is closed, the abort signal attached to this Request will be triggered.
322
307
  */
323
- dispatch: () => this;
308
+ getRequest: () => Request;
324
309
  /**
325
- * Flush the contents of the internal buffer to the client and clear the buffer.
310
+ * Get a Response object representing the response of the underlying connection this session manages.
311
+ *
312
+ * When using the Fetch API, this will be a new Response object with status code and headers copied from the original response if given.
313
+ * Its body will be a ReadableStream that should begin being consumed for the session to consider itself connected.
326
314
  *
327
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
315
+ * When using the Node HTTP APIs, this will be a new Response object with status code and headers copied from the original response.
316
+ * Its body will be `null`, as data is instead written to the stream of the originally given response object.
328
317
  */
329
- flush: () => this;
318
+ getResponse: () => Response;
330
319
  /**
331
320
  * Push an event to the client.
332
321
  *
@@ -334,6 +323,8 @@ declare class Session<State = DefaultSessionState> extends TypedEmitter<SessionE
334
323
  *
335
324
  * If no event ID is given, the event ID (and thus the `lastId` property) is set to a unique string generated using a cryptographic pseudorandom number generator.
336
325
  *
326
+ * If the session has disconnected, an `SseError` will be thrown.
327
+ *
337
328
  * Emits the `push` event with the given data, event name and event ID in that order.
338
329
  *
339
330
  * @param data - Data to write.
@@ -351,9 +342,9 @@ declare class Session<State = DefaultSessionState> extends TypedEmitter<SessionE
351
342
  * @param stream - Readable stream to consume data from.
352
343
  * @param options - Options to alter how the stream is flushed to the client.
353
344
  *
354
- * @returns A promise that resolves or rejects based on the success of the stream write finishing.
345
+ * @returns A promise that resolves with `true` or rejects based on the success of the stream write finishing.
355
346
  */
356
- stream: (stream: stream.Readable, options?: StreamOptions) => Promise<boolean>;
347
+ stream: PushFromStream;
357
348
  /**
358
349
  * Iterate over an iterable and send yielded values as events to the client.
359
350
  *
@@ -365,7 +356,7 @@ declare class Session<State = DefaultSessionState> extends TypedEmitter<SessionE
365
356
  *
366
357
  * @returns A promise that resolves once all data has been successfully yielded from the iterable.
367
358
  */
368
- iterate: <DataType = unknown>(iterable: Iterable<DataType> | AsyncIterable<DataType>, options?: IterateOptions) => Promise<void>;
359
+ iterate: PushFromIterable;
369
360
  /**
370
361
  * Batch and send multiple events at once.
371
362
  *
@@ -384,9 +375,30 @@ declare class Session<State = DefaultSessionState> extends TypedEmitter<SessionE
384
375
  }
385
376
 
386
377
  /**
387
- * Create a new session and return the session instance once it has connected.
378
+ * Create a new session.
379
+ *
380
+ * When using the Fetch API, resolves immediately with a session instance before it has connected.
381
+ * You can listen for the `connected` event on the session to know when it has connected, or
382
+ * otherwise use the shorthand `createResponse` function that does so for you instead.
383
+ *
384
+ * When using the Node HTTP APIs, waits for the session to connect before resolving with its instance.
385
+ */
386
+ declare function createSession<State = DefaultSessionState>(req: IncomingMessage, res: ServerResponse, options?: SessionOptions<State>): Promise<Session<State>>;
387
+ declare function createSession<State = DefaultSessionState>(req: Http2ServerRequest, res: Http2ServerResponse, options?: SessionOptions<State>): Promise<Session<State>>;
388
+ declare function createSession<State = DefaultSessionState>(req: Request, res?: Response, options?: SessionOptions<State>): Promise<Session<State>>;
389
+ declare function createSession<State = DefaultSessionState>(req: Request, options?: SessionOptions<State>): Promise<Session<State>>;
390
+
391
+ type CreateResponseCallback<State> = (session: Session<State>) => void;
392
+ /**
393
+ * Create a new session using the Fetch API and return its corresponding `Response` object.
394
+ *
395
+ * The last argument should be a callback function that will be invoked with
396
+ * the session instance once it has connected.
388
397
  */
389
- declare const createSession: <State = DefaultSessionState>(req: http.IncomingMessage | http2.Http2ServerRequest, res: http.ServerResponse<http.IncomingMessage> | http2.Http2ServerResponse<http2.Http2ServerRequest>, options?: SessionOptions<State> | undefined) => Promise<Session<State>>;
398
+ declare function createResponse<State = DefaultSessionState>(request: Request, callback: CreateResponseCallback<State>): Response;
399
+ declare function createResponse<State = DefaultSessionState>(request: Request, response: Response, callback: CreateResponseCallback<State>): Response;
400
+ declare function createResponse<State = DefaultSessionState>(request: Request, options: SessionOptions<State>, callback: CreateResponseCallback<State>): Response;
401
+ declare function createResponse<State = DefaultSessionState>(request: Request, response: Response, options: SessionOptions<State>, callback: CreateResponseCallback<State>): Response;
390
402
 
391
403
  interface ChannelOptions<State = DefaultChannelState> {
392
404
  /**
@@ -482,4 +494,4 @@ declare class SseError extends Error {
482
494
  constructor(message: string);
483
495
  }
484
496
 
485
- export { type BroadcastOptions, Channel, type ChannelEvents, type ChannelOptions, type DefaultChannelState, type DefaultSessionState, EventBuffer, type EventBufferOptions, type IterateOptions, Session, type SessionEvents, type SessionOptions, SseError, type StreamOptions, createChannel, createEventBuffer, createSession };
497
+ export { type BroadcastOptions, Channel, type ChannelEvents, type ChannelOptions, type CreateResponseCallback, type DefaultChannelState, type DefaultSessionState, EventBuffer, type EventBufferOptions, type IterateOptions, Session, type SessionEvents, type SessionOptions, SseError, type StreamOptions, createChannel, createEventBuffer, createResponse, createSession };