webtransport.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.WebTransport = void 0;
  4. const transport_1 = require("../transport");
  5. const debug_1 = require("debug");
  6. const engine_io_parser_1 = require("engine.io-parser");
  7. const debug = (0, debug_1.default)("engine:webtransport");
  8. /**
  9. * Reference: https://developer.mozilla.org/en-US/docs/Web/API/WebTransport_API
  10. */
  11. class WebTransport extends transport_1.Transport {
  12. constructor(session, stream, reader) {
  13. super({ _query: { EIO: "4" } });
  14. this.session = session;
  15. const transformStream = (0, engine_io_parser_1.createPacketEncoderStream)();
  16. transformStream.readable.pipeTo(stream.writable).catch(() => {
  17. debug("the stream was closed");
  18. });
  19. this.writer = transformStream.writable.getWriter();
  20. (async () => {
  21. try {
  22. while (true) {
  23. const { value, done } = await reader.read();
  24. if (done) {
  25. debug("session is closed");
  26. break;
  27. }
  28. debug("received chunk: %o", value);
  29. this.onPacket(value);
  30. }
  31. }
  32. catch (e) {
  33. debug("error while reading: %s", e.message);
  34. }
  35. })();
  36. session.closed.then(() => this.onClose());
  37. this.writable = true;
  38. }
  39. get name() {
  40. return "webtransport";
  41. }
  42. get supportsFraming() {
  43. return true;
  44. }
  45. async send(packets) {
  46. this.writable = false;
  47. try {
  48. for (let i = 0; i < packets.length; i++) {
  49. const packet = packets[i];
  50. await this.writer.write(packet);
  51. }
  52. }
  53. catch (e) {
  54. debug("error while writing: %s", e.message);
  55. }
  56. this.writable = true;
  57. this.emit("drain");
  58. }
  59. doClose(fn) {
  60. debug("closing WebTransport session");
  61. this.session.close();
  62. fn && fn();
  63. }
  64. }
  65. exports.WebTransport = WebTransport;