better-sse 0.15.1 → 0.16.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/README.md +26 -3
- package/build/index.cjs +771 -0
- package/build/index.d.cts +662 -0
- package/build/index.d.mts +580 -415
- package/build/index.mjs +728 -744
- package/package.json +15 -16
- package/build/index.d.ts +0 -497
- package/build/index.js +0 -807
package/build/index.js
DELETED
|
@@ -1,807 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __export = (target, all) => {
|
|
7
|
-
for (var name in all)
|
|
8
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
-
};
|
|
10
|
-
var __copyProps = (to, from, except, desc) => {
|
|
11
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
-
for (let key of __getOwnPropNames(from))
|
|
13
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
-
|
|
20
|
-
// src/index.ts
|
|
21
|
-
var src_exports = {};
|
|
22
|
-
__export(src_exports, {
|
|
23
|
-
Channel: () => Channel,
|
|
24
|
-
EventBuffer: () => EventBuffer,
|
|
25
|
-
Session: () => Session,
|
|
26
|
-
SseError: () => SseError,
|
|
27
|
-
createChannel: () => createChannel,
|
|
28
|
-
createEventBuffer: () => createEventBuffer,
|
|
29
|
-
createResponse: () => createResponse,
|
|
30
|
-
createSession: () => createSession
|
|
31
|
-
});
|
|
32
|
-
module.exports = __toCommonJS(src_exports);
|
|
33
|
-
|
|
34
|
-
// src/Session.ts
|
|
35
|
-
var import_node_http = require("http");
|
|
36
|
-
var import_node_http2 = require("http2");
|
|
37
|
-
var import_node_timers = require("timers");
|
|
38
|
-
|
|
39
|
-
// src/lib/createPushFromIterable.ts
|
|
40
|
-
var createPushFromIterable = (push) => async (iterable, options = {}) => {
|
|
41
|
-
const { eventName = "iteration" } = options;
|
|
42
|
-
for await (const data of iterable) {
|
|
43
|
-
push(data, eventName);
|
|
44
|
-
}
|
|
45
|
-
};
|
|
46
|
-
|
|
47
|
-
// src/lib/createPushFromStream.ts
|
|
48
|
-
var import_node_stream = require("stream");
|
|
49
|
-
var createPushFromStream = (push) => async (stream, options = {}) => {
|
|
50
|
-
const { eventName = "stream" } = options;
|
|
51
|
-
if (stream instanceof import_node_stream.Readable) {
|
|
52
|
-
return await new Promise((resolve, reject) => {
|
|
53
|
-
stream.on("data", (chunk) => {
|
|
54
|
-
let data;
|
|
55
|
-
if (Buffer.isBuffer(chunk)) {
|
|
56
|
-
data = chunk.toString();
|
|
57
|
-
} else {
|
|
58
|
-
data = chunk;
|
|
59
|
-
}
|
|
60
|
-
push(data, eventName);
|
|
61
|
-
});
|
|
62
|
-
stream.once("end", () => resolve(true));
|
|
63
|
-
stream.once("close", () => resolve(true));
|
|
64
|
-
stream.once("error", (err) => reject(err));
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
for await (const chunk of stream) {
|
|
68
|
-
if (Buffer.isBuffer(chunk)) {
|
|
69
|
-
push(chunk.toString(), eventName);
|
|
70
|
-
} else {
|
|
71
|
-
push(chunk, eventName);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
return true;
|
|
75
|
-
};
|
|
76
|
-
|
|
77
|
-
// src/lib/generateId.ts
|
|
78
|
-
var import_node_crypto = require("crypto");
|
|
79
|
-
var generateId;
|
|
80
|
-
if (import_node_crypto.randomUUID) {
|
|
81
|
-
generateId = () => (0, import_node_crypto.randomUUID)();
|
|
82
|
-
} else {
|
|
83
|
-
generateId = () => (0, import_node_crypto.randomBytes)(4).toString("hex");
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// src/lib/sanitize.ts
|
|
87
|
-
var newlineVariantsRegex = /(\r\n|\r|\n)/g;
|
|
88
|
-
var newlineTrailingRegex = /\n+$/g;
|
|
89
|
-
var sanitize = (text) => {
|
|
90
|
-
let sanitized = text;
|
|
91
|
-
sanitized = sanitized.replace(newlineVariantsRegex, "\n");
|
|
92
|
-
sanitized = sanitized.replace(newlineTrailingRegex, "");
|
|
93
|
-
return sanitized;
|
|
94
|
-
};
|
|
95
|
-
|
|
96
|
-
// src/lib/serialize.ts
|
|
97
|
-
var serialize = (data) => JSON.stringify(data);
|
|
98
|
-
|
|
99
|
-
// src/EventBuffer.ts
|
|
100
|
-
var EventBuffer = class {
|
|
101
|
-
buffer = "";
|
|
102
|
-
serialize;
|
|
103
|
-
sanitize;
|
|
104
|
-
constructor(options = {}) {
|
|
105
|
-
this.serialize = options.serializer ?? serialize;
|
|
106
|
-
this.sanitize = options.sanitizer ?? sanitize;
|
|
107
|
-
}
|
|
108
|
-
/**
|
|
109
|
-
* Write a line with a field key and value appended with a newline character.
|
|
110
|
-
*/
|
|
111
|
-
writeField = (name, value) => {
|
|
112
|
-
const sanitized = this.sanitize(value);
|
|
113
|
-
this.buffer += name + ":" + sanitized + "\n";
|
|
114
|
-
return this;
|
|
115
|
-
};
|
|
116
|
-
/**
|
|
117
|
-
* Write an event name field (also referred to as the event "type" in the specification).
|
|
118
|
-
*
|
|
119
|
-
* @param type - Event name/type.
|
|
120
|
-
*/
|
|
121
|
-
event(type) {
|
|
122
|
-
this.writeField("event", type);
|
|
123
|
-
return this;
|
|
124
|
-
}
|
|
125
|
-
/**
|
|
126
|
-
* Write arbitrary data into a data field.
|
|
127
|
-
*
|
|
128
|
-
* Data is serialized to a string using the given `serializer` function option or JSON stringification by default.
|
|
129
|
-
*
|
|
130
|
-
* @param data - Data to serialize and write.
|
|
131
|
-
*/
|
|
132
|
-
data = (data) => {
|
|
133
|
-
const serialized = this.serialize(data);
|
|
134
|
-
this.writeField("data", serialized);
|
|
135
|
-
return this;
|
|
136
|
-
};
|
|
137
|
-
/**
|
|
138
|
-
* Write an event ID field.
|
|
139
|
-
*
|
|
140
|
-
* Defaults to an empty string if no argument is given.
|
|
141
|
-
*
|
|
142
|
-
* @param id - Identification string to write.
|
|
143
|
-
*/
|
|
144
|
-
id = (id = "") => {
|
|
145
|
-
this.writeField("id", id);
|
|
146
|
-
return this;
|
|
147
|
-
};
|
|
148
|
-
/**
|
|
149
|
-
* Write a retry field that suggests a reconnection time with the given milliseconds.
|
|
150
|
-
*
|
|
151
|
-
* @param time - Time in milliseconds to retry.
|
|
152
|
-
*/
|
|
153
|
-
retry = (time) => {
|
|
154
|
-
const stringifed = time.toString();
|
|
155
|
-
this.writeField("retry", stringifed);
|
|
156
|
-
return this;
|
|
157
|
-
};
|
|
158
|
-
/**
|
|
159
|
-
* Write a comment (an ignored field).
|
|
160
|
-
*
|
|
161
|
-
* This will not fire an event but is often used to keep the connection alive.
|
|
162
|
-
*
|
|
163
|
-
* @param text - Text of the comment. Otherwise writes an empty field value.
|
|
164
|
-
*/
|
|
165
|
-
comment = (text = "") => {
|
|
166
|
-
this.writeField("", text);
|
|
167
|
-
return this;
|
|
168
|
-
};
|
|
169
|
-
/**
|
|
170
|
-
* Indicate that the event has finished being created by writing an additional newline character.
|
|
171
|
-
*/
|
|
172
|
-
dispatch = () => {
|
|
173
|
-
this.buffer += "\n";
|
|
174
|
-
return this;
|
|
175
|
-
};
|
|
176
|
-
/**
|
|
177
|
-
* Create, write and dispatch an event with the given data all at once.
|
|
178
|
-
*
|
|
179
|
-
* This is equivalent to calling the methods `event`, `id`, `data` and `dispatch` in that order.
|
|
180
|
-
*
|
|
181
|
-
* If no event name is given, the event name is set to `"message"`.
|
|
182
|
-
*
|
|
183
|
-
* If no event ID is given, the event ID is set to a unique string generated using a cryptographic pseudorandom number generator.
|
|
184
|
-
*
|
|
185
|
-
* @param data - Data to write.
|
|
186
|
-
* @param eventName - Event name to write.
|
|
187
|
-
* @param eventId - Event ID to write.
|
|
188
|
-
*/
|
|
189
|
-
push = (data, eventName = "message", eventId = generateId()) => {
|
|
190
|
-
this.event(eventName).id(eventId).data(data).dispatch();
|
|
191
|
-
return this;
|
|
192
|
-
};
|
|
193
|
-
/**
|
|
194
|
-
* Pipe readable stream data as a series of events into the buffer.
|
|
195
|
-
*
|
|
196
|
-
* This uses the `push` method under the hood.
|
|
197
|
-
*
|
|
198
|
-
* If no event name is given in the `options` object, the event name is set to `"stream"`.
|
|
199
|
-
*
|
|
200
|
-
* @param stream - Readable stream to consume data from.
|
|
201
|
-
* @param options - Event name to use for each event created.
|
|
202
|
-
*
|
|
203
|
-
* @returns A promise that resolves with `true` or rejects based on the success of the stream write finishing.
|
|
204
|
-
*/
|
|
205
|
-
stream = createPushFromStream(this.push);
|
|
206
|
-
/**
|
|
207
|
-
* Iterate over an iterable and write yielded values as events into the buffer.
|
|
208
|
-
*
|
|
209
|
-
* This uses the `push` method under the hood.
|
|
210
|
-
*
|
|
211
|
-
* If no event name is given in the `options` object, the event name is set to `"iteration"`.
|
|
212
|
-
*
|
|
213
|
-
* @param iterable - Iterable to consume data from.
|
|
214
|
-
*
|
|
215
|
-
* @returns A promise that resolves once all data has been successfully yielded from the iterable.
|
|
216
|
-
*/
|
|
217
|
-
iterate = createPushFromIterable(this.push);
|
|
218
|
-
/**
|
|
219
|
-
* Clear the contents of the buffer.
|
|
220
|
-
*/
|
|
221
|
-
clear = () => {
|
|
222
|
-
this.buffer = "";
|
|
223
|
-
return this;
|
|
224
|
-
};
|
|
225
|
-
/**
|
|
226
|
-
* Get a copy of the buffer contents.
|
|
227
|
-
*/
|
|
228
|
-
read = () => this.buffer;
|
|
229
|
-
};
|
|
230
|
-
|
|
231
|
-
// src/lib/applyHeaders.ts
|
|
232
|
-
var applyHeaders = (from, to) => {
|
|
233
|
-
const fromMap = from instanceof Headers ? Object.fromEntries(from) : from;
|
|
234
|
-
for (const [key, value] of Object.entries(fromMap)) {
|
|
235
|
-
if (Array.isArray(value)) {
|
|
236
|
-
to.delete(key);
|
|
237
|
-
for (const item of value) {
|
|
238
|
-
to.append(key, item);
|
|
239
|
-
}
|
|
240
|
-
} else if (value === void 0) {
|
|
241
|
-
to.delete(key);
|
|
242
|
-
} else {
|
|
243
|
-
to.set(key, value);
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
};
|
|
247
|
-
|
|
248
|
-
// src/lib/constants.ts
|
|
249
|
-
var DEFAULT_REQUEST_HOST = "localhost";
|
|
250
|
-
var DEFAULT_REQUEST_METHOD = "GET";
|
|
251
|
-
var DEFAULT_RESPONSE_CODE = 200;
|
|
252
|
-
var DEFAULT_RESPONSE_HEADERS = {
|
|
253
|
-
"Content-Type": "text/event-stream",
|
|
254
|
-
"Cache-Control": "private, no-cache, no-store, no-transform, must-revalidate, max-age=0",
|
|
255
|
-
Connection: "keep-alive",
|
|
256
|
-
Pragma: "no-cache",
|
|
257
|
-
"X-Accel-Buffering": "no"
|
|
258
|
-
};
|
|
259
|
-
|
|
260
|
-
// src/adapters/FetchConnection.ts
|
|
261
|
-
var FetchConnection = class _FetchConnection {
|
|
262
|
-
static encoder = new TextEncoder();
|
|
263
|
-
writer;
|
|
264
|
-
url;
|
|
265
|
-
request;
|
|
266
|
-
response;
|
|
267
|
-
constructor(request, response, options = {}) {
|
|
268
|
-
this.url = new URL(request.url);
|
|
269
|
-
this.request = request;
|
|
270
|
-
const { readable, writable } = new TransformStream();
|
|
271
|
-
this.writer = writable.getWriter();
|
|
272
|
-
this.response = new Response(readable, {
|
|
273
|
-
status: options.statusCode ?? response?.status ?? DEFAULT_RESPONSE_CODE,
|
|
274
|
-
headers: DEFAULT_RESPONSE_HEADERS
|
|
275
|
-
});
|
|
276
|
-
if (response) {
|
|
277
|
-
applyHeaders(response.headers, this.response.headers);
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
sendHead = () => {
|
|
281
|
-
};
|
|
282
|
-
sendChunk = (chunk) => {
|
|
283
|
-
const encoded = _FetchConnection.encoder.encode(chunk);
|
|
284
|
-
this.writer.write(encoded);
|
|
285
|
-
};
|
|
286
|
-
cleanup = () => {
|
|
287
|
-
this.writer.close();
|
|
288
|
-
};
|
|
289
|
-
};
|
|
290
|
-
|
|
291
|
-
// src/adapters/NodeHttp1Connection.ts
|
|
292
|
-
var NodeHttp1Connection = class {
|
|
293
|
-
constructor(req, res, options = {}) {
|
|
294
|
-
this.req = req;
|
|
295
|
-
this.res = res;
|
|
296
|
-
this.url = new URL(
|
|
297
|
-
`http://${req.headers.host ?? DEFAULT_REQUEST_HOST}${req.url}`
|
|
298
|
-
);
|
|
299
|
-
this.controller = new AbortController();
|
|
300
|
-
req.once("close", this.onClose);
|
|
301
|
-
res.once("close", this.onClose);
|
|
302
|
-
this.request = new Request(this.url, {
|
|
303
|
-
method: req.method ?? DEFAULT_REQUEST_METHOD,
|
|
304
|
-
signal: this.controller.signal
|
|
305
|
-
});
|
|
306
|
-
applyHeaders(req.headers, this.request.headers);
|
|
307
|
-
this.response = new Response(null, {
|
|
308
|
-
status: options.statusCode ?? res.statusCode ?? DEFAULT_RESPONSE_CODE,
|
|
309
|
-
headers: DEFAULT_RESPONSE_HEADERS
|
|
310
|
-
});
|
|
311
|
-
if (res) {
|
|
312
|
-
applyHeaders(
|
|
313
|
-
res.getHeaders(),
|
|
314
|
-
this.response.headers
|
|
315
|
-
);
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
controller;
|
|
319
|
-
url;
|
|
320
|
-
request;
|
|
321
|
-
response;
|
|
322
|
-
onClose = () => {
|
|
323
|
-
this.controller.abort();
|
|
324
|
-
};
|
|
325
|
-
sendHead = () => {
|
|
326
|
-
this.res.writeHead(
|
|
327
|
-
this.response.status,
|
|
328
|
-
Object.fromEntries(this.response.headers)
|
|
329
|
-
);
|
|
330
|
-
};
|
|
331
|
-
sendChunk = (chunk) => {
|
|
332
|
-
this.res.write(chunk);
|
|
333
|
-
};
|
|
334
|
-
cleanup = () => {
|
|
335
|
-
this.req.removeListener("close", this.onClose);
|
|
336
|
-
this.res.removeListener("close", this.onClose);
|
|
337
|
-
};
|
|
338
|
-
};
|
|
339
|
-
|
|
340
|
-
// src/adapters/NodeHttp2CompatConnection.ts
|
|
341
|
-
var NodeHttp2CompatConnection = class {
|
|
342
|
-
constructor(req, res, options = {}) {
|
|
343
|
-
this.req = req;
|
|
344
|
-
this.res = res;
|
|
345
|
-
this.url = new URL(
|
|
346
|
-
`http://${req.headers.host ?? DEFAULT_REQUEST_HOST}${req.url}`
|
|
347
|
-
);
|
|
348
|
-
this.controller = new AbortController();
|
|
349
|
-
req.once("close", this.onClose);
|
|
350
|
-
res.once("close", this.onClose);
|
|
351
|
-
this.request = new Request(this.url, {
|
|
352
|
-
method: req.method ?? DEFAULT_REQUEST_METHOD,
|
|
353
|
-
signal: this.controller.signal
|
|
354
|
-
});
|
|
355
|
-
const allowedHeaders = { ...req.headers };
|
|
356
|
-
for (const header of Object.keys(allowedHeaders)) {
|
|
357
|
-
if (header.startsWith(":")) {
|
|
358
|
-
delete allowedHeaders[header];
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
applyHeaders(allowedHeaders, this.request.headers);
|
|
362
|
-
this.response = new Response(null, {
|
|
363
|
-
status: options.statusCode ?? res.statusCode ?? DEFAULT_RESPONSE_CODE,
|
|
364
|
-
headers: DEFAULT_RESPONSE_HEADERS
|
|
365
|
-
});
|
|
366
|
-
if (res) {
|
|
367
|
-
applyHeaders(
|
|
368
|
-
res.getHeaders(),
|
|
369
|
-
this.response.headers
|
|
370
|
-
);
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
controller;
|
|
374
|
-
url;
|
|
375
|
-
request;
|
|
376
|
-
response;
|
|
377
|
-
onClose = () => {
|
|
378
|
-
this.controller.abort();
|
|
379
|
-
};
|
|
380
|
-
sendHead = () => {
|
|
381
|
-
this.res.writeHead(
|
|
382
|
-
this.response.status,
|
|
383
|
-
Object.fromEntries(this.response.headers)
|
|
384
|
-
);
|
|
385
|
-
};
|
|
386
|
-
sendChunk = (chunk) => {
|
|
387
|
-
this.res.write(chunk);
|
|
388
|
-
};
|
|
389
|
-
cleanup = () => {
|
|
390
|
-
this.req.removeListener("close", this.onClose);
|
|
391
|
-
this.res.removeListener("close", this.onClose);
|
|
392
|
-
};
|
|
393
|
-
};
|
|
394
|
-
|
|
395
|
-
// src/lib/SseError.ts
|
|
396
|
-
var SseError = class extends Error {
|
|
397
|
-
constructor(message) {
|
|
398
|
-
super(message);
|
|
399
|
-
this.message = `better-sse: ${message}`;
|
|
400
|
-
}
|
|
401
|
-
};
|
|
402
|
-
|
|
403
|
-
// src/lib/TypedEmitter.ts
|
|
404
|
-
var import_node_events = require("events");
|
|
405
|
-
var TypedEmitter = class extends import_node_events.EventEmitter {
|
|
406
|
-
addListener(event, listener) {
|
|
407
|
-
return super.addListener(event, listener);
|
|
408
|
-
}
|
|
409
|
-
prependListener(event, listener) {
|
|
410
|
-
return super.prependListener(event, listener);
|
|
411
|
-
}
|
|
412
|
-
prependOnceListener(event, listener) {
|
|
413
|
-
return super.prependOnceListener(event, listener);
|
|
414
|
-
}
|
|
415
|
-
on(event, listener) {
|
|
416
|
-
return super.on(event, listener);
|
|
417
|
-
}
|
|
418
|
-
once(event, listener) {
|
|
419
|
-
return super.once(event, listener);
|
|
420
|
-
}
|
|
421
|
-
emit(event, ...args) {
|
|
422
|
-
return super.emit(event, ...args);
|
|
423
|
-
}
|
|
424
|
-
off(event, listener) {
|
|
425
|
-
return super.off(event, listener);
|
|
426
|
-
}
|
|
427
|
-
removeListener(event, listener) {
|
|
428
|
-
return super.removeListener(event, listener);
|
|
429
|
-
}
|
|
430
|
-
};
|
|
431
|
-
|
|
432
|
-
// src/Session.ts
|
|
433
|
-
var Session = class extends TypedEmitter {
|
|
434
|
-
/**
|
|
435
|
-
* The last event ID sent to the client.
|
|
436
|
-
*
|
|
437
|
-
* 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.
|
|
438
|
-
*
|
|
439
|
-
* 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.
|
|
440
|
-
*
|
|
441
|
-
* @readonly
|
|
442
|
-
*/
|
|
443
|
-
lastId = "";
|
|
444
|
-
/**
|
|
445
|
-
* Indicates whether the session and underlying connection is open or not.
|
|
446
|
-
*
|
|
447
|
-
* @readonly
|
|
448
|
-
*/
|
|
449
|
-
isConnected = false;
|
|
450
|
-
/**
|
|
451
|
-
* Custom state for this session.
|
|
452
|
-
*
|
|
453
|
-
* Use this object to safely store information related to the session and user.
|
|
454
|
-
*
|
|
455
|
-
* Use [module augmentation and declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)
|
|
456
|
-
* to safely add new properties to the `DefaultSessionState` interface.
|
|
457
|
-
*/
|
|
458
|
-
state;
|
|
459
|
-
buffer;
|
|
460
|
-
connection;
|
|
461
|
-
sanitize;
|
|
462
|
-
serialize;
|
|
463
|
-
initialRetry;
|
|
464
|
-
keepAliveInterval;
|
|
465
|
-
keepAliveTimer;
|
|
466
|
-
constructor(req, res, options) {
|
|
467
|
-
super();
|
|
468
|
-
let givenOptions = options ?? {};
|
|
469
|
-
if (req instanceof Request) {
|
|
470
|
-
let givenRes = null;
|
|
471
|
-
if (res) {
|
|
472
|
-
if (res instanceof Response) {
|
|
473
|
-
givenRes = res;
|
|
474
|
-
} else {
|
|
475
|
-
if (options) {
|
|
476
|
-
throw new SseError(
|
|
477
|
-
"When providing a Fetch Request object but no Response object, you may pass options as the second OR third argument to the session constructor, but not to both."
|
|
478
|
-
);
|
|
479
|
-
}
|
|
480
|
-
givenOptions = res;
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
this.connection = new FetchConnection(req, givenRes, givenOptions);
|
|
484
|
-
} else if (req instanceof import_node_http.IncomingMessage) {
|
|
485
|
-
if (res instanceof import_node_http.ServerResponse) {
|
|
486
|
-
this.connection = new NodeHttp1Connection(req, res, givenOptions);
|
|
487
|
-
} else {
|
|
488
|
-
throw new SseError(
|
|
489
|
-
"When providing a Node IncomingMessage object, a corresponding ServerResponse object must also be provided."
|
|
490
|
-
);
|
|
491
|
-
}
|
|
492
|
-
} else if (req instanceof import_node_http2.Http2ServerRequest) {
|
|
493
|
-
if (res instanceof import_node_http2.Http2ServerResponse) {
|
|
494
|
-
this.connection = new NodeHttp2CompatConnection(req, res, givenOptions);
|
|
495
|
-
} else {
|
|
496
|
-
throw new SseError(
|
|
497
|
-
"When providing a Node HTTP2ServerRequest object, a corresponding HTTP2ServerResponse object must also be provided."
|
|
498
|
-
);
|
|
499
|
-
}
|
|
500
|
-
} else {
|
|
501
|
-
throw new SseError(
|
|
502
|
-
"Malformed request or response objects given to session constructor. Must be one of IncomingMessage/ServerResponse from the Node HTTP/1 API, HTTP2ServerRequest/HTTP2ServerResponse from the Node HTTP/2 Compatibility API, or Request/Response from the Fetch API."
|
|
503
|
-
);
|
|
504
|
-
}
|
|
505
|
-
if (givenOptions.headers) {
|
|
506
|
-
applyHeaders(givenOptions.headers, this.connection.response.headers);
|
|
507
|
-
}
|
|
508
|
-
if (givenOptions.trustClientEventId !== false) {
|
|
509
|
-
this.lastId = this.connection.request.headers.get("last-event-id") ?? this.connection.url.searchParams.get("lastEventId") ?? this.connection.url.searchParams.get("evs_last_event_id") ?? "";
|
|
510
|
-
}
|
|
511
|
-
this.state = givenOptions.state ?? {};
|
|
512
|
-
this.initialRetry = givenOptions.retry === null ? null : givenOptions.retry ?? 2e3;
|
|
513
|
-
this.keepAliveInterval = givenOptions.keepAlive === null ? null : givenOptions.keepAlive ?? 1e4;
|
|
514
|
-
this.serialize = givenOptions.serializer ?? serialize;
|
|
515
|
-
this.sanitize = givenOptions.sanitizer ?? sanitize;
|
|
516
|
-
this.buffer = new EventBuffer({
|
|
517
|
-
serializer: this.serialize,
|
|
518
|
-
sanitizer: this.sanitize
|
|
519
|
-
});
|
|
520
|
-
this.connection.request.signal.addEventListener(
|
|
521
|
-
"abort",
|
|
522
|
-
this.onDisconnected
|
|
523
|
-
);
|
|
524
|
-
(0, import_node_timers.setImmediate)(this.initialize);
|
|
525
|
-
}
|
|
526
|
-
initialize = () => {
|
|
527
|
-
this.connection.sendHead();
|
|
528
|
-
if (this.connection.url.searchParams.has("padding")) {
|
|
529
|
-
this.buffer.comment(" ".repeat(2049)).dispatch();
|
|
530
|
-
}
|
|
531
|
-
if (this.connection.url.searchParams.has("evs_preamble")) {
|
|
532
|
-
this.buffer.comment(" ".repeat(2056)).dispatch();
|
|
533
|
-
}
|
|
534
|
-
if (this.initialRetry !== null) {
|
|
535
|
-
this.buffer.retry(this.initialRetry).dispatch();
|
|
536
|
-
}
|
|
537
|
-
this.flush();
|
|
538
|
-
if (this.keepAliveInterval !== null) {
|
|
539
|
-
this.keepAliveTimer = setInterval(this.keepAlive, this.keepAliveInterval);
|
|
540
|
-
}
|
|
541
|
-
this.isConnected = true;
|
|
542
|
-
this.emit("connected");
|
|
543
|
-
};
|
|
544
|
-
onDisconnected = () => {
|
|
545
|
-
this.connection.request.signal.removeEventListener(
|
|
546
|
-
"abort",
|
|
547
|
-
this.onDisconnected
|
|
548
|
-
);
|
|
549
|
-
this.connection.cleanup();
|
|
550
|
-
if (this.keepAliveTimer) {
|
|
551
|
-
clearInterval(this.keepAliveTimer);
|
|
552
|
-
}
|
|
553
|
-
this.isConnected = false;
|
|
554
|
-
this.emit("disconnected");
|
|
555
|
-
};
|
|
556
|
-
/**
|
|
557
|
-
* Write an empty comment and flush it to the client.
|
|
558
|
-
*/
|
|
559
|
-
keepAlive = () => {
|
|
560
|
-
this.buffer.comment().dispatch();
|
|
561
|
-
this.flush();
|
|
562
|
-
};
|
|
563
|
-
/**
|
|
564
|
-
* Flush the contents of the internal buffer to the client and clear the buffer.
|
|
565
|
-
*/
|
|
566
|
-
flush = () => {
|
|
567
|
-
const contents = this.buffer.read();
|
|
568
|
-
this.buffer.clear();
|
|
569
|
-
this.connection.sendChunk(contents);
|
|
570
|
-
};
|
|
571
|
-
/**
|
|
572
|
-
* Get a Request object representing the request of the underlying connection this session manages.
|
|
573
|
-
*
|
|
574
|
-
* When using the Fetch API, this will be the original Request object passed to the session constructor.
|
|
575
|
-
*
|
|
576
|
-
* When using the Node HTTP APIs, this will be a new Request object with status code and headers copied from the original request.
|
|
577
|
-
* When the originally given request or response is closed, the abort signal attached to this Request will be triggered.
|
|
578
|
-
*/
|
|
579
|
-
getRequest = () => this.connection.request;
|
|
580
|
-
/**
|
|
581
|
-
* Get a Response object representing the response of the underlying connection this session manages.
|
|
582
|
-
*
|
|
583
|
-
* When using the Fetch API, this will be a new Response object with status code and headers copied from the original response if given.
|
|
584
|
-
* Its body will be a ReadableStream that should begin being consumed for the session to consider itself connected.
|
|
585
|
-
*
|
|
586
|
-
* When using the Node HTTP APIs, this will be a new Response object with status code and headers copied from the original response.
|
|
587
|
-
* Its body will be `null`, as data is instead written to the stream of the originally given response object.
|
|
588
|
-
*/
|
|
589
|
-
getResponse = () => this.connection.response;
|
|
590
|
-
/**
|
|
591
|
-
* Push an event to the client.
|
|
592
|
-
*
|
|
593
|
-
* If no event name is given, the event name is set to `"message"`.
|
|
594
|
-
*
|
|
595
|
-
* 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.
|
|
596
|
-
*
|
|
597
|
-
* If the session has disconnected, an `SseError` will be thrown.
|
|
598
|
-
*
|
|
599
|
-
* Emits the `push` event with the given data, event name and event ID in that order.
|
|
600
|
-
*
|
|
601
|
-
* @param data - Data to write.
|
|
602
|
-
* @param eventName - Event name to write.
|
|
603
|
-
* @param eventId - Event ID to write.
|
|
604
|
-
*/
|
|
605
|
-
push = (data, eventName = "message", eventId = generateId()) => {
|
|
606
|
-
if (!this.isConnected) {
|
|
607
|
-
throw new SseError(
|
|
608
|
-
"Cannot push data to a non-active session. Ensure the session is connected before attempting to push events. If using the Fetch API, the response stream must begin being consumed before the session is considered connected."
|
|
609
|
-
);
|
|
610
|
-
}
|
|
611
|
-
this.buffer.push(data, eventName, eventId);
|
|
612
|
-
this.flush();
|
|
613
|
-
this.lastId = eventId;
|
|
614
|
-
this.emit("push", data, eventName, eventId);
|
|
615
|
-
return this;
|
|
616
|
-
};
|
|
617
|
-
/**
|
|
618
|
-
* Pipe readable stream data as a series of events to the client.
|
|
619
|
-
*
|
|
620
|
-
* This uses the `push` method under the hood.
|
|
621
|
-
*
|
|
622
|
-
* If no event name is given in the `options` object, the event name is set to `"stream"`.
|
|
623
|
-
*
|
|
624
|
-
* @param stream - Readable stream to consume data from.
|
|
625
|
-
* @param options - Options to alter how the stream is flushed to the client.
|
|
626
|
-
*
|
|
627
|
-
* @returns A promise that resolves with `true` or rejects based on the success of the stream write finishing.
|
|
628
|
-
*/
|
|
629
|
-
stream = createPushFromStream(this.push);
|
|
630
|
-
/**
|
|
631
|
-
* Iterate over an iterable and send yielded values as events to the client.
|
|
632
|
-
*
|
|
633
|
-
* This uses the `push` method under the hood.
|
|
634
|
-
*
|
|
635
|
-
* If no event name is given in the `options` object, the event name is set to `"iteration"`.
|
|
636
|
-
*
|
|
637
|
-
* @param iterable - Iterable to consume data from.
|
|
638
|
-
*
|
|
639
|
-
* @returns A promise that resolves once all data has been successfully yielded from the iterable.
|
|
640
|
-
*/
|
|
641
|
-
iterate = createPushFromIterable(this.push);
|
|
642
|
-
/**
|
|
643
|
-
* Batch and send multiple events at once.
|
|
644
|
-
*
|
|
645
|
-
* If given an `EventBuffer` instance, its contents will be sent to the client.
|
|
646
|
-
*
|
|
647
|
-
* If given a callback, it will be passed an instance of `EventBuffer` which uses the same serializer and sanitizer as the session.
|
|
648
|
-
* 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.
|
|
649
|
-
*
|
|
650
|
-
* @param batcher - Event buffer to get contents from, or callback that takes an event buffer to write to.
|
|
651
|
-
*
|
|
652
|
-
* @returns A promise that resolves once all data from the event buffer has been successfully sent to the client.
|
|
653
|
-
*
|
|
654
|
-
* @see EventBuffer
|
|
655
|
-
*/
|
|
656
|
-
batch = async (batcher) => {
|
|
657
|
-
if (batcher instanceof EventBuffer) {
|
|
658
|
-
this.connection.sendChunk(batcher.read());
|
|
659
|
-
} else {
|
|
660
|
-
const buffer = new EventBuffer({
|
|
661
|
-
serializer: this.serialize,
|
|
662
|
-
sanitizer: this.sanitize
|
|
663
|
-
});
|
|
664
|
-
await batcher(buffer);
|
|
665
|
-
this.connection.sendChunk(buffer.read());
|
|
666
|
-
}
|
|
667
|
-
};
|
|
668
|
-
};
|
|
669
|
-
|
|
670
|
-
// src/createSession.ts
|
|
671
|
-
function createSession(req, res, options) {
|
|
672
|
-
return new Promise((resolve) => {
|
|
673
|
-
const session = new Session(req, res, options);
|
|
674
|
-
if (req instanceof Request) {
|
|
675
|
-
resolve(session);
|
|
676
|
-
} else {
|
|
677
|
-
session.once("connected", () => {
|
|
678
|
-
resolve(session);
|
|
679
|
-
});
|
|
680
|
-
}
|
|
681
|
-
});
|
|
682
|
-
}
|
|
683
|
-
|
|
684
|
-
// src/createResponse.ts
|
|
685
|
-
function createResponse(request, response, options, callback) {
|
|
686
|
-
const args = [request, response, options, callback];
|
|
687
|
-
let givenCallback;
|
|
688
|
-
for (let index = args.length - 1; index >= 0; --index) {
|
|
689
|
-
const arg = args.pop();
|
|
690
|
-
if (arg) {
|
|
691
|
-
givenCallback = arg;
|
|
692
|
-
break;
|
|
693
|
-
}
|
|
694
|
-
}
|
|
695
|
-
if (typeof givenCallback !== "function") {
|
|
696
|
-
throw new SseError(
|
|
697
|
-
"Last argument given to createResponse must be a callback function."
|
|
698
|
-
);
|
|
699
|
-
}
|
|
700
|
-
const session = new Session(...args);
|
|
701
|
-
session.once("connected", () => {
|
|
702
|
-
givenCallback(session);
|
|
703
|
-
});
|
|
704
|
-
return session.getResponse();
|
|
705
|
-
}
|
|
706
|
-
|
|
707
|
-
// src/Channel.ts
|
|
708
|
-
var Channel = class extends TypedEmitter {
|
|
709
|
-
/**
|
|
710
|
-
* Custom state for this channel.
|
|
711
|
-
*
|
|
712
|
-
* Use this object to safely store information related to the channel.
|
|
713
|
-
*/
|
|
714
|
-
state;
|
|
715
|
-
sessions = /* @__PURE__ */ new Set();
|
|
716
|
-
constructor(options = {}) {
|
|
717
|
-
super();
|
|
718
|
-
this.state = options.state ?? {};
|
|
719
|
-
}
|
|
720
|
-
/**
|
|
721
|
-
* List of the currently active sessions subscribed to this channel.
|
|
722
|
-
*/
|
|
723
|
-
get activeSessions() {
|
|
724
|
-
return Array.from(this.sessions);
|
|
725
|
-
}
|
|
726
|
-
/**
|
|
727
|
-
* Number of sessions subscribed to this channel.
|
|
728
|
-
*/
|
|
729
|
-
get sessionCount() {
|
|
730
|
-
return this.sessions.size;
|
|
731
|
-
}
|
|
732
|
-
/**
|
|
733
|
-
* Register a session so that it can start receiving events from this channel.
|
|
734
|
-
*
|
|
735
|
-
* If the session was already registered to begin with this method does nothing.
|
|
736
|
-
*
|
|
737
|
-
* @param session - Session to register.
|
|
738
|
-
*/
|
|
739
|
-
register(session) {
|
|
740
|
-
if (this.sessions.has(session)) {
|
|
741
|
-
return this;
|
|
742
|
-
}
|
|
743
|
-
if (!session.isConnected) {
|
|
744
|
-
throw new SseError("Cannot register a non-active session.");
|
|
745
|
-
}
|
|
746
|
-
session.once("disconnected", () => {
|
|
747
|
-
this.emit("session-disconnected", session);
|
|
748
|
-
this.deregister(session);
|
|
749
|
-
});
|
|
750
|
-
this.sessions.add(session);
|
|
751
|
-
this.emit("session-registered", session);
|
|
752
|
-
return this;
|
|
753
|
-
}
|
|
754
|
-
/**
|
|
755
|
-
* Deregister a session so that it no longer receives events from this channel.
|
|
756
|
-
*
|
|
757
|
-
* If the session was not registered to begin with this method does nothing.
|
|
758
|
-
*
|
|
759
|
-
* @param session - Session to deregister.
|
|
760
|
-
*/
|
|
761
|
-
deregister(session) {
|
|
762
|
-
if (!this.sessions.has(session)) {
|
|
763
|
-
return this;
|
|
764
|
-
}
|
|
765
|
-
this.sessions.delete(session);
|
|
766
|
-
this.emit("session-deregistered", session);
|
|
767
|
-
return this;
|
|
768
|
-
}
|
|
769
|
-
/**
|
|
770
|
-
* Broadcast an event to every active session registered with this channel.
|
|
771
|
-
*
|
|
772
|
-
* Under the hood this calls the `push` method on every active session.
|
|
773
|
-
*
|
|
774
|
-
* If no event name is given, the event name is set to `"message"`.
|
|
775
|
-
*
|
|
776
|
-
* Note that the broadcasted event will have the same ID across all receiving sessions instead of generating a unique ID for each.
|
|
777
|
-
*
|
|
778
|
-
* @param data - Data to write.
|
|
779
|
-
* @param eventName - Event name to write.
|
|
780
|
-
*/
|
|
781
|
-
broadcast = (data, eventName = "message", options = {}) => {
|
|
782
|
-
const eventId = options.eventId ?? generateId();
|
|
783
|
-
const sessions = options.filter ? this.activeSessions.filter(options.filter) : this.sessions;
|
|
784
|
-
for (const session of sessions) {
|
|
785
|
-
session.push(data, eventName, eventId);
|
|
786
|
-
}
|
|
787
|
-
this.emit("broadcast", data, eventName, eventId);
|
|
788
|
-
return this;
|
|
789
|
-
};
|
|
790
|
-
};
|
|
791
|
-
|
|
792
|
-
// src/createChannel.ts
|
|
793
|
-
var createChannel = (...args) => new Channel(...args);
|
|
794
|
-
|
|
795
|
-
// src/createEventBuffer.ts
|
|
796
|
-
var createEventBuffer = (...args) => new EventBuffer(...args);
|
|
797
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
798
|
-
0 && (module.exports = {
|
|
799
|
-
Channel,
|
|
800
|
-
EventBuffer,
|
|
801
|
-
Session,
|
|
802
|
-
SseError,
|
|
803
|
-
createChannel,
|
|
804
|
-
createEventBuffer,
|
|
805
|
-
createResponse,
|
|
806
|
-
createSession
|
|
807
|
-
});
|