baseconnection.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { EventEmitter, ValidEventTypes } from "eventemitter3";
  2. import type { Peer } from "./peer";
  3. import type { ServerMessage } from "./servermessage";
  4. import type { ConnectionType } from "./enums";
  5. export type BaseConnectionEvents = {
  6. /**
  7. * Emitted when either you or the remote peer closes the connection.
  8. *
  9. * ```ts
  10. * connection.on('close', () => { ... });
  11. * ```
  12. */
  13. close: () => void;
  14. /**
  15. * ```ts
  16. * connection.on('error', (error) => { ... });
  17. * ```
  18. */
  19. error: (error: Error) => void;
  20. iceStateChanged: (state: RTCIceConnectionState) => void;
  21. };
  22. export abstract class BaseConnection<
  23. T extends ValidEventTypes,
  24. > extends EventEmitter<T & BaseConnectionEvents> {
  25. protected _open = false;
  26. /**
  27. * Any type of metadata associated with the connection,
  28. * passed in by whoever initiated the connection.
  29. */
  30. readonly metadata: any;
  31. connectionId: string;
  32. peerConnection: RTCPeerConnection;
  33. dataChannel: RTCDataChannel;
  34. abstract get type(): ConnectionType;
  35. /**
  36. * The optional label passed in or assigned by PeerJS when the connection was initiated.
  37. */
  38. label: string;
  39. /**
  40. * Whether the media connection is active (e.g. your call has been answered).
  41. * You can check this if you want to set a maximum wait time for a one-sided call.
  42. */
  43. get open() {
  44. return this._open;
  45. }
  46. protected constructor(
  47. /**
  48. * The ID of the peer on the other end of this connection.
  49. */
  50. readonly peer: string,
  51. public provider: Peer,
  52. readonly options: any,
  53. ) {
  54. super();
  55. this.metadata = options.metadata;
  56. }
  57. abstract close(): void;
  58. /**
  59. * @internal
  60. */
  61. abstract handleMessage(message: ServerMessage): void;
  62. /**
  63. * Called by the Negotiator when the DataChannel is ready.
  64. * @internal
  65. * */
  66. abstract _initializeDataChannel(dc: RTCDataChannel): void;
  67. }