crossws 0.3.0 → 0.3.2

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.
@@ -1,619 +1,18 @@
1
- import { M as Message, P as Peer, t as toBufferLike } from '../shared/crossws.DTY7a69w.mjs';
2
- import { d as defineWebSocketAdapter, a as adapterUtils, A as AdapterHookable } from '../shared/crossws.B4sHId41.mjs';
1
+ import { M as Message, P as Peer, t as toBufferLike } from '../shared/crossws.DLRVRjZs.mjs';
2
+ import { d as defineWebSocketAdapter, a as adapterUtils, A as AdapterHookable } from '../shared/crossws.BcEs6ZHK.mjs';
3
3
  import { W as WSError } from '../shared/crossws.By9qWDAI.mjs';
4
4
  import 'stream';
5
- import { v as validationExports, g as getDefaultExportFromCjs, e as extension$1, p as permessageDeflate, w as websocket, c as constants } from '../shared/crossws.YgHWLi0G.mjs';
6
- import require$$0 from 'events';
7
- import require$$2 from 'http';
8
- import require$$1 from 'crypto';
5
+ import { _ as _WebSocketServer } from '../shared/crossws.DelSCW9g.mjs';
9
6
  import 'uncrypto';
7
+ import 'events';
8
+ import 'http';
9
+ import 'crypto';
10
+ import 'buffer';
11
+ import 'zlib';
10
12
  import 'https';
11
13
  import 'net';
12
14
  import 'tls';
13
15
  import 'url';
14
- import 'zlib';
15
- import 'buffer';
16
-
17
- const { tokenChars } = validationExports;
18
-
19
- /**
20
- * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
21
- *
22
- * @param {String} header The field value of the header
23
- * @return {Set} The subprotocol names
24
- * @public
25
- */
26
- function parse(header) {
27
- const protocols = new Set();
28
- let start = -1;
29
- let end = -1;
30
- let i = 0;
31
-
32
- for (i; i < header.length; i++) {
33
- const code = header.charCodeAt(i);
34
-
35
- if (end === -1 && tokenChars[code] === 1) {
36
- if (start === -1) start = i;
37
- } else if (
38
- i !== 0 &&
39
- (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
40
- ) {
41
- if (end === -1 && start !== -1) end = i;
42
- } else if (code === 0x2c /* ',' */) {
43
- if (start === -1) {
44
- throw new SyntaxError(`Unexpected character at index ${i}`);
45
- }
46
-
47
- if (end === -1) end = i;
48
-
49
- const protocol = header.slice(start, end);
50
-
51
- if (protocols.has(protocol)) {
52
- throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
53
- }
54
-
55
- protocols.add(protocol);
56
- start = end = -1;
57
- } else {
58
- throw new SyntaxError(`Unexpected character at index ${i}`);
59
- }
60
- }
61
-
62
- if (start === -1 || end !== -1) {
63
- throw new SyntaxError('Unexpected end of input');
64
- }
65
-
66
- const protocol = header.slice(start, i);
67
-
68
- if (protocols.has(protocol)) {
69
- throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
70
- }
71
-
72
- protocols.add(protocol);
73
- return protocols;
74
- }
75
-
76
- var subprotocol$1 = { parse };
77
-
78
- /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */
79
-
80
- const EventEmitter = require$$0;
81
- const http = require$$2;
82
- const { createHash } = require$$1;
83
-
84
- const extension = extension$1;
85
- const PerMessageDeflate = permessageDeflate;
86
- const subprotocol = subprotocol$1;
87
- const WebSocket = websocket;
88
- const { GUID, kWebSocket } = constants;
89
-
90
- const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
91
-
92
- const RUNNING = 0;
93
- const CLOSING = 1;
94
- const CLOSED = 2;
95
-
96
- /**
97
- * Class representing a WebSocket server.
98
- *
99
- * @extends EventEmitter
100
- */
101
- class WebSocketServer extends EventEmitter {
102
- /**
103
- * Create a `WebSocketServer` instance.
104
- *
105
- * @param {Object} options Configuration options
106
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
107
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
108
- * multiple times in the same tick
109
- * @param {Boolean} [options.autoPong=true] Specifies whether or not to
110
- * automatically send a pong in response to a ping
111
- * @param {Number} [options.backlog=511] The maximum length of the queue of
112
- * pending connections
113
- * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
114
- * track clients
115
- * @param {Function} [options.handleProtocols] A hook to handle protocols
116
- * @param {String} [options.host] The hostname where to bind the server
117
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
118
- * size
119
- * @param {Boolean} [options.noServer=false] Enable no server mode
120
- * @param {String} [options.path] Accept only connections matching this path
121
- * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
122
- * permessage-deflate
123
- * @param {Number} [options.port] The port where to bind the server
124
- * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
125
- * server to use
126
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
127
- * not to skip UTF-8 validation for text and close messages
128
- * @param {Function} [options.verifyClient] A hook to reject connections
129
- * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
130
- * class to use. It must be the `WebSocket` class or class that extends it
131
- * @param {Function} [callback] A listener for the `listening` event
132
- */
133
- constructor(options, callback) {
134
- super();
135
-
136
- options = {
137
- allowSynchronousEvents: true,
138
- autoPong: true,
139
- maxPayload: 100 * 1024 * 1024,
140
- skipUTF8Validation: false,
141
- perMessageDeflate: false,
142
- handleProtocols: null,
143
- clientTracking: true,
144
- verifyClient: null,
145
- noServer: false,
146
- backlog: null, // use default (511 as implemented in net.js)
147
- server: null,
148
- host: null,
149
- path: null,
150
- port: null,
151
- WebSocket,
152
- ...options
153
- };
154
-
155
- if (
156
- (options.port == null && !options.server && !options.noServer) ||
157
- (options.port != null && (options.server || options.noServer)) ||
158
- (options.server && options.noServer)
159
- ) {
160
- throw new TypeError(
161
- 'One and only one of the "port", "server", or "noServer" options ' +
162
- 'must be specified'
163
- );
164
- }
165
-
166
- if (options.port != null) {
167
- this._server = http.createServer((req, res) => {
168
- const body = http.STATUS_CODES[426];
169
-
170
- res.writeHead(426, {
171
- 'Content-Length': body.length,
172
- 'Content-Type': 'text/plain'
173
- });
174
- res.end(body);
175
- });
176
- this._server.listen(
177
- options.port,
178
- options.host,
179
- options.backlog,
180
- callback
181
- );
182
- } else if (options.server) {
183
- this._server = options.server;
184
- }
185
-
186
- if (this._server) {
187
- const emitConnection = this.emit.bind(this, 'connection');
188
-
189
- this._removeListeners = addListeners(this._server, {
190
- listening: this.emit.bind(this, 'listening'),
191
- error: this.emit.bind(this, 'error'),
192
- upgrade: (req, socket, head) => {
193
- this.handleUpgrade(req, socket, head, emitConnection);
194
- }
195
- });
196
- }
197
-
198
- if (options.perMessageDeflate === true) options.perMessageDeflate = {};
199
- if (options.clientTracking) {
200
- this.clients = new Set();
201
- this._shouldEmitClose = false;
202
- }
203
-
204
- this.options = options;
205
- this._state = RUNNING;
206
- }
207
-
208
- /**
209
- * Returns the bound address, the address family name, and port of the server
210
- * as reported by the operating system if listening on an IP socket.
211
- * If the server is listening on a pipe or UNIX domain socket, the name is
212
- * returned as a string.
213
- *
214
- * @return {(Object|String|null)} The address of the server
215
- * @public
216
- */
217
- address() {
218
- if (this.options.noServer) {
219
- throw new Error('The server is operating in "noServer" mode');
220
- }
221
-
222
- if (!this._server) return null;
223
- return this._server.address();
224
- }
225
-
226
- /**
227
- * Stop the server from accepting new connections and emit the `'close'` event
228
- * when all existing connections are closed.
229
- *
230
- * @param {Function} [cb] A one-time listener for the `'close'` event
231
- * @public
232
- */
233
- close(cb) {
234
- if (this._state === CLOSED) {
235
- if (cb) {
236
- this.once('close', () => {
237
- cb(new Error('The server is not running'));
238
- });
239
- }
240
-
241
- process.nextTick(emitClose, this);
242
- return;
243
- }
244
-
245
- if (cb) this.once('close', cb);
246
-
247
- if (this._state === CLOSING) return;
248
- this._state = CLOSING;
249
-
250
- if (this.options.noServer || this.options.server) {
251
- if (this._server) {
252
- this._removeListeners();
253
- this._removeListeners = this._server = null;
254
- }
255
-
256
- if (this.clients) {
257
- if (!this.clients.size) {
258
- process.nextTick(emitClose, this);
259
- } else {
260
- this._shouldEmitClose = true;
261
- }
262
- } else {
263
- process.nextTick(emitClose, this);
264
- }
265
- } else {
266
- const server = this._server;
267
-
268
- this._removeListeners();
269
- this._removeListeners = this._server = null;
270
-
271
- //
272
- // The HTTP/S server was created internally. Close it, and rely on its
273
- // `'close'` event.
274
- //
275
- server.close(() => {
276
- emitClose(this);
277
- });
278
- }
279
- }
280
-
281
- /**
282
- * See if a given request should be handled by this server instance.
283
- *
284
- * @param {http.IncomingMessage} req Request object to inspect
285
- * @return {Boolean} `true` if the request is valid, else `false`
286
- * @public
287
- */
288
- shouldHandle(req) {
289
- if (this.options.path) {
290
- const index = req.url.indexOf('?');
291
- const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
292
-
293
- if (pathname !== this.options.path) return false;
294
- }
295
-
296
- return true;
297
- }
298
-
299
- /**
300
- * Handle a HTTP Upgrade request.
301
- *
302
- * @param {http.IncomingMessage} req The request object
303
- * @param {Duplex} socket The network socket between the server and client
304
- * @param {Buffer} head The first packet of the upgraded stream
305
- * @param {Function} cb Callback
306
- * @public
307
- */
308
- handleUpgrade(req, socket, head, cb) {
309
- socket.on('error', socketOnError);
310
-
311
- const key = req.headers['sec-websocket-key'];
312
- const upgrade = req.headers.upgrade;
313
- const version = +req.headers['sec-websocket-version'];
314
-
315
- if (req.method !== 'GET') {
316
- const message = 'Invalid HTTP method';
317
- abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
318
- return;
319
- }
320
-
321
- if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
322
- const message = 'Invalid Upgrade header';
323
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
324
- return;
325
- }
326
-
327
- if (key === undefined || !keyRegex.test(key)) {
328
- const message = 'Missing or invalid Sec-WebSocket-Key header';
329
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
330
- return;
331
- }
332
-
333
- if (version !== 8 && version !== 13) {
334
- const message = 'Missing or invalid Sec-WebSocket-Version header';
335
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
336
- return;
337
- }
338
-
339
- if (!this.shouldHandle(req)) {
340
- abortHandshake(socket, 400);
341
- return;
342
- }
343
-
344
- const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
345
- let protocols = new Set();
346
-
347
- if (secWebSocketProtocol !== undefined) {
348
- try {
349
- protocols = subprotocol.parse(secWebSocketProtocol);
350
- } catch (err) {
351
- const message = 'Invalid Sec-WebSocket-Protocol header';
352
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
353
- return;
354
- }
355
- }
356
-
357
- const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
358
- const extensions = {};
359
-
360
- if (
361
- this.options.perMessageDeflate &&
362
- secWebSocketExtensions !== undefined
363
- ) {
364
- const perMessageDeflate = new PerMessageDeflate(
365
- this.options.perMessageDeflate,
366
- true,
367
- this.options.maxPayload
368
- );
369
-
370
- try {
371
- const offers = extension.parse(secWebSocketExtensions);
372
-
373
- if (offers[PerMessageDeflate.extensionName]) {
374
- perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
375
- extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
376
- }
377
- } catch (err) {
378
- const message =
379
- 'Invalid or unacceptable Sec-WebSocket-Extensions header';
380
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
381
- return;
382
- }
383
- }
384
-
385
- //
386
- // Optionally call external client verification handler.
387
- //
388
- if (this.options.verifyClient) {
389
- const info = {
390
- origin:
391
- req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
392
- secure: !!(req.socket.authorized || req.socket.encrypted),
393
- req
394
- };
395
-
396
- if (this.options.verifyClient.length === 2) {
397
- this.options.verifyClient(info, (verified, code, message, headers) => {
398
- if (!verified) {
399
- return abortHandshake(socket, code || 401, message, headers);
400
- }
401
-
402
- this.completeUpgrade(
403
- extensions,
404
- key,
405
- protocols,
406
- req,
407
- socket,
408
- head,
409
- cb
410
- );
411
- });
412
- return;
413
- }
414
-
415
- if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
416
- }
417
-
418
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
419
- }
420
-
421
- /**
422
- * Upgrade the connection to WebSocket.
423
- *
424
- * @param {Object} extensions The accepted extensions
425
- * @param {String} key The value of the `Sec-WebSocket-Key` header
426
- * @param {Set} protocols The subprotocols
427
- * @param {http.IncomingMessage} req The request object
428
- * @param {Duplex} socket The network socket between the server and client
429
- * @param {Buffer} head The first packet of the upgraded stream
430
- * @param {Function} cb Callback
431
- * @throws {Error} If called more than once with the same socket
432
- * @private
433
- */
434
- completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
435
- //
436
- // Destroy the socket if the client has already sent a FIN packet.
437
- //
438
- if (!socket.readable || !socket.writable) return socket.destroy();
439
-
440
- if (socket[kWebSocket]) {
441
- throw new Error(
442
- 'server.handleUpgrade() was called more than once with the same ' +
443
- 'socket, possibly due to a misconfiguration'
444
- );
445
- }
446
-
447
- if (this._state > RUNNING) return abortHandshake(socket, 503);
448
-
449
- const digest = createHash('sha1')
450
- .update(key + GUID)
451
- .digest('base64');
452
-
453
- const headers = [
454
- 'HTTP/1.1 101 Switching Protocols',
455
- 'Upgrade: websocket',
456
- 'Connection: Upgrade',
457
- `Sec-WebSocket-Accept: ${digest}`
458
- ];
459
-
460
- const ws = new this.options.WebSocket(null, undefined, this.options);
461
-
462
- if (protocols.size) {
463
- //
464
- // Optionally call external protocol selection handler.
465
- //
466
- const protocol = this.options.handleProtocols
467
- ? this.options.handleProtocols(protocols, req)
468
- : protocols.values().next().value;
469
-
470
- if (protocol) {
471
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
472
- ws._protocol = protocol;
473
- }
474
- }
475
-
476
- if (extensions[PerMessageDeflate.extensionName]) {
477
- const params = extensions[PerMessageDeflate.extensionName].params;
478
- const value = extension.format({
479
- [PerMessageDeflate.extensionName]: [params]
480
- });
481
- headers.push(`Sec-WebSocket-Extensions: ${value}`);
482
- ws._extensions = extensions;
483
- }
484
-
485
- //
486
- // Allow external modification/inspection of handshake headers.
487
- //
488
- this.emit('headers', headers, req);
489
-
490
- socket.write(headers.concat('\r\n').join('\r\n'));
491
- socket.removeListener('error', socketOnError);
492
-
493
- ws.setSocket(socket, head, {
494
- allowSynchronousEvents: this.options.allowSynchronousEvents,
495
- maxPayload: this.options.maxPayload,
496
- skipUTF8Validation: this.options.skipUTF8Validation
497
- });
498
-
499
- if (this.clients) {
500
- this.clients.add(ws);
501
- ws.on('close', () => {
502
- this.clients.delete(ws);
503
-
504
- if (this._shouldEmitClose && !this.clients.size) {
505
- process.nextTick(emitClose, this);
506
- }
507
- });
508
- }
509
-
510
- cb(ws, req);
511
- }
512
- }
513
-
514
- var websocketServer = WebSocketServer;
515
-
516
- /**
517
- * Add event listeners on an `EventEmitter` using a map of <event, listener>
518
- * pairs.
519
- *
520
- * @param {EventEmitter} server The event emitter
521
- * @param {Object.<String, Function>} map The listeners to add
522
- * @return {Function} A function that will remove the added listeners when
523
- * called
524
- * @private
525
- */
526
- function addListeners(server, map) {
527
- for (const event of Object.keys(map)) server.on(event, map[event]);
528
-
529
- return function removeListeners() {
530
- for (const event of Object.keys(map)) {
531
- server.removeListener(event, map[event]);
532
- }
533
- };
534
- }
535
-
536
- /**
537
- * Emit a `'close'` event on an `EventEmitter`.
538
- *
539
- * @param {EventEmitter} server The event emitter
540
- * @private
541
- */
542
- function emitClose(server) {
543
- server._state = CLOSED;
544
- server.emit('close');
545
- }
546
-
547
- /**
548
- * Handle socket errors.
549
- *
550
- * @private
551
- */
552
- function socketOnError() {
553
- this.destroy();
554
- }
555
-
556
- /**
557
- * Close the connection when preconditions are not fulfilled.
558
- *
559
- * @param {Duplex} socket The socket of the upgrade request
560
- * @param {Number} code The HTTP response status code
561
- * @param {String} [message] The HTTP response body
562
- * @param {Object} [headers] Additional HTTP response headers
563
- * @private
564
- */
565
- function abortHandshake(socket, code, message, headers) {
566
- //
567
- // The socket is writable unless the user destroyed or ended it before calling
568
- // `server.handleUpgrade()` or in the `verifyClient` function, which is a user
569
- // error. Handling this does not make much sense as the worst that can happen
570
- // is that some of the data written by the user might be discarded due to the
571
- // call to `socket.end()` below, which triggers an `'error'` event that in
572
- // turn causes the socket to be destroyed.
573
- //
574
- message = message || http.STATUS_CODES[code];
575
- headers = {
576
- Connection: 'close',
577
- 'Content-Type': 'text/html',
578
- 'Content-Length': Buffer.byteLength(message),
579
- ...headers
580
- };
581
-
582
- socket.once('finish', socket.destroy);
583
-
584
- socket.end(
585
- `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
586
- Object.keys(headers)
587
- .map((h) => `${h}: ${headers[h]}`)
588
- .join('\r\n') +
589
- '\r\n\r\n' +
590
- message
591
- );
592
- }
593
-
594
- /**
595
- * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
596
- * one listener for it, otherwise call `abortHandshake()`.
597
- *
598
- * @param {WebSocketServer} server The WebSocket server
599
- * @param {http.IncomingMessage} req The request object
600
- * @param {Duplex} socket The socket of the upgrade request
601
- * @param {Number} code The HTTP response status code
602
- * @param {String} message The HTTP response body
603
- * @private
604
- */
605
- function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
606
- if (server.listenerCount('wsClientError')) {
607
- const err = new Error(message);
608
- Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
609
-
610
- server.emit('wsClientError', err, socket, req);
611
- } else {
612
- abortHandshake(socket, code, message);
613
- }
614
- }
615
-
616
- const _WebSocketServer = /*@__PURE__*/getDefaultExportFromCjs(websocketServer);
617
16
 
618
17
  const node = defineWebSocketAdapter(
619
18
  (options = {}) => {
@@ -658,12 +57,13 @@ const node = defineWebSocketAdapter(
658
57
  ...adapterUtils(peers),
659
58
  handleUpgrade: async (nodeReq, socket, head) => {
660
59
  const request = new NodeReqProxy(nodeReq);
661
- const res = await hooks.callHook("upgrade", request);
662
- if (res instanceof Response) {
663
- return sendResponse(socket, res);
60
+ const { upgradeHeaders, endResponse, context } = await hooks.upgrade(request);
61
+ if (endResponse) {
62
+ return sendResponse(socket, endResponse);
664
63
  }
665
64
  nodeReq._request = request;
666
- nodeReq._upgradeHeaders = res?.headers;
65
+ nodeReq._upgradeHeaders = upgradeHeaders;
66
+ nodeReq._context = context;
667
67
  wss.handleUpgrade(nodeReq, socket, head, (ws) => {
668
68
  wss.emit("connection", ws, nodeReq);
669
69
  });
@@ -680,6 +80,9 @@ class NodePeer extends Peer {
680
80
  get remoteAddress() {
681
81
  return this._internal.nodeReq.socket?.remoteAddress;
682
82
  }
83
+ get context() {
84
+ return this._internal.nodeReq._context;
85
+ }
683
86
  send(data, options) {
684
87
  const dataBuff = toBufferLike(data);
685
88
  const isBinary = typeof data !== "string";
@@ -1,17 +1,17 @@
1
- import { M as Message, P as Peer, a as toString } from '../shared/crossws.DTY7a69w.mjs';
2
- import { d as defineWebSocketAdapter, a as adapterUtils, A as AdapterHookable } from '../shared/crossws.B4sHId41.mjs';
1
+ import { M as Message, P as Peer, a as toString } from '../shared/crossws.DLRVRjZs.mjs';
2
+ import { d as defineWebSocketAdapter, a as adapterUtils, A as AdapterHookable } from '../shared/crossws.BcEs6ZHK.mjs';
3
3
  import 'uncrypto';
4
4
 
5
5
  const sse = defineWebSocketAdapter((opts = {}) => {
6
6
  const hooks = new AdapterHookable(opts);
7
7
  const peers = /* @__PURE__ */ new Set();
8
- const peersMap = opts.bidir ? /* @__PURE__ */ new Map() : void 0;
8
+ const peersMap = opts.bidir ? /* @__PURE__ */ new Map() : undefined;
9
9
  return {
10
10
  ...adapterUtils(peers),
11
11
  fetch: async (request) => {
12
- const _res = await hooks.callHook("upgrade", request);
13
- if (_res instanceof Response) {
14
- return _res;
12
+ const { upgradeHeaders, endResponse, context } = await hooks.upgrade(request);
13
+ if (endResponse) {
14
+ return endResponse;
15
15
  }
16
16
  let peer;
17
17
  if (opts.bidir && request.body && request.headers.has("x-crossws-id")) {
@@ -37,7 +37,8 @@ const sse = defineWebSocketAdapter((opts = {}) => {
37
37
  peersMap,
38
38
  request,
39
39
  hooks,
40
- ws
40
+ ws,
41
+ context
41
42
  });
42
43
  peers.add(peer);
43
44
  if (opts.bidir) {
@@ -53,13 +54,13 @@ const sse = defineWebSocketAdapter((opts = {}) => {
53
54
  if (opts.bidir) {
54
55
  headers["x-crossws-id"] = peer.id;
55
56
  }
56
- if (_res?.headers) {
57
+ if (upgradeHeaders) {
57
58
  headers = new Headers(headers);
58
- for (const [key, value] of new Headers(_res.headers)) {
59
+ for (const [key, value] of new Headers(upgradeHeaders)) {
59
60
  headers.set(key, value);
60
61
  }
61
62
  }
62
- return new Response(peer._sseStream, { ..._res, headers });
63
+ return new Response(peer._sseStream, { headers });
63
64
  }
64
65
  };
65
66
  });