provider-websocket.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { WebSocket as _WebSocket } from "./ws.js"; /*-browser*/
  2. import { SocketProvider } from "./provider-socket.js";
  3. /**
  4. * A JSON-RPC provider which is backed by a WebSocket.
  5. *
  6. * WebSockets are often preferred because they retain a live connection
  7. * to a server, which permits more instant access to events.
  8. *
  9. * However, this incurs higher server infrasturture costs, so additional
  10. * resources may be required to host your own WebSocket nodes and many
  11. * third-party services charge additional fees for WebSocket endpoints.
  12. */
  13. export class WebSocketProvider extends SocketProvider {
  14. #connect;
  15. #websocket;
  16. get websocket() {
  17. if (this.#websocket == null) {
  18. throw new Error("websocket closed");
  19. }
  20. return this.#websocket;
  21. }
  22. constructor(url, network, options) {
  23. super(network, options);
  24. if (typeof (url) === "string") {
  25. this.#connect = () => { return new _WebSocket(url); };
  26. this.#websocket = this.#connect();
  27. }
  28. else if (typeof (url) === "function") {
  29. this.#connect = url;
  30. this.#websocket = url();
  31. }
  32. else {
  33. this.#connect = null;
  34. this.#websocket = url;
  35. }
  36. this.websocket.onopen = async () => {
  37. try {
  38. await this._start();
  39. this.resume();
  40. }
  41. catch (error) {
  42. console.log("failed to start WebsocketProvider", error);
  43. // @TODO: now what? Attempt reconnect?
  44. }
  45. };
  46. this.websocket.onmessage = (message) => {
  47. this._processMessage(message.data);
  48. };
  49. /*
  50. this.websocket.onclose = (event) => {
  51. // @TODO: What event.code should we reconnect on?
  52. const reconnect = false;
  53. if (reconnect) {
  54. this.pause(true);
  55. if (this.#connect) {
  56. this.#websocket = this.#connect();
  57. this.#websocket.onopen = ...
  58. // @TODO: this requires the super class to rebroadcast; move it there
  59. }
  60. this._reconnect();
  61. }
  62. };
  63. */
  64. }
  65. async _write(message) {
  66. this.websocket.send(message);
  67. }
  68. async destroy() {
  69. if (this.#websocket != null) {
  70. this.#websocket.close();
  71. this.#websocket = null;
  72. }
  73. super.destroy();
  74. }
  75. }
  76. //# sourceMappingURL=provider-websocket.js.map