better-sse 0.15.1 → 0.16.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,662 @@
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";
5
+
6
+ //#region src/utils/createPushFromIterable.d.ts
7
+ interface IterateOptions {
8
+ /**
9
+ * Event name/type to be emitted when iterable data is sent to the client.
10
+ *
11
+ * Defaults to `"iteration"`.
12
+ */
13
+ eventName?: string;
14
+ }
15
+ type PushFromIterable = (iterable: Iterable<unknown> | AsyncIterable<unknown>, options?: IterateOptions) => Promise<void>;
16
+ //#endregion
17
+ //#region src/utils/createPushFromStream.d.ts
18
+ type WebReadableStream = ReadableStream;
19
+ interface StreamOptions {
20
+ /**
21
+ * Event name/type to be emitted when stream data is sent to the client.
22
+ *
23
+ * Defaults to `"stream"`.
24
+ */
25
+ eventName?: string;
26
+ }
27
+ type PushFromStream = (stream: Readable | WebReadableStream, options?: StreamOptions) => Promise<boolean>;
28
+ //#endregion
29
+ //#region src/utils/sanitize.d.ts
30
+ type SanitizerFunction = (text: string) => string;
31
+ //#endregion
32
+ //#region src/utils/serialize.d.ts
33
+ /**
34
+ * Serialize arbitrary data to a string that can be sent over the wire to the client.
35
+ */
36
+ type SerializerFunction = (data: unknown) => string;
37
+ //#endregion
38
+ //#region src/EventBuffer.d.ts
39
+ interface EventBufferOptions {
40
+ /**
41
+ * Serialize data to a string that can be written.
42
+ *
43
+ * Defaults to `JSON.stringify`.
44
+ */
45
+ serializer?: SerializerFunction;
46
+ /**
47
+ * Sanitize values so as to not prematurely dispatch events when writing fields whose text inadvertently contains newlines.
48
+ *
49
+ * By default, CR, LF and CRLF characters are replaced with a single LF character (`\n`) and then any trailing LF characters are stripped so as to prevent a blank line being written and accidentally dispatching the event before `.dispatch()` is called.
50
+ */
51
+ sanitizer?: SanitizerFunction;
52
+ }
53
+ /**
54
+ * An `EventBuffer` allows you to write raw spec-compliant SSE fields into a text buffer that can be sent directly over the wire.
55
+ */
56
+ declare class EventBuffer {
57
+ private buffer;
58
+ private serialize;
59
+ private sanitize;
60
+ constructor(options?: EventBufferOptions);
61
+ /**
62
+ * Write a line with a field key and value appended with a newline character.
63
+ */
64
+ private writeField;
65
+ /**
66
+ * Write an event name field (also referred to as the event "type" in the specification).
67
+ *
68
+ * @param type - Event name/type.
69
+ */
70
+ event(type: string): this;
71
+ /**
72
+ * Write arbitrary data into a data field.
73
+ *
74
+ * Data is serialized to a string using the given `serializer` function option or JSON stringification by default.
75
+ *
76
+ * @param data - Data to serialize and write.
77
+ */
78
+ data: (data: unknown) => this;
79
+ /**
80
+ * Write an event ID field.
81
+ *
82
+ * Defaults to an empty string if no argument is given.
83
+ *
84
+ * @param id - Identification string to write.
85
+ */
86
+ id: (id?: string) => this;
87
+ /**
88
+ * Write a retry field that suggests a reconnection time with the given milliseconds.
89
+ *
90
+ * @param time - Time in milliseconds to retry.
91
+ */
92
+ retry: (time: number) => this;
93
+ /**
94
+ * Write a comment (an ignored field).
95
+ *
96
+ * This will not fire an event but is often used to keep the connection alive.
97
+ *
98
+ * @param text - Text of the comment. Otherwise writes an empty field value.
99
+ */
100
+ comment: (text?: string) => this;
101
+ /**
102
+ * Indicate that the event has finished being created by writing an additional newline character.
103
+ */
104
+ dispatch: () => this;
105
+ /**
106
+ * Create, write and dispatch an event with the given data all at once.
107
+ *
108
+ * This is equivalent to calling the methods `event`, `id`, `data` and `dispatch` in that order.
109
+ *
110
+ * If no event name is given, the event name is set to `"message"`.
111
+ *
112
+ * If no event ID is given, the event ID is set to a randomly generated UUIDv4.
113
+ *
114
+ * @param data - Data to write.
115
+ * @param eventName - Event name to write.
116
+ * @param eventId - Event ID to write.
117
+ */
118
+ push: (data: unknown, eventName?: string, eventId?: string) => this;
119
+ /**
120
+ * Pipe readable stream data as a series of events into the buffer.
121
+ *
122
+ * This uses the `push` method under the hood.
123
+ *
124
+ * If no event name is given in the `options` object, the event name is set to `"stream"`.
125
+ *
126
+ * @param stream - Readable stream to consume data from.
127
+ * @param options - Event name to use for each event created.
128
+ *
129
+ * @returns A promise that resolves with `true` or rejects based on the success of the stream write finishing.
130
+ */
131
+ stream: PushFromStream;
132
+ /**
133
+ * Iterate over an iterable and write yielded values as events into the buffer.
134
+ *
135
+ * This uses the `push` method under the hood.
136
+ *
137
+ * If no event name is given in the `options` object, the event name is set to `"iteration"`.
138
+ *
139
+ * @param iterable - Iterable to consume data from.
140
+ *
141
+ * @returns A promise that resolves once all data has been successfully yielded from the iterable.
142
+ */
143
+ iterate: PushFromIterable;
144
+ /**
145
+ * Clear the contents of the buffer.
146
+ */
147
+ clear: () => this;
148
+ /**
149
+ * Get a copy of the buffer contents.
150
+ */
151
+ read: () => string;
152
+ }
153
+ //#endregion
154
+ //#region src/utils/TypedEmitter.d.ts
155
+ interface EventMap {
156
+ [name: string | symbol]: (...args: any[]) => void;
157
+ }
158
+ /**
159
+ * Get event names type
160
+ */
161
+ type EventNames<T> = keyof { [K in keyof T as string extends K ? never : number extends K ? never : K]: never } | (string & {});
162
+ /**
163
+ * Wraps the EventEmitter class to add types that map event names
164
+ * to types of arguments in the event handler callback.
165
+ */
166
+ declare class TypedEmitter<Events extends EventMap> extends EventEmitter {
167
+ constructor(...args: ConstructorParameters<typeof EventEmitter>);
168
+ addListener<EventName extends EventNames<Events>>(event: EventName, listener: Events[EventName]): this;
169
+ prependListener<EventName extends EventNames<Events>>(event: EventName, listener: Events[EventName]): this;
170
+ prependOnceListener<EventName extends EventNames<Events>>(event: EventName, listener: Events[EventName]): this;
171
+ on<EventName extends EventNames<Events>>(event: EventName, listener: Events[EventName]): this;
172
+ once<EventName extends EventNames<Events>>(event: EventName, listener: Events[EventName]): this;
173
+ emit<EventName extends EventNames<Events>>(event: EventName, ...args: Parameters<Events[EventName]>): boolean;
174
+ off<EventName extends EventNames<Events>>(event: EventName, listener: Events[EventName]): this;
175
+ removeListener<EventName extends EventNames<Events>>(event: EventName, listener: Events[EventName]): this;
176
+ }
177
+ //#endregion
178
+ //#region src/Session.d.ts
179
+ interface SessionOptions<State = DefaultSessionState> extends Pick<EventBufferOptions, "serializer" | "sanitizer"> {
180
+ /**
181
+ * Whether to trust or ignore the last event ID given by the client in the `Last-Event-ID` request header.
182
+ *
183
+ * When set to `false`, the `lastId` property will always be initialized to an empty string.
184
+ *
185
+ * Defaults to `true`.
186
+ */
187
+ trustClientEventId?: boolean;
188
+ /**
189
+ * Time in milliseconds for the client to wait before attempting to reconnect if the connection is closed.
190
+ *
191
+ * This is a request to the client browser, and does not guarantee that the client will actually respect the given time.
192
+ *
193
+ * Equivalent to immediately calling `.retry().dispatch().flush()` after a connection is made.
194
+ *
195
+ * Give as `null` to avoid sending an explicit reconnection time and allow the client browser to decide itself.
196
+ *
197
+ * Defaults to `2000` milliseconds.
198
+ *
199
+ * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-event-stream-reconnection-time
200
+ */
201
+ retry?: number | null;
202
+ /**
203
+ * Time in milliseconds interval for the session to send a comment to keep the connection alive.
204
+ *
205
+ * Give as `null` to disable the connection keep-alive mechanism.
206
+ *
207
+ * Defaults to `10000` milliseconds (`10` seconds).
208
+ */
209
+ keepAlive?: number | null;
210
+ /**
211
+ * Status code to be sent to the client.
212
+ *
213
+ * Event stream requests can be redirected using HTTP 301 and 307 status codes.
214
+ * Make sure to set `Location` header when using these status codes using the `headers` property.
215
+ *
216
+ * A client can be asked to stop reconnecting by using 204 status code.
217
+ *
218
+ * Ignored if passing a custom `Connection` instance to the `Session` constructor.
219
+ *
220
+ * Defaults to `200`.
221
+ */
222
+ statusCode?: number;
223
+ /**
224
+ * Additional headers to be sent along with the response.
225
+ *
226
+ * Ignored if passing a custom `Connection` instance to the `Session` constructor.
227
+ */
228
+ headers?: Record<string, string | string[] | undefined>;
229
+ /**
230
+ * Custom state for this session.
231
+ *
232
+ * Use this object to safely store information related to the session and user.
233
+ */
234
+ state?: State;
235
+ }
236
+ interface DefaultSessionState {
237
+ [key: string]: unknown;
238
+ }
239
+ interface SessionEvents extends EventMap {
240
+ connected: () => void;
241
+ disconnected: () => void;
242
+ push: (data: unknown, eventName: string, eventId: string) => void;
243
+ }
244
+ /**
245
+ * A `Session` represents an open connection between the server and a client.
246
+ *
247
+ * It extends from the {@link https://nodejs.org/api/events.html#events_class_eventemitter | EventEmitter} class.
248
+ *
249
+ * It emits the `connected` event after it has connected and sent the response head to the client.
250
+ * It emits the `disconnected` event after the connection has been closed.
251
+ *
252
+ * When using the Fetch API, the session is considered connected only once the `ReadableStream` contained in the body
253
+ * of the `Response` returned by `getResponse` has began being consumed.
254
+ *
255
+ * When using the Node HTTP APIs, the session will send the response with status code, headers and other preamble data ahead of time,
256
+ * allowing the session to connect and start pushing events immediately. As such, keep in mind that attempting
257
+ * to write additional headers after the session has been created will result in an error being thrown.
258
+ *
259
+ * @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.
260
+ * @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.
261
+ * @param options - Optional additional configuration for the session.
262
+ */
263
+ declare class Session<State = DefaultSessionState> extends TypedEmitter<SessionEvents> {
264
+ /**
265
+ * The last event ID sent to the client.
266
+ *
267
+ * This is initialized to the last event ID given by the user, and otherwise is equal to the last number given to the `.id` method.
268
+ *
269
+ * For security reasons, keep in mind that the client can provide *any* initial ID here. Use the `trustClientEventId` constructor option to ignore the client-given initial ID.
270
+ *
271
+ * @readonly
272
+ */
273
+ lastId: string;
274
+ /**
275
+ * Indicates whether the session and underlying connection is open or not.
276
+ *
277
+ * @readonly
278
+ */
279
+ isConnected: boolean;
280
+ /**
281
+ * Custom state for this session.
282
+ *
283
+ * Use this object to safely store information related to the session and user.
284
+ *
285
+ * Use [module augmentation and declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)
286
+ * to safely add new properties to the `DefaultSessionState` interface.
287
+ */
288
+ state: State;
289
+ private buffer;
290
+ private connection;
291
+ private sanitize;
292
+ private serialize;
293
+ private initialRetry;
294
+ private keepAliveInterval;
295
+ private keepAliveTimer?;
296
+ constructor(req: IncomingMessage, res: ServerResponse, options?: SessionOptions<State>);
297
+ constructor(req: Http2ServerRequest, res: Http2ServerResponse, options?: SessionOptions<State>);
298
+ constructor(req: Request, res?: Response, options?: SessionOptions<State>);
299
+ constructor(req: Request, options?: SessionOptions<State>);
300
+ constructor(connection: Connection, options?: SessionOptions<State>);
301
+ private initialize;
302
+ private onDisconnected;
303
+ /**
304
+ * Write an empty comment and flush it to the client.
305
+ */
306
+ private keepAlive;
307
+ /**
308
+ * Flush the contents of the internal buffer to the client and clear the buffer.
309
+ */
310
+ private flush;
311
+ /**
312
+ * Get a Request object representing the request of the underlying connection this session manages.
313
+ *
314
+ * When using the Fetch API, this will be the original Request object passed to the session constructor.
315
+ *
316
+ * When using the Node HTTP APIs, this will be a new Request object with status code and headers copied from the original request.
317
+ * When the originally given request or response is closed, the abort signal attached to this Request will be triggered.
318
+ */
319
+ getRequest: () => any;
320
+ /**
321
+ * Get a Response object representing the response of the underlying connection this session manages.
322
+ *
323
+ * When using the Fetch API, this will be a new Response object with status code and headers copied from the original response if given.
324
+ * Its body will be a ReadableStream that should begin being consumed for the session to consider itself connected.
325
+ *
326
+ * When using the Node HTTP APIs, this will be a new Response object with status code and headers copied from the original response.
327
+ * Its body will be `null`, as data is instead written to the stream of the originally given response object.
328
+ */
329
+ getResponse: () => any;
330
+ /**
331
+ * Push an event to the client.
332
+ *
333
+ * If no event name is given, the event name is set to `"message"`.
334
+ *
335
+ * If no event ID is given, the event ID (and thus the `lastId` property) is set to a randomly generated UUIDv4.
336
+ *
337
+ * If the session has disconnected, an `SseError` will be thrown.
338
+ *
339
+ * Emits the `push` event with the given data, event name and event ID in that order.
340
+ *
341
+ * @param data - Data to write.
342
+ * @param eventName - Event name to write.
343
+ * @param eventId - Event ID to write.
344
+ */
345
+ push: (data: unknown, eventName?: string, eventId?: string) => this;
346
+ /**
347
+ * Pipe readable stream data as a series of events to the client.
348
+ *
349
+ * This uses the `push` method under the hood.
350
+ *
351
+ * If no event name is given in the `options` object, the event name is set to `"stream"`.
352
+ *
353
+ * @param stream - Readable stream to consume data from.
354
+ * @param options - Options to alter how the stream is flushed to the client.
355
+ *
356
+ * @returns A promise that resolves with `true` or rejects based on the success of the stream write finishing.
357
+ */
358
+ stream: PushFromStream;
359
+ /**
360
+ * Iterate over an iterable and send yielded values as events to the client.
361
+ *
362
+ * This uses the `push` method under the hood.
363
+ *
364
+ * If no event name is given in the `options` object, the event name is set to `"iteration"`.
365
+ *
366
+ * @param iterable - Iterable to consume data from.
367
+ *
368
+ * @returns A promise that resolves once all data has been successfully yielded from the iterable.
369
+ */
370
+ iterate: PushFromIterable;
371
+ /**
372
+ * Batch and send multiple events at once.
373
+ *
374
+ * If given an `EventBuffer` instance, its contents will be sent to the client.
375
+ *
376
+ * If given a callback, it will be passed an instance of `EventBuffer` which uses the same serializer and sanitizer as the session.
377
+ * Once its execution completes - or once it resolves if it returns a promise - the contents of the passed `EventBuffer` will be sent to the client.
378
+ *
379
+ * @param batcher - Event buffer to get contents from, or callback that takes an event buffer to write to.
380
+ *
381
+ * @returns A promise that resolves once all data from the event buffer has been successfully sent to the client.
382
+ *
383
+ * @see EventBuffer
384
+ */
385
+ batch: (batcher: EventBuffer | ((buffer: EventBuffer) => void | Promise<void>)) => Promise<void>;
386
+ }
387
+ //#endregion
388
+ //#region src/adapters/Connection.d.ts
389
+ type ConnectionConstants = Readonly<{
390
+ /**
391
+ * The default HTTP request method to apply to the `Connection#request` `status` property.
392
+ */
393
+ REQUEST_METHOD: string;
394
+ /**
395
+ * The default domain to apply to the `Connection#url` `host` property, typically overriden by the value of the `Host` header.
396
+ */
397
+ REQUEST_HOST: string;
398
+ /**
399
+ * The default HTTP response status code to apply to the `Connection#response` `status` property.
400
+ */
401
+ RESPONSE_CODE: number;
402
+ /**
403
+ * The default HTTP response headers to apply to the `Connection#response` `headers` property.
404
+ */
405
+ RESPONSE_HEADERS: Readonly<Record<string, string>>;
406
+ }>;
407
+ /**
408
+ * Represents the full request and response of an underlying network connection,
409
+ * abstracting away the differences between the Node HTTP/1, HTTP/2, Fetch and
410
+ * any other APIs.
411
+ *
412
+ * You can implement your own custom `Connection` subclass to make Better SSE
413
+ * compatible with any framework.
414
+ */
415
+ declare abstract class Connection {
416
+ /**
417
+ * Useful constants that you may use when implementing your own custom connection.
418
+ */
419
+ static constants: Readonly<{
420
+ /**
421
+ * The default HTTP request method to apply to the `Connection#request` `status` property.
422
+ */
423
+ REQUEST_METHOD: string;
424
+ /**
425
+ * The default domain to apply to the `Connection#url` `host` property, typically overriden by the value of the `Host` header.
426
+ */
427
+ REQUEST_HOST: string;
428
+ /**
429
+ * The default HTTP response status code to apply to the `Connection#response` `status` property.
430
+ */
431
+ RESPONSE_CODE: number;
432
+ /**
433
+ * The default HTTP response headers to apply to the `Connection#response` `headers` property.
434
+ */
435
+ RESPONSE_HEADERS: Readonly<Record<string, string>>;
436
+ }>;
437
+ /**
438
+ * Utility method to consistently merge headers from an object into a `Headers` object.
439
+ *
440
+ * For each entry in `from`:
441
+ * - If the value is a `string`, it will replace the target header.
442
+ * - If the value is an `Array`, it will replace the target header and then append each item.
443
+ * - If the value is `undefined`, it will delete the target header.
444
+ */
445
+ static applyHeaders(from: Record<string, string | string[] | undefined> | Headers, to: Headers): void;
446
+ /**
447
+ * The URL used to open the connection to the server.
448
+ *
449
+ * For HTTP-based connections, this is typically constructured from the request `Host` header and URL path, including the query string.
450
+ *
451
+ * You should pass this to the constructor of the `Request` object stored in the `Connection#request` property.
452
+ */
453
+ abstract url: URL;
454
+ /**
455
+ * Represents the request that opened the connection.
456
+ *
457
+ * You should populate its `url` property - likely with the same value as the `url` property - its `method` and its `headers` properties.
458
+ *
459
+ * You should populate its `signal` property with an `AbortSignal` that gets triggered when the request *or* the response is closed, indicating to the session that the connection has disconnected.
460
+ */
461
+ abstract request: Request;
462
+ /**
463
+ * Represents the response that will be sent to the client.
464
+ *
465
+ * You should populate its `status` and `headers` properties.
466
+ *
467
+ * You *may* populate its `body` property with a `ReadableStream` that will enqueue any data written with the `sendChunk` method if you intend to use the session with a Fetch-based framework.
468
+ */
469
+ abstract response: Response;
470
+ /**
471
+ * Send the response head with status code and headers from the `response` instance.
472
+ */
473
+ abstract sendHead(): void;
474
+ /**
475
+ * Write a chunk of data to the socket.
476
+ *
477
+ * You should encode the data to UTF-8 beforehand.
478
+ */
479
+ abstract sendChunk(chunk: string): void;
480
+ /**
481
+ * Perform any necessary cleanup after the connection is closed.
482
+ */
483
+ abstract cleanup(): void;
484
+ }
485
+ /**
486
+ * Options passed from `Session` `options` argument to the built-in `Connection` implementations.
487
+ */
488
+ interface BuiltInConnectionOptions extends Pick<SessionOptions, "statusCode" | "headers"> {}
489
+ //#endregion
490
+ //#region src/adapters/FetchConnection.d.ts
491
+ declare class FetchConnection extends Connection {
492
+ private static encoder;
493
+ private writer;
494
+ url: URL;
495
+ request: Request;
496
+ response: Response;
497
+ constructor(request: Request, response: Response | null, options?: BuiltInConnectionOptions);
498
+ sendHead: () => void;
499
+ sendChunk: (chunk: string) => void;
500
+ cleanup: () => void;
501
+ }
502
+ //#endregion
503
+ //#region src/adapters/NodeHttp1Connection.d.ts
504
+ declare class NodeHttp1Connection extends Connection {
505
+ private req;
506
+ private res;
507
+ private controller;
508
+ url: URL;
509
+ request: Request;
510
+ response: Response;
511
+ constructor(req: IncomingMessage, res: ServerResponse, options?: BuiltInConnectionOptions);
512
+ private onClose;
513
+ sendHead: () => void;
514
+ sendChunk: (chunk: string) => void;
515
+ cleanup: () => void;
516
+ }
517
+ //#endregion
518
+ //#region src/adapters/NodeHttp2CompatConnection.d.ts
519
+ declare class NodeHttp2CompatConnection extends Connection {
520
+ private req;
521
+ private res;
522
+ private controller;
523
+ url: URL;
524
+ request: Request;
525
+ response: Response;
526
+ constructor(req: Http2ServerRequest, res: Http2ServerResponse, options?: BuiltInConnectionOptions);
527
+ private onClose;
528
+ sendHead: () => void;
529
+ sendChunk: (chunk: string) => void;
530
+ cleanup: () => void;
531
+ }
532
+ //#endregion
533
+ //#region src/Channel.d.ts
534
+ interface ChannelOptions<State = DefaultChannelState> {
535
+ /**
536
+ * Custom state for this channel.
537
+ *
538
+ * Use this object to safely store information related to the channel.
539
+ */
540
+ state?: State;
541
+ }
542
+ interface BroadcastOptions<SessionState = DefaultSessionState> {
543
+ /**
544
+ * Unique ID for the event being broadcast.
545
+ *
546
+ * If no event ID is given, the event ID is set to a randomly generated UUIDv4.
547
+ */
548
+ eventId?: string;
549
+ /**
550
+ * Filter sessions that should receive the event.
551
+ *
552
+ * Called with each session and should return `true` to allow the event to be sent and otherwise return `false` to prevent the session from receiving the event.
553
+ */
554
+ filter?: (session: Session<SessionState>) => boolean;
555
+ }
556
+ interface ChannelEvents<SessionState = DefaultSessionState> extends EventMap {
557
+ "session-registered": (session: Session<SessionState>) => void;
558
+ "session-deregistered": (session: Session<SessionState>) => void;
559
+ "session-disconnected": (session: Session<SessionState>) => void;
560
+ broadcast: (data: unknown, eventName: string, eventId: string) => void;
561
+ }
562
+ interface DefaultChannelState {
563
+ [key: string]: unknown;
564
+ }
565
+ /**
566
+ * A `Channel` is used to broadcast events to many sessions at once.
567
+ *
568
+ * It extends from the {@link https://nodejs.org/api/events.html#events_class_eventemitter | EventEmitter} class.
569
+ *
570
+ * You may use the second generic argument `SessionState` to enforce that only sessions with the same state type may be registered with this channel.
571
+ */
572
+ declare class Channel<State = DefaultChannelState, SessionState = DefaultSessionState> extends TypedEmitter<ChannelEvents<SessionState>> {
573
+ /**
574
+ * Custom state for this channel.
575
+ *
576
+ * Use this object to safely store information related to the channel.
577
+ */
578
+ state: State;
579
+ private sessions;
580
+ constructor(options?: ChannelOptions<State>);
581
+ /**
582
+ * List of the currently active sessions registered with this channel.
583
+ */
584
+ get activeSessions(): ReadonlyArray<Session<SessionState>>;
585
+ /**
586
+ * Number of sessions registered with this channel.
587
+ */
588
+ get sessionCount(): number;
589
+ /**
590
+ * Register a session so that it can start receiving events from this channel.
591
+ *
592
+ * If the session was already registered to begin with this method does nothing.
593
+ *
594
+ * @param session - Session to register.
595
+ */
596
+ register(session: Session<SessionState>): this;
597
+ /**
598
+ * Deregister a session so that it no longer receives events from this channel.
599
+ *
600
+ * If the session was not registered to begin with this method does nothing.
601
+ *
602
+ * @param session - Session to deregister.
603
+ */
604
+ deregister(session: Session<SessionState>): this;
605
+ /**
606
+ * Broadcast an event to every active session registered with this channel.
607
+ *
608
+ * Under the hood this calls the `push` method on every active session.
609
+ *
610
+ * If no event name is given, the event name is set to `"message"`.
611
+ *
612
+ * Note that the broadcasted event will have the same ID across all receiving sessions instead of generating a unique ID for each.
613
+ *
614
+ * @param data - Data to write.
615
+ * @param eventName - Event name to write.
616
+ */
617
+ broadcast: (data: unknown, eventName?: string, options?: BroadcastOptions<SessionState>) => this;
618
+ }
619
+ //#endregion
620
+ //#region src/createChannel.d.ts
621
+ declare const createChannel: <State = DefaultChannelState, SessionState = DefaultSessionState>(...args: ConstructorParameters<typeof Channel<State, SessionState>>) => Channel<State, SessionState>;
622
+ //#endregion
623
+ //#region src/createEventBuffer.d.ts
624
+ declare const createEventBuffer: (...args: ConstructorParameters<typeof EventBuffer>) => EventBuffer;
625
+ //#endregion
626
+ //#region src/createResponse.d.ts
627
+ type CreateResponseCallback<State> = (session: Session<State>) => void;
628
+ /**
629
+ * Create a new session using the Fetch API and return its corresponding `Response` object.
630
+ *
631
+ * The last argument should be a callback function that will be invoked with
632
+ * the session instance once it has connected.
633
+ */
634
+ declare function createResponse<State = DefaultSessionState>(request: Request, callback: CreateResponseCallback<State>): Response;
635
+ declare function createResponse<State = DefaultSessionState>(request: Request, response: Response, callback: CreateResponseCallback<State>): Response;
636
+ declare function createResponse<State = DefaultSessionState>(request: Request, options: SessionOptions<State>, callback: CreateResponseCallback<State>): Response;
637
+ declare function createResponse<State = DefaultSessionState>(request: Connection, callback: CreateResponseCallback<State>): Response;
638
+ declare function createResponse<State = DefaultSessionState>(request: Connection, options: SessionOptions<State>, callback: CreateResponseCallback<State>): Response;
639
+ declare function createResponse<State = DefaultSessionState>(request: Request, response: Response, options: SessionOptions<State>, callback: CreateResponseCallback<State>): Response;
640
+ //#endregion
641
+ //#region src/createSession.d.ts
642
+ /**
643
+ * Create a new session.
644
+ *
645
+ * When using the Fetch API, resolves immediately with a session instance before it has connected.
646
+ * You can listen for the `connected` event on the session to know when it has connected, or
647
+ * otherwise use the shorthand `createResponse` function that does so for you instead.
648
+ *
649
+ * When using the Node HTTP APIs, waits for the session to connect before resolving with its instance.
650
+ */
651
+ declare function createSession<State = DefaultSessionState>(req: IncomingMessage, res: ServerResponse, options?: SessionOptions<State>): Promise<Session<State>>;
652
+ declare function createSession<State = DefaultSessionState>(req: Http2ServerRequest, res: Http2ServerResponse, options?: SessionOptions<State>): Promise<Session<State>>;
653
+ declare function createSession<State = DefaultSessionState>(req: Request, res?: Response, options?: SessionOptions<State>): Promise<Session<State>>;
654
+ declare function createSession<State = DefaultSessionState>(req: Request, options?: SessionOptions<State>): Promise<Session<State>>;
655
+ declare function createSession<State = DefaultSessionState>(req: Connection, options?: SessionOptions<State>): Promise<Session<State>>;
656
+ //#endregion
657
+ //#region src/utils/SseError.d.ts
658
+ declare class SseError extends Error {
659
+ constructor(message: string);
660
+ }
661
+ //#endregion
662
+ export { type BroadcastOptions, type BuiltInConnectionOptions, Channel, type ChannelEvents, type ChannelOptions, Connection, type ConnectionConstants, type CreateResponseCallback, type DefaultChannelState, type DefaultSessionState, EventBuffer, type EventBufferOptions, FetchConnection, type IterateOptions, NodeHttp1Connection, NodeHttp2CompatConnection, Session, type SessionEvents, type SessionOptions, SseError, type StreamOptions, createChannel, createEventBuffer, createResponse, createSession };