@digipair/skill-sse 0.116.2 → 0.116.4

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.
Files changed (2) hide show
  1. package/dist/index.esm.js +500 -232
  2. package/package.json +2 -2
package/dist/index.esm.js CHANGED
@@ -1,6 +1,9 @@
1
- import { ServerResponse } from 'http';
2
- import { randomUUID, randomBytes } from 'crypto';
3
- import { EventEmitter } from 'events';
1
+ import { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { Http2ServerRequest, Http2ServerResponse } from 'node:http2';
3
+ import { setImmediate } from 'node:timers';
4
+ import { Readable } from 'node:stream';
5
+ import { randomUUID, randomBytes } from 'node:crypto';
6
+ import { EventEmitter } from 'node:events';
4
7
 
5
8
  // src/Session.ts
6
9
  function _array_like_to_array$8(arr, len) {
@@ -216,6 +219,21 @@ function _non_iterable_rest$6() {
216
219
  function _non_iterable_spread$7() {
217
220
  throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
218
221
  }
222
+ function _object_spread$3(target) {
223
+ for(var i = 1; i < arguments.length; i++){
224
+ var source = arguments[i] != null ? arguments[i] : {};
225
+ var ownKeys = Object.keys(source);
226
+ if (typeof Object.getOwnPropertySymbols === "function") {
227
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
228
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
229
+ }));
230
+ }
231
+ ownKeys.forEach(function(key) {
232
+ _define_property$5(target, key, source[key]);
233
+ });
234
+ }
235
+ return target;
236
+ }
219
237
  function _possible_constructor_return$l(self, call) {
220
238
  if (call && (_type_of$D(call) === "object" || typeof call === "function")) {
221
239
  return call;
@@ -399,76 +417,7 @@ function _ts_generator(thisArg, body) {
399
417
  };
400
418
  }
401
419
  }
402
- // src/lib/serialize.ts
403
- var serialize = function(data) {
404
- return JSON.stringify(data);
405
- };
406
- // src/lib/sanitize.ts
407
- var newlineVariantsRegex = /(\r\n|\r|\n)/g;
408
- var newlineTrailingRegex = /\n+$/g;
409
- var sanitize = function(text) {
410
- var sanitized = text;
411
- sanitized = sanitized.replace(newlineVariantsRegex, "\n");
412
- sanitized = sanitized.replace(newlineTrailingRegex, "");
413
- return sanitized;
414
- };
415
- var generateId;
416
- if (randomUUID) {
417
- generateId = function() {
418
- return randomUUID();
419
- };
420
- } else {
421
- generateId = function() {
422
- return randomBytes(4).toString("hex");
423
- };
424
- }
425
- // src/lib/createPushFromStream.ts
426
- var createPushFromStream = function(push) {
427
- return function() {
428
- var _ref = _async_to_generator(function(stream) {
429
- var options, _options_eventName, eventName;
430
- var _arguments = arguments;
431
- return _ts_generator(this, function(_state) {
432
- switch(_state.label){
433
- case 0:
434
- options = _arguments.length > 1 && _arguments[1] !== void 0 ? _arguments[1] : {};
435
- _options_eventName = options.eventName, eventName = _options_eventName === void 0 ? "stream" : _options_eventName;
436
- return [
437
- 4,
438
- new Promise(function(resolve, reject) {
439
- stream.on("data", function(chunk) {
440
- var data;
441
- if (Buffer.isBuffer(chunk)) {
442
- data = chunk.toString();
443
- } else {
444
- data = chunk;
445
- }
446
- push(data, eventName);
447
- });
448
- stream.once("end", function() {
449
- return resolve(true);
450
- });
451
- stream.once("close", function() {
452
- return resolve(true);
453
- });
454
- stream.once("error", function(err) {
455
- return reject(err);
456
- });
457
- })
458
- ];
459
- case 1:
460
- return [
461
- 2,
462
- _state.sent()
463
- ];
464
- }
465
- });
466
- });
467
- return function(stream) {
468
- return _ref.apply(this, arguments);
469
- };
470
- }();
471
- };
420
+ var __FetchConnection;
472
421
  // src/lib/createPushFromIterable.ts
473
422
  var createPushFromIterable = function(push) {
474
423
  return function() {
@@ -570,6 +519,167 @@ var createPushFromIterable = function(push) {
570
519
  };
571
520
  }();
572
521
  };
522
+ var createPushFromStream = function(push) {
523
+ return function() {
524
+ var _ref = _async_to_generator(function(stream) {
525
+ var options, _options_eventName, eventName, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, chunk, err;
526
+ var _arguments = arguments;
527
+ return _ts_generator(this, function(_state) {
528
+ switch(_state.label){
529
+ case 0:
530
+ options = _arguments.length > 1 && _arguments[1] !== void 0 ? _arguments[1] : {};
531
+ _options_eventName = options.eventName, eventName = _options_eventName === void 0 ? "stream" : _options_eventName;
532
+ if (!_instanceof$k(stream, Readable)) return [
533
+ 3,
534
+ 2
535
+ ];
536
+ return [
537
+ 4,
538
+ new Promise(function(resolve, reject) {
539
+ stream.on("data", function(chunk) {
540
+ var data;
541
+ if (Buffer.isBuffer(chunk)) {
542
+ data = chunk.toString();
543
+ } else {
544
+ data = chunk;
545
+ }
546
+ push(data, eventName);
547
+ });
548
+ stream.once("end", function() {
549
+ return resolve(true);
550
+ });
551
+ stream.once("close", function() {
552
+ return resolve(true);
553
+ });
554
+ stream.once("error", function(err) {
555
+ return reject(err);
556
+ });
557
+ })
558
+ ];
559
+ case 1:
560
+ return [
561
+ 2,
562
+ _state.sent()
563
+ ];
564
+ case 2:
565
+ _iteratorAbruptCompletion = false, _didIteratorError = false;
566
+ _state.label = 3;
567
+ case 3:
568
+ _state.trys.push([
569
+ 3,
570
+ 8,
571
+ 9,
572
+ 14
573
+ ]);
574
+ _iterator = _async_iterator(stream);
575
+ _state.label = 4;
576
+ case 4:
577
+ return [
578
+ 4,
579
+ _iterator.next()
580
+ ];
581
+ case 5:
582
+ if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
583
+ 3,
584
+ 7
585
+ ];
586
+ _value = _step.value;
587
+ chunk = _value;
588
+ if (Buffer.isBuffer(chunk)) {
589
+ push(chunk.toString(), eventName);
590
+ } else {
591
+ push(chunk, eventName);
592
+ }
593
+ _state.label = 6;
594
+ case 6:
595
+ _iteratorAbruptCompletion = false;
596
+ return [
597
+ 3,
598
+ 4
599
+ ];
600
+ case 7:
601
+ return [
602
+ 3,
603
+ 14
604
+ ];
605
+ case 8:
606
+ err = _state.sent();
607
+ _didIteratorError = true;
608
+ _iteratorError = err;
609
+ return [
610
+ 3,
611
+ 14
612
+ ];
613
+ case 9:
614
+ _state.trys.push([
615
+ 9,
616
+ ,
617
+ 12,
618
+ 13
619
+ ]);
620
+ if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
621
+ 3,
622
+ 11
623
+ ];
624
+ return [
625
+ 4,
626
+ _iterator.return()
627
+ ];
628
+ case 10:
629
+ _state.sent();
630
+ _state.label = 11;
631
+ case 11:
632
+ return [
633
+ 3,
634
+ 13
635
+ ];
636
+ case 12:
637
+ if (_didIteratorError) {
638
+ throw _iteratorError;
639
+ }
640
+ return [
641
+ 7
642
+ ];
643
+ case 13:
644
+ return [
645
+ 7
646
+ ];
647
+ case 14:
648
+ return [
649
+ 2,
650
+ true
651
+ ];
652
+ }
653
+ });
654
+ });
655
+ return function(stream) {
656
+ return _ref.apply(this, arguments);
657
+ };
658
+ }();
659
+ };
660
+ var generateId;
661
+ if (randomUUID) {
662
+ generateId = function() {
663
+ return randomUUID();
664
+ };
665
+ } else {
666
+ generateId = function() {
667
+ return randomBytes(4).toString("hex");
668
+ };
669
+ }
670
+ // src/lib/sanitize.ts
671
+ var newlineVariantsRegex = /(\r\n|\r|\n)/g;
672
+ var newlineTrailingRegex = /\n+$/g;
673
+ var sanitize = function(text) {
674
+ var sanitized = text;
675
+ sanitized = sanitized.replace(newlineVariantsRegex, "\n");
676
+ sanitized = sanitized.replace(newlineTrailingRegex, "");
677
+ return sanitized;
678
+ };
679
+ // src/lib/serialize.ts
680
+ var serialize = function(data) {
681
+ return JSON.stringify(data);
682
+ };
573
683
  // src/EventBuffer.ts
574
684
  var EventBuffer = /*#__PURE__*/ function() {
575
685
  function EventBuffer() {
@@ -662,7 +772,7 @@ var EventBuffer = /*#__PURE__*/ function() {
662
772
  * @param stream - Readable stream to consume data from.
663
773
  * @param options - Event name to use for each event created.
664
774
  *
665
- * @returns A promise that resolves or rejects based on the success of the stream write finishing.
775
+ * @returns A promise that resolves with `true` or rejects based on the success of the stream write finishing.
666
776
  */ _define_property$5(this, "stream", createPushFromStream(this.push));
667
777
  /**
668
778
  * Iterate over an iterable and write yielded values as events into the buffer.
@@ -706,6 +816,221 @@ var EventBuffer = /*#__PURE__*/ function() {
706
816
  ]);
707
817
  return EventBuffer;
708
818
  }();
819
+ // src/lib/applyHeaders.ts
820
+ var applyHeaders = function(from, to) {
821
+ var fromMap = _instanceof$k(from, Headers) ? Object.fromEntries(from) : from;
822
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
823
+ try {
824
+ for(var _iterator = Object.entries(fromMap)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
825
+ var _step_value = _sliced_to_array$6(_step.value, 2), key = _step_value[0], value = _step_value[1];
826
+ if (Array.isArray(value)) {
827
+ to.delete(key);
828
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
829
+ try {
830
+ for(var _iterator1 = value[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
831
+ var item = _step1.value;
832
+ to.append(key, item);
833
+ }
834
+ } catch (err) {
835
+ _didIteratorError1 = true;
836
+ _iteratorError1 = err;
837
+ } finally{
838
+ try {
839
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
840
+ _iterator1.return();
841
+ }
842
+ } finally{
843
+ if (_didIteratorError1) {
844
+ throw _iteratorError1;
845
+ }
846
+ }
847
+ }
848
+ } else if (value === void 0) {
849
+ to.delete(key);
850
+ } else {
851
+ to.set(key, value);
852
+ }
853
+ }
854
+ } catch (err) {
855
+ _didIteratorError = true;
856
+ _iteratorError = err;
857
+ } finally{
858
+ try {
859
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
860
+ _iterator.return();
861
+ }
862
+ } finally{
863
+ if (_didIteratorError) {
864
+ throw _iteratorError;
865
+ }
866
+ }
867
+ }
868
+ };
869
+ // src/lib/constants.ts
870
+ var DEFAULT_REQUEST_HOST = "localhost";
871
+ var DEFAULT_REQUEST_METHOD = "GET";
872
+ var DEFAULT_RESPONSE_CODE = 200;
873
+ var DEFAULT_RESPONSE_HEADERS = {
874
+ "Content-Type": "text/event-stream",
875
+ "Cache-Control": "private, no-cache, no-store, no-transform, must-revalidate, max-age=0",
876
+ Connection: "keep-alive",
877
+ Pragma: "no-cache",
878
+ "X-Accel-Buffering": "no"
879
+ };
880
+ // src/adapters/FetchConnection.ts
881
+ var FetchConnection = (__FetchConnection = function _FetchConnection(request, response) {
882
+ var _this = this;
883
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
884
+ _class_call_check$B(this, _FetchConnection);
885
+ _define_property$5(this, "writer", void 0);
886
+ _define_property$5(this, "url", void 0);
887
+ _define_property$5(this, "request", void 0);
888
+ _define_property$5(this, "response", void 0);
889
+ _define_property$5(this, "sendHead", function() {});
890
+ _define_property$5(this, "sendChunk", function(chunk) {
891
+ var encoded = _FetchConnection.encoder.encode(chunk);
892
+ _this.writer.write(encoded);
893
+ });
894
+ _define_property$5(this, "cleanup", function() {
895
+ _this.writer.close();
896
+ });
897
+ this.url = new URL(request.url);
898
+ this.request = request;
899
+ var _ref = new TransformStream(), readable = _ref.readable, writable = _ref.writable;
900
+ this.writer = writable.getWriter();
901
+ var _options_statusCode, _ref1;
902
+ this.response = new Response(readable, {
903
+ status: (_ref1 = (_options_statusCode = options.statusCode) !== null && _options_statusCode !== void 0 ? _options_statusCode : response === null || response === void 0 ? void 0 : response.status) !== null && _ref1 !== void 0 ? _ref1 : DEFAULT_RESPONSE_CODE,
904
+ headers: DEFAULT_RESPONSE_HEADERS
905
+ });
906
+ if (response) {
907
+ applyHeaders(response.headers, this.response.headers);
908
+ }
909
+ }, _define_property$5(__FetchConnection, "encoder", new TextEncoder()), __FetchConnection);
910
+ // src/adapters/NodeHttp1Connection.ts
911
+ var NodeHttp1Connection = function NodeHttp1Connection(req, res) {
912
+ var _this = this;
913
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
914
+ _class_call_check$B(this, NodeHttp1Connection);
915
+ _define_property$5(this, "controller", void 0);
916
+ _define_property$5(this, "url", void 0);
917
+ _define_property$5(this, "request", void 0);
918
+ _define_property$5(this, "response", void 0);
919
+ _define_property$5(this, "onClose", function() {
920
+ _this.controller.abort();
921
+ });
922
+ _define_property$5(this, "sendHead", function() {
923
+ _this.res.writeHead(_this.response.status, Object.fromEntries(_this.response.headers));
924
+ });
925
+ _define_property$5(this, "sendChunk", function(chunk) {
926
+ _this.res.write(chunk);
927
+ });
928
+ _define_property$5(this, "cleanup", function() {
929
+ _this.req.removeListener("close", _this.onClose);
930
+ _this.res.removeListener("close", _this.onClose);
931
+ });
932
+ this.req = req;
933
+ this.res = res;
934
+ var _req_headers_host;
935
+ this.url = new URL("http://".concat((_req_headers_host = req.headers.host) !== null && _req_headers_host !== void 0 ? _req_headers_host : DEFAULT_REQUEST_HOST).concat(req.url));
936
+ this.controller = new AbortController();
937
+ req.once("close", this.onClose);
938
+ res.once("close", this.onClose);
939
+ var _req_method;
940
+ this.request = new Request(this.url, {
941
+ method: (_req_method = req.method) !== null && _req_method !== void 0 ? _req_method : DEFAULT_REQUEST_METHOD,
942
+ signal: this.controller.signal
943
+ });
944
+ applyHeaders(req.headers, this.request.headers);
945
+ var _options_statusCode, _ref;
946
+ this.response = new Response(null, {
947
+ status: (_ref = (_options_statusCode = options.statusCode) !== null && _options_statusCode !== void 0 ? _options_statusCode : res.statusCode) !== null && _ref !== void 0 ? _ref : DEFAULT_RESPONSE_CODE,
948
+ headers: DEFAULT_RESPONSE_HEADERS
949
+ });
950
+ if (res) {
951
+ applyHeaders(res.getHeaders(), this.response.headers);
952
+ }
953
+ };
954
+ // src/adapters/NodeHttp2CompatConnection.ts
955
+ var NodeHttp2CompatConnection = function NodeHttp2CompatConnection(req, res) {
956
+ var _this = this;
957
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
958
+ _class_call_check$B(this, NodeHttp2CompatConnection);
959
+ _define_property$5(this, "controller", void 0);
960
+ _define_property$5(this, "url", void 0);
961
+ _define_property$5(this, "request", void 0);
962
+ _define_property$5(this, "response", void 0);
963
+ _define_property$5(this, "onClose", function() {
964
+ _this.controller.abort();
965
+ });
966
+ _define_property$5(this, "sendHead", function() {
967
+ _this.res.writeHead(_this.response.status, Object.fromEntries(_this.response.headers));
968
+ });
969
+ _define_property$5(this, "sendChunk", function(chunk) {
970
+ _this.res.write(chunk);
971
+ });
972
+ _define_property$5(this, "cleanup", function() {
973
+ _this.req.removeListener("close", _this.onClose);
974
+ _this.res.removeListener("close", _this.onClose);
975
+ });
976
+ this.req = req;
977
+ this.res = res;
978
+ var _req_headers_host;
979
+ this.url = new URL("http://".concat((_req_headers_host = req.headers.host) !== null && _req_headers_host !== void 0 ? _req_headers_host : DEFAULT_REQUEST_HOST).concat(req.url));
980
+ this.controller = new AbortController();
981
+ req.once("close", this.onClose);
982
+ res.once("close", this.onClose);
983
+ var _req_method;
984
+ this.request = new Request(this.url, {
985
+ method: (_req_method = req.method) !== null && _req_method !== void 0 ? _req_method : DEFAULT_REQUEST_METHOD,
986
+ signal: this.controller.signal
987
+ });
988
+ var allowedHeaders = _object_spread$3({}, req.headers);
989
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
990
+ try {
991
+ for(var _iterator = Object.keys(allowedHeaders)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
992
+ var header = _step.value;
993
+ if (header.startsWith(":")) {
994
+ delete allowedHeaders[header];
995
+ }
996
+ }
997
+ } catch (err) {
998
+ _didIteratorError = true;
999
+ _iteratorError = err;
1000
+ } finally{
1001
+ try {
1002
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1003
+ _iterator.return();
1004
+ }
1005
+ } finally{
1006
+ if (_didIteratorError) {
1007
+ throw _iteratorError;
1008
+ }
1009
+ }
1010
+ }
1011
+ applyHeaders(allowedHeaders, this.request.headers);
1012
+ var _options_statusCode, _ref;
1013
+ this.response = new Response(null, {
1014
+ status: (_ref = (_options_statusCode = options.statusCode) !== null && _options_statusCode !== void 0 ? _options_statusCode : res.statusCode) !== null && _ref !== void 0 ? _ref : DEFAULT_RESPONSE_CODE,
1015
+ headers: DEFAULT_RESPONSE_HEADERS
1016
+ });
1017
+ if (res) {
1018
+ applyHeaders(res.getHeaders(), this.response.headers);
1019
+ }
1020
+ };
1021
+ // src/lib/SseError.ts
1022
+ var SseError = /*#__PURE__*/ function(Error1) {
1023
+ _inherits$l(SseError, Error1);
1024
+ var _super = _create_super$l(SseError);
1025
+ function SseError(message) {
1026
+ _class_call_check$B(this, SseError);
1027
+ var _this;
1028
+ _this = _super.call(this, message);
1029
+ _this.message = "better-sse: ".concat(message);
1030
+ return _this;
1031
+ }
1032
+ return SseError;
1033
+ }(_wrap_native_super$7(Error));
709
1034
  var TypedEmitter = /*#__PURE__*/ function(EventEmitter) {
710
1035
  _inherits$l(TypedEmitter, EventEmitter);
711
1036
  var _super = _create_super$l(TypedEmitter);
@@ -772,25 +1097,11 @@ var TypedEmitter = /*#__PURE__*/ function(EventEmitter) {
772
1097
  ]);
773
1098
  return TypedEmitter;
774
1099
  }(EventEmitter);
775
- // src/lib/SseError.ts
776
- var SseError = /*#__PURE__*/ function(Error1) {
777
- _inherits$l(SseError, Error1);
778
- var _super = _create_super$l(SseError);
779
- function SseError(message) {
780
- _class_call_check$B(this, SseError);
781
- var _this;
782
- _this = _super.call(this, message);
783
- _this.message = "better-sse: ".concat(message);
784
- return _this;
785
- }
786
- return SseError;
787
- }(_wrap_native_super$7(Error));
788
1100
  // src/Session.ts
789
1101
  var Session = /*#__PURE__*/ function(TypedEmitter) {
790
1102
  _inherits$l(Session, TypedEmitter);
791
1103
  var _super = _create_super$l(Session);
792
- function Session(req, res) {
793
- var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1104
+ function Session(req, res, options) {
794
1105
  _class_call_check$B(this, Session);
795
1106
  var _this;
796
1107
  _this = _super.call(this);
@@ -817,67 +1128,18 @@ var Session = /*#__PURE__*/ function(TypedEmitter) {
817
1128
  * to safely add new properties to the `DefaultSessionState` interface.
818
1129
  */ _define_property$5(_assert_this_initialized$l(_this), "state", void 0);
819
1130
  _define_property$5(_assert_this_initialized$l(_this), "buffer", void 0);
820
- /**
821
- * Raw HTTP request.
822
- */ _define_property$5(_assert_this_initialized$l(_this), "req", void 0);
823
- /**
824
- * Raw HTTP response that is the minimal interface needed and forms the
825
- * intersection between the HTTP/1.1 and HTTP/2 server response interfaces.
826
- */ _define_property$5(_assert_this_initialized$l(_this), "res", void 0);
827
- _define_property$5(_assert_this_initialized$l(_this), "serialize", void 0);
1131
+ _define_property$5(_assert_this_initialized$l(_this), "connection", void 0);
828
1132
  _define_property$5(_assert_this_initialized$l(_this), "sanitize", void 0);
829
- _define_property$5(_assert_this_initialized$l(_this), "trustClientEventId", void 0);
1133
+ _define_property$5(_assert_this_initialized$l(_this), "serialize", void 0);
830
1134
  _define_property$5(_assert_this_initialized$l(_this), "initialRetry", void 0);
831
1135
  _define_property$5(_assert_this_initialized$l(_this), "keepAliveInterval", void 0);
832
1136
  _define_property$5(_assert_this_initialized$l(_this), "keepAliveTimer", void 0);
833
- _define_property$5(_assert_this_initialized$l(_this), "statusCode", void 0);
834
- _define_property$5(_assert_this_initialized$l(_this), "headers", void 0);
835
1137
  _define_property$5(_assert_this_initialized$l(_this), "initialize", function() {
836
- var url = "http://".concat(_this.req.headers.host).concat(_this.req.url);
837
- var params = new URL(url).searchParams;
838
- if (_this.trustClientEventId) {
839
- var _this_req_headers_lasteventid, _ref, _ref1;
840
- var givenLastEventId = (_ref1 = (_ref = (_this_req_headers_lasteventid = _this.req.headers["last-event-id"]) !== null && _this_req_headers_lasteventid !== void 0 ? _this_req_headers_lasteventid : params.get("lastEventId")) !== null && _ref !== void 0 ? _ref : params.get("evs_last_event_id")) !== null && _ref1 !== void 0 ? _ref1 : "";
841
- _this.lastId = givenLastEventId;
842
- }
843
- var headers = {};
844
- if (_instanceof$k(_this.res, ServerResponse)) {
845
- headers["Content-Type"] = "text/event-stream";
846
- headers["Cache-Control"] = "private, no-cache, no-store, no-transform, must-revalidate, max-age=0";
847
- headers["Connection"] = "keep-alive";
848
- headers["Pragma"] = "no-cache";
849
- headers["X-Accel-Buffering"] = "no";
850
- } else {
851
- headers["content-type"] = "text/event-stream";
852
- headers["cache-control"] = "private, no-cache, no-store, no-transform, must-revalidate, max-age=0";
853
- headers["pragma"] = "no-cache";
854
- headers["x-accel-buffering"] = "no";
855
- }
856
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
857
- try {
858
- for(var _iterator = Object.entries(_this.headers)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
859
- var _step_value = _sliced_to_array$6(_step.value, 2), name = _step_value[0], value = _step_value[1];
860
- headers[name] = value !== null && value !== void 0 ? value : "";
861
- }
862
- } catch (err) {
863
- _didIteratorError = true;
864
- _iteratorError = err;
865
- } finally{
866
- try {
867
- if (!_iteratorNormalCompletion && _iterator.return != null) {
868
- _iterator.return();
869
- }
870
- } finally{
871
- if (_didIteratorError) {
872
- throw _iteratorError;
873
- }
874
- }
875
- }
876
- _this.res.writeHead(_this.statusCode, headers);
877
- if (params.has("padding")) {
1138
+ _this.connection.sendHead();
1139
+ if (_this.connection.url.searchParams.has("padding")) {
878
1140
  _this.buffer.comment(" ".repeat(2049)).dispatch();
879
1141
  }
880
- if (params.has("evs_preamble")) {
1142
+ if (_this.connection.url.searchParams.has("evs_preamble")) {
881
1143
  _this.buffer.comment(" ".repeat(2056)).dispatch();
882
1144
  }
883
1145
  if (_this.initialRetry !== null) {
@@ -891,58 +1153,47 @@ var Session = /*#__PURE__*/ function(TypedEmitter) {
891
1153
  _this.emit("connected");
892
1154
  });
893
1155
  _define_property$5(_assert_this_initialized$l(_this), "onDisconnected", function() {
894
- _this.req.removeListener("close", _this.onDisconnected);
895
- _this.res.removeListener("close", _this.onDisconnected);
1156
+ _this.connection.request.signal.removeEventListener("abort", _this.onDisconnected);
1157
+ _this.connection.cleanup();
896
1158
  if (_this.keepAliveTimer) {
897
1159
  clearInterval(_this.keepAliveTimer);
898
1160
  }
899
1161
  _this.isConnected = false;
900
1162
  _this.emit("disconnected");
901
1163
  });
902
- _define_property$5(_assert_this_initialized$l(_this), "keepAlive", function() {
1164
+ /**
1165
+ * Write an empty comment and flush it to the client.
1166
+ */ _define_property$5(_assert_this_initialized$l(_this), "keepAlive", function() {
903
1167
  _this.buffer.comment().dispatch();
904
1168
  _this.flush();
905
1169
  });
906
1170
  /**
907
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
908
- */ _define_property$5(_assert_this_initialized$l(_this), "data", function(data) {
909
- _this.buffer.data(data);
910
- return _assert_this_initialized$l(_this);
911
- });
912
- /**
913
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
914
- */ _define_property$5(_assert_this_initialized$l(_this), "id", function() {
915
- var id = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
916
- _this.buffer.id(id);
917
- _this.lastId = id;
918
- return _assert_this_initialized$l(_this);
919
- });
920
- /**
921
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
922
- */ _define_property$5(_assert_this_initialized$l(_this), "retry", function(time) {
923
- _this.buffer.retry(time);
924
- return _assert_this_initialized$l(_this);
925
- });
926
- /**
927
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
928
- */ _define_property$5(_assert_this_initialized$l(_this), "comment", function(text) {
929
- _this.buffer.comment(text);
930
- return _assert_this_initialized$l(_this);
1171
+ * Flush the contents of the internal buffer to the client and clear the buffer.
1172
+ */ _define_property$5(_assert_this_initialized$l(_this), "flush", function() {
1173
+ var contents = _this.buffer.read();
1174
+ _this.buffer.clear();
1175
+ _this.connection.sendChunk(contents);
931
1176
  });
932
1177
  /**
933
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
934
- */ _define_property$5(_assert_this_initialized$l(_this), "dispatch", function() {
935
- _this.buffer.dispatch();
936
- return _assert_this_initialized$l(_this);
1178
+ * Get a Request object representing the request of the underlying connection this session manages.
1179
+ *
1180
+ * When using the Fetch API, this will be the original Request object passed to the session constructor.
1181
+ *
1182
+ * When using the Node HTTP APIs, this will be a new Request object with status code and headers copied from the original request.
1183
+ * When the originally given request or response is closed, the abort signal attached to this Request will be triggered.
1184
+ */ _define_property$5(_assert_this_initialized$l(_this), "getRequest", function() {
1185
+ return _this.connection.request;
937
1186
  });
938
1187
  /**
939
- * Flush the contents of the internal buffer to the client and clear the buffer.
1188
+ * Get a Response object representing the response of the underlying connection this session manages.
940
1189
  *
941
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
942
- */ _define_property$5(_assert_this_initialized$l(_this), "flush", function() {
943
- _this.res.write(_this.buffer.read());
944
- _this.buffer.clear();
945
- return _assert_this_initialized$l(_this);
1190
+ * When using the Fetch API, this will be a new Response object with status code and headers copied from the original response if given.
1191
+ * Its body will be a ReadableStream that should begin being consumed for the session to consider itself connected.
1192
+ *
1193
+ * When using the Node HTTP APIs, this will be a new Response object with status code and headers copied from the original response.
1194
+ * Its body will be `null`, as data is instead written to the stream of the originally given response object.
1195
+ */ _define_property$5(_assert_this_initialized$l(_this), "getResponse", function() {
1196
+ return _this.connection.response;
946
1197
  });
947
1198
  /**
948
1199
  * Push an event to the client.
@@ -951,6 +1202,8 @@ var Session = /*#__PURE__*/ function(TypedEmitter) {
951
1202
  *
952
1203
  * 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.
953
1204
  *
1205
+ * If the session has disconnected, an `SseError` will be thrown.
1206
+ *
954
1207
  * Emits the `push` event with the given data, event name and event ID in that order.
955
1208
  *
956
1209
  * @param data - Data to write.
@@ -959,7 +1212,7 @@ var Session = /*#__PURE__*/ function(TypedEmitter) {
959
1212
  */ _define_property$5(_assert_this_initialized$l(_this), "push", function(data) {
960
1213
  var eventName = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "message", eventId = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : generateId();
961
1214
  if (!_this.isConnected) {
962
- throw new SseError("Cannot push data to a non-active session.");
1215
+ throw new SseError("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.");
963
1216
  }
964
1217
  _this.buffer.push(data, eventName, eventId);
965
1218
  _this.flush();
@@ -977,7 +1230,7 @@ var Session = /*#__PURE__*/ function(TypedEmitter) {
977
1230
  * @param stream - Readable stream to consume data from.
978
1231
  * @param options - Options to alter how the stream is flushed to the client.
979
1232
  *
980
- * @returns A promise that resolves or rejects based on the success of the stream write finishing.
1233
+ * @returns A promise that resolves with `true` or rejects based on the success of the stream write finishing.
981
1234
  */ _define_property$5(_assert_this_initialized$l(_this), "stream", createPushFromStream(_this.push));
982
1235
  /**
983
1236
  * Iterate over an iterable and send yielded values as events to the client.
@@ -1014,7 +1267,7 @@ var Session = /*#__PURE__*/ function(TypedEmitter) {
1014
1267
  3,
1015
1268
  1
1016
1269
  ];
1017
- _this1.res.write(batcher.read());
1270
+ _this1.connection.sendChunk(batcher.read());
1018
1271
  return [
1019
1272
  3,
1020
1273
  3
@@ -1030,7 +1283,7 @@ var Session = /*#__PURE__*/ function(TypedEmitter) {
1030
1283
  ];
1031
1284
  case 2:
1032
1285
  _state.sent();
1033
- _this1.res.write(buffer.read());
1286
+ _this1.connection.sendChunk(buffer.read());
1034
1287
  _state.label = 3;
1035
1288
  case 3:
1036
1289
  return [
@@ -1043,60 +1296,75 @@ var Session = /*#__PURE__*/ function(TypedEmitter) {
1043
1296
  return _ref.apply(this, arguments);
1044
1297
  };
1045
1298
  }());
1046
- _this.req = req;
1047
- _this.res = res;
1048
- var _options_serializer;
1049
- var serializer = (_options_serializer = options.serializer) !== null && _options_serializer !== void 0 ? _options_serializer : serialize;
1050
- var _options_sanitizer;
1051
- var sanitizer = (_options_sanitizer = options.sanitizer) !== null && _options_sanitizer !== void 0 ? _options_sanitizer : sanitize;
1052
- _this.serialize = serializer;
1053
- _this.sanitize = sanitizer;
1299
+ var givenOptions = options !== null && options !== void 0 ? options : {};
1300
+ if (_instanceof$k(req, Request)) {
1301
+ var givenRes = null;
1302
+ if (res) {
1303
+ if (_instanceof$k(res, Response)) {
1304
+ givenRes = res;
1305
+ } else {
1306
+ if (options) {
1307
+ throw new SseError("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.");
1308
+ }
1309
+ givenOptions = res;
1310
+ }
1311
+ }
1312
+ _this.connection = new FetchConnection(req, givenRes, givenOptions);
1313
+ } else if (_instanceof$k(req, IncomingMessage)) {
1314
+ if (_instanceof$k(res, ServerResponse)) {
1315
+ _this.connection = new NodeHttp1Connection(req, res, givenOptions);
1316
+ } else {
1317
+ throw new SseError("When providing a Node IncomingMessage object, a corresponding ServerResponse object must also be provided.");
1318
+ }
1319
+ } else if (_instanceof$k(req, Http2ServerRequest)) {
1320
+ if (_instanceof$k(res, Http2ServerResponse)) {
1321
+ _this.connection = new NodeHttp2CompatConnection(req, res, givenOptions);
1322
+ } else {
1323
+ throw new SseError("When providing a Node HTTP2ServerRequest object, a corresponding HTTP2ServerResponse object must also be provided.");
1324
+ }
1325
+ } else {
1326
+ throw new SseError("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.");
1327
+ }
1328
+ if (givenOptions.headers) {
1329
+ applyHeaders(givenOptions.headers, _this.connection.response.headers);
1330
+ }
1331
+ if (givenOptions.trustClientEventId !== false) {
1332
+ var _this_connection_request_headers_get, _ref, _ref1;
1333
+ _this.lastId = (_ref1 = (_ref = (_this_connection_request_headers_get = _this.connection.request.headers.get("last-event-id")) !== null && _this_connection_request_headers_get !== void 0 ? _this_connection_request_headers_get : _this.connection.url.searchParams.get("lastEventId")) !== null && _ref !== void 0 ? _ref : _this.connection.url.searchParams.get("evs_last_event_id")) !== null && _ref1 !== void 0 ? _ref1 : "";
1334
+ }
1335
+ var _givenOptions_state;
1336
+ _this.state = (_givenOptions_state = givenOptions.state) !== null && _givenOptions_state !== void 0 ? _givenOptions_state : {};
1337
+ var _givenOptions_retry;
1338
+ _this.initialRetry = givenOptions.retry === null ? null : (_givenOptions_retry = givenOptions.retry) !== null && _givenOptions_retry !== void 0 ? _givenOptions_retry : 2e3;
1339
+ var _givenOptions_keepAlive;
1340
+ _this.keepAliveInterval = givenOptions.keepAlive === null ? null : (_givenOptions_keepAlive = givenOptions.keepAlive) !== null && _givenOptions_keepAlive !== void 0 ? _givenOptions_keepAlive : 1e4;
1341
+ var _givenOptions_serializer;
1342
+ _this.serialize = (_givenOptions_serializer = givenOptions.serializer) !== null && _givenOptions_serializer !== void 0 ? _givenOptions_serializer : serialize;
1343
+ var _givenOptions_sanitizer;
1344
+ _this.sanitize = (_givenOptions_sanitizer = givenOptions.sanitizer) !== null && _givenOptions_sanitizer !== void 0 ? _givenOptions_sanitizer : sanitize;
1054
1345
  _this.buffer = new EventBuffer({
1055
- serializer: serializer,
1056
- sanitizer: sanitizer
1346
+ serializer: _this.serialize,
1347
+ sanitizer: _this.sanitize
1057
1348
  });
1058
- var _options_trustClientEventId;
1059
- _this.trustClientEventId = (_options_trustClientEventId = options.trustClientEventId) !== null && _options_trustClientEventId !== void 0 ? _options_trustClientEventId : true;
1060
- var _options_retry;
1061
- _this.initialRetry = options.retry === null ? null : (_options_retry = options.retry) !== null && _options_retry !== void 0 ? _options_retry : 2e3;
1062
- var _options_keepAlive;
1063
- _this.keepAliveInterval = options.keepAlive === null ? null : (_options_keepAlive = options.keepAlive) !== null && _options_keepAlive !== void 0 ? _options_keepAlive : 1e4;
1064
- var _options_statusCode;
1065
- _this.statusCode = (_options_statusCode = options.statusCode) !== null && _options_statusCode !== void 0 ? _options_statusCode : 200;
1066
- var _options_headers;
1067
- _this.headers = (_options_headers = options.headers) !== null && _options_headers !== void 0 ? _options_headers : {};
1068
- var _options_state;
1069
- _this.state = (_options_state = options.state) !== null && _options_state !== void 0 ? _options_state : {};
1070
- _this.req.once("close", _this.onDisconnected);
1071
- _this.res.once("close", _this.onDisconnected);
1349
+ _this.connection.request.signal.addEventListener("abort", _this.onDisconnected);
1072
1350
  setImmediate(_this.initialize);
1073
1351
  return _this;
1074
1352
  }
1075
- _create_class$w(Session, [
1076
- {
1077
- /**
1078
- * @deprecated see https://github.com/MatthewWid/better-sse/issues/52
1079
- */ key: "event",
1080
- value: function event(type) {
1081
- this.buffer.event(type);
1082
- return this;
1083
- }
1084
- }
1085
- ]);
1086
1353
  return Session;
1087
1354
  }(TypedEmitter);
1088
1355
  // src/createSession.ts
1089
- var createSession = function() {
1090
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
1091
- args[_key] = arguments[_key];
1092
- }
1356
+ function createSession(req, res, options) {
1093
1357
  return new Promise(function(resolve) {
1094
- var session = _construct$7(Session, _to_consumable_array$7(args));
1095
- session.once("connected", function() {
1358
+ var session = new Session(req, res, options);
1359
+ if (_instanceof$k(req, Request)) {
1096
1360
  resolve(session);
1097
- });
1361
+ } else {
1362
+ session.once("connected", function() {
1363
+ resolve(session);
1364
+ });
1365
+ }
1098
1366
  });
1099
- };
1367
+ }
1100
1368
  // src/Channel.ts
1101
1369
  var Channel = /*#__PURE__*/ function(TypedEmitter) {
1102
1370
  _inherits$l(Channel, TypedEmitter);
@@ -24065,14 +24333,14 @@ function indent(str, spaces) {
24065
24333
  var match = parseIdentifier(input, i1, namePart) || namePart && parseAdditionalSymbol(input, i1) || maybeSpace && parseSpaces(input, i1);
24066
24334
  // match is required
24067
24335
  if (!match) {
24068
- return tokens = tokens1, nextMatch = nextMatch1, i = i1, {
24336
+ return i = i1, nextMatch = nextMatch1, tokens = tokens1, {
24069
24337
  v: nextMatch1
24070
24338
  };
24071
24339
  }
24072
24340
  var token = match.token, offset = match.offset;
24073
24341
  i1 += offset;
24074
24342
  if (token === ' ') {
24075
- return tokens = tokens1, nextMatch = nextMatch1, i = i1, "continue";
24343
+ return i = i1, nextMatch = nextMatch1, tokens = tokens1, "continue";
24076
24344
  }
24077
24345
  tokens1 = _to_consumable_array$4(tokens1).concat([
24078
24346
  token
@@ -24091,7 +24359,7 @@ function indent(str, spaces) {
24091
24359
  if (contextKeys.some(function(el) {
24092
24360
  return el.startsWith(name);
24093
24361
  })) {
24094
- return tokens = tokens1, nextMatch = nextMatch1, i = i1, "continue";
24362
+ return i = i1, nextMatch = nextMatch1, tokens = tokens1, "continue";
24095
24363
  }
24096
24364
  if (dateTimeIdentifiers.some(function(el) {
24097
24365
  return el === name;
@@ -24110,9 +24378,9 @@ function indent(str, spaces) {
24110
24378
  if (dateTimeIdentifiers.some(function(el) {
24111
24379
  return el.startsWith(name);
24112
24380
  })) {
24113
- return tokens = tokens1, nextMatch = nextMatch1, i = i1, "continue";
24381
+ return i = i1, nextMatch = nextMatch1, tokens = tokens1, "continue";
24114
24382
  }
24115
- return tokens = tokens1, nextMatch = nextMatch1, i = i1, {
24383
+ return i = i1, nextMatch = nextMatch1, tokens = tokens1, {
24116
24384
  v: nextMatch1
24117
24385
  };
24118
24386
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@digipair/skill-sse",
3
- "version": "0.116.2",
3
+ "version": "0.116.4",
4
4
  "main": "./dist/index.cjs.js",
5
5
  "module": "./dist/index.esm.js",
6
6
  "types": "./dist/index.d.ts",
@@ -30,6 +30,6 @@
30
30
  "name": "skill-sse"
31
31
  },
32
32
  "dependencies": {
33
- "better-sse": "^0.14.0"
33
+ "better-sse": "^0.15.1"
34
34
  }
35
35
  }