peer.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. import { util } from "./util";
  2. import logger, { LogLevel } from "./logger";
  3. import { Socket } from "./socket";
  4. import { MediaConnection } from "./mediaconnection";
  5. import type { DataConnection } from "./dataconnection/DataConnection";
  6. import {
  7. BaseConnectionErrorType,
  8. ConnectionType,
  9. PeerErrorType,
  10. ServerMessageType,
  11. SocketEventType,
  12. } from "./enums";
  13. import type { ServerMessage } from "./servermessage";
  14. import { API } from "./api";
  15. import type {
  16. CallOption,
  17. PeerConnectOption,
  18. PeerJSOption,
  19. } from "./optionInterfaces";
  20. import { BinaryPack } from "./dataconnection/BufferedConnection/BinaryPack";
  21. import { Raw } from "./dataconnection/BufferedConnection/Raw";
  22. import { Json } from "./dataconnection/BufferedConnection/Json";
  23. import { EventEmitterWithError, PeerError } from "./peerError";
  24. class PeerOptions implements PeerJSOption {
  25. /**
  26. * Prints log messages depending on the debug level passed in.
  27. */
  28. debug?: LogLevel;
  29. /**
  30. * Server host. Defaults to `0.peerjs.com`.
  31. * Also accepts `'/'` to signify relative hostname.
  32. */
  33. host?: string;
  34. /**
  35. * Server port. Defaults to `443`.
  36. */
  37. port?: number;
  38. /**
  39. * The path where your self-hosted PeerServer is running. Defaults to `'/'`
  40. */
  41. path?: string;
  42. /**
  43. * API key for the PeerServer.
  44. * This is not used anymore.
  45. * @deprecated
  46. */
  47. key?: string;
  48. token?: string;
  49. /**
  50. * Configuration hash passed to RTCPeerConnection.
  51. * This hash contains any custom ICE/TURN server configuration.
  52. *
  53. * Defaults to {@apilink util.defaultConfig}
  54. */
  55. config?: any;
  56. /**
  57. * Set to true `true` if you're using TLS.
  58. * :::danger
  59. * If possible *always use TLS*
  60. * :::
  61. */
  62. secure?: boolean;
  63. pingInterval?: number;
  64. referrerPolicy?: ReferrerPolicy;
  65. logFunction?: (logLevel: LogLevel, ...rest: any[]) => void;
  66. serializers?: SerializerMapping;
  67. }
  68. export { type PeerOptions };
  69. export interface SerializerMapping {
  70. [key: string]: new (
  71. peerId: string,
  72. provider: Peer,
  73. options: any,
  74. ) => DataConnection;
  75. }
  76. export interface PeerEvents {
  77. /**
  78. * Emitted when a connection to the PeerServer is established.
  79. *
  80. * You may use the peer before this is emitted, but messages to the server will be queued. <code>id</code> is the brokering ID of the peer (which was either provided in the constructor or assigned by the server).<span class='tip'>You should not wait for this event before connecting to other peers if connection speed is important.</span>
  81. */
  82. open: (id: string) => void;
  83. /**
  84. * Emitted when a new data connection is established from a remote peer.
  85. */
  86. connection: (dataConnection: DataConnection) => void;
  87. /**
  88. * Emitted when a remote peer attempts to call you.
  89. */
  90. call: (mediaConnection: MediaConnection) => void;
  91. /**
  92. * Emitted when the peer is destroyed and can no longer accept or create any new connections.
  93. */
  94. close: () => void;
  95. /**
  96. * Emitted when the peer is disconnected from the signalling server
  97. */
  98. disconnected: (currentId: string) => void;
  99. /**
  100. * Errors on the peer are almost always fatal and will destroy the peer.
  101. *
  102. * Errors from the underlying socket and PeerConnections are forwarded here.
  103. */
  104. error: (error: PeerError<`${PeerErrorType}`>) => void;
  105. }
  106. export interface IPeer {
  107. /**
  108. * The brokering ID of this peer
  109. *
  110. * If no ID was specified in {@apilink Peer | the constructor},
  111. * this will be `undefined` until the {@apilink PeerEvents | `open`} event is emitted.
  112. */
  113. get id(): string;
  114. get open(): boolean;
  115. /**
  116. * A hash of all connections associated with this peer, keyed by the remote peer's ID.
  117. * @deprecated
  118. * Return type will change from Object to Map<string,[]>
  119. */
  120. get connections(): Object;
  121. /**
  122. * true if this peer and all of its connections can no longer be used.
  123. */
  124. get destroyed(): boolean;
  125. /**
  126. * Connects to the remote peer specified by id and returns a data connection.
  127. *
  128. * Make sure to listen to the `error` event of the resulting {@link DataConnection}
  129. * in case the connection fails.
  130. *
  131. * @param peer The brokering ID of the remote peer (their {@link Peer.id}).
  132. * @param options for specifying details about Peer Connection
  133. */
  134. connect(peer: string, options: PeerConnectOption): DataConnection;
  135. /**
  136. * Calls the remote peer specified by id and returns a media connection.
  137. * @param peer The brokering ID of the remote peer (their peer.id).
  138. * @param stream The caller's media stream
  139. * @param options Metadata associated with the connection, passed in by whoever initiated the connection.
  140. */
  141. call(peer: string, stream: MediaStream, options: CallOption): MediaConnection;
  142. /** Retrieve a data/media connection for this peer. */
  143. getConnection(
  144. peerId: string,
  145. connectionId: string,
  146. ): null | DataConnection | MediaConnection;
  147. /**
  148. * Destroys the Peer: closes all active connections as well as the connection
  149. * to the server.
  150. *
  151. * :::caution
  152. * This cannot be undone; the respective peer object will no longer be able
  153. * to create or receive any connections, its ID will be forfeited on the server,
  154. * and all of its data and media connections will be closed.
  155. * :::
  156. */
  157. destroy(): void;
  158. /**
  159. * Disconnects the Peer's connection to the PeerServer. Does not close any
  160. * active connections.
  161. * Warning: The peer can no longer create or accept connections after being
  162. * disconnected. It also cannot reconnect to the server.
  163. */
  164. disconnect(): void;
  165. /** Attempts to reconnect with the same ID.
  166. *
  167. * Only {@apilink Peer.disconnect | disconnected peers} can be reconnected.
  168. * Destroyed peers cannot be reconnected.
  169. * If the connection fails (as an example, if the peer's old ID is now taken),
  170. * the peer's existing connections will not close, but any associated errors events will fire.
  171. */
  172. reconnect(): void;
  173. }
  174. /**
  175. * A peer who can initiate connections with other peers.
  176. */
  177. export class Peer
  178. extends EventEmitterWithError<PeerErrorType, PeerEvents>
  179. implements IPeer
  180. {
  181. private static readonly DEFAULT_KEY = "peerjs";
  182. protected readonly _serializers: SerializerMapping = {
  183. raw: Raw,
  184. json: Json,
  185. binary: BinaryPack,
  186. "binary-utf8": BinaryPack,
  187. default: BinaryPack,
  188. };
  189. private readonly _options: PeerOptions;
  190. private readonly _api: API;
  191. private readonly _socket: Socket;
  192. private _id: string | null = null;
  193. private _lastServerId: string | null = null;
  194. // States.
  195. private _destroyed = false; // Connections have been killed
  196. private _disconnected = false; // Connection to PeerServer killed but P2P connections still active
  197. private _open = false; // Sockets and such are not yet open.
  198. private readonly _connections: Map<
  199. string,
  200. (DataConnection | MediaConnection)[]
  201. > = new Map(); // All connections for this peer.
  202. private readonly _lostMessages: Map<string, ServerMessage[]> = new Map(); // src => [list of messages]
  203. private then: (
  204. onfulfilled?: (value: IPeer) => any,
  205. onrejected?: (reason: PeerError<PeerErrorType>) => any,
  206. ) => void;
  207. get id() {
  208. return this._id;
  209. }
  210. get options() {
  211. return this._options;
  212. }
  213. get open() {
  214. return this._open;
  215. }
  216. /**
  217. * @internal
  218. */
  219. get socket() {
  220. return this._socket;
  221. }
  222. get connections(): Object {
  223. const plainConnections = Object.create(null);
  224. for (const [k, v] of this._connections) {
  225. plainConnections[k] = v;
  226. }
  227. return plainConnections;
  228. }
  229. get destroyed() {
  230. return this._destroyed;
  231. }
  232. get disconnected() {
  233. return this._disconnected;
  234. }
  235. /**
  236. * A peer can connect to other peers and listen for connections.
  237. */
  238. constructor();
  239. /**
  240. * A peer can connect to other peers and listen for connections.
  241. * @param options for specifying details about PeerServer
  242. */
  243. constructor(options: PeerOptions);
  244. /**
  245. * A peer can connect to other peers and listen for connections.
  246. * @param id Other peers can connect to this peer using the provided ID.
  247. * If no ID is given, one will be generated by the brokering server.
  248. * The ID must start and end with an alphanumeric character (lower or upper case character or a digit). In the middle of the ID spaces, dashes (-) and underscores (_) are allowed. Use {@apilink PeerOptions.metadata } to send identifying information.
  249. * @param options for specifying details about PeerServer
  250. */
  251. constructor(id: string, options?: PeerOptions);
  252. constructor(id?: string | PeerOptions, options?: PeerOptions) {
  253. super();
  254. this.then = (
  255. onfulfilled?: (value: IPeer) => any,
  256. onrejected?: (reason: PeerError<PeerErrorType>) => any,
  257. ) => {
  258. // Remove 'then' to prevent potential recursion issues
  259. // `await` will wait for a Promise-like to resolve recursively
  260. delete this.then;
  261. // We don’t need to worry about cleaning up listeners here
  262. // `await`ing a Promise will make sure only one of the paths executes
  263. this.once("open", () => onfulfilled(this));
  264. this.once("error", onrejected);
  265. };
  266. let userId: string | undefined;
  267. // Deal with overloading
  268. if (id && id.constructor == Object) {
  269. options = id as PeerOptions;
  270. } else if (id) {
  271. userId = id.toString();
  272. }
  273. // Configurize options
  274. options = {
  275. debug: 0, // 1: Errors, 2: Warnings, 3: All logs
  276. host: util.CLOUD_HOST,
  277. port: util.CLOUD_PORT,
  278. path: "/",
  279. key: Peer.DEFAULT_KEY,
  280. token: util.randomToken(),
  281. config: util.defaultConfig,
  282. referrerPolicy: "strict-origin-when-cross-origin",
  283. serializers: {},
  284. ...options,
  285. };
  286. this._options = options;
  287. this._serializers = { ...this._serializers, ...this.options.serializers };
  288. // Detect relative URL host.
  289. if (this._options.host === "/") {
  290. this._options.host = window.location.hostname;
  291. }
  292. // Set path correctly.
  293. if (this._options.path) {
  294. if (this._options.path[0] !== "/") {
  295. this._options.path = "/" + this._options.path;
  296. }
  297. if (this._options.path[this._options.path.length - 1] !== "/") {
  298. this._options.path += "/";
  299. }
  300. }
  301. // Set whether we use SSL to same as current host
  302. if (
  303. this._options.secure === undefined &&
  304. this._options.host !== util.CLOUD_HOST
  305. ) {
  306. this._options.secure = util.isSecure();
  307. } else if (this._options.host == util.CLOUD_HOST) {
  308. this._options.secure = true;
  309. }
  310. // Set a custom log function if present
  311. if (this._options.logFunction) {
  312. logger.setLogFunction(this._options.logFunction);
  313. }
  314. logger.logLevel = this._options.debug || 0;
  315. this._api = new API(options);
  316. this._socket = this._createServerConnection();
  317. // Sanity checks
  318. // Ensure WebRTC supported
  319. if (!util.supports.audioVideo && !util.supports.data) {
  320. this._delayedAbort(
  321. PeerErrorType.BrowserIncompatible,
  322. "The current browser does not support WebRTC",
  323. );
  324. return;
  325. }
  326. // Ensure alphanumeric id
  327. if (!!userId && !util.validateId(userId)) {
  328. this._delayedAbort(PeerErrorType.InvalidID, `ID "${userId}" is invalid`);
  329. return;
  330. }
  331. if (userId) {
  332. this._initialize(userId);
  333. } else {
  334. this._api
  335. .retrieveId()
  336. .then((id) => this._initialize(id))
  337. .catch((error) => this._abort(PeerErrorType.ServerError, error));
  338. }
  339. }
  340. private _createServerConnection(): Socket {
  341. const socket = new Socket(
  342. this._options.secure,
  343. this._options.host!,
  344. this._options.port!,
  345. this._options.path!,
  346. this._options.key!,
  347. this._options.pingInterval,
  348. );
  349. socket.on(SocketEventType.Message, (data: ServerMessage) => {
  350. this._handleMessage(data);
  351. });
  352. socket.on(SocketEventType.Error, (error: string) => {
  353. this._abort(PeerErrorType.SocketError, error);
  354. });
  355. socket.on(SocketEventType.Disconnected, () => {
  356. if (this.disconnected) {
  357. return;
  358. }
  359. this.emitError(PeerErrorType.Network, "Lost connection to server.");
  360. this.disconnect();
  361. });
  362. socket.on(SocketEventType.Close, () => {
  363. if (this.disconnected) {
  364. return;
  365. }
  366. this._abort(
  367. PeerErrorType.SocketClosed,
  368. "Underlying socket is already closed.",
  369. );
  370. });
  371. return socket;
  372. }
  373. /** Initialize a connection with the server. */
  374. private _initialize(id: string): void {
  375. this._id = id;
  376. this.socket.start(id, this._options.token!);
  377. }
  378. /** Handles messages from the server. */
  379. private _handleMessage(message: ServerMessage): void {
  380. const type = message.type;
  381. const payload = message.payload;
  382. const peerId = message.src;
  383. switch (type) {
  384. case ServerMessageType.Open: // The connection to the server is open.
  385. this._lastServerId = this.id;
  386. this._open = true;
  387. this.emit("open", this.id);
  388. break;
  389. case ServerMessageType.Error: // Server error.
  390. this._abort(PeerErrorType.ServerError, payload.msg);
  391. break;
  392. case ServerMessageType.IdTaken: // The selected ID is taken.
  393. this._abort(PeerErrorType.UnavailableID, `ID "${this.id}" is taken`);
  394. break;
  395. case ServerMessageType.InvalidKey: // The given API key cannot be found.
  396. this._abort(
  397. PeerErrorType.InvalidKey,
  398. `API KEY "${this._options.key}" is invalid`,
  399. );
  400. break;
  401. case ServerMessageType.Leave: // Another peer has closed its connection to this peer.
  402. logger.log(`Received leave message from ${peerId}`);
  403. this._cleanupPeer(peerId);
  404. this._connections.delete(peerId);
  405. break;
  406. case ServerMessageType.Expire: // The offer sent to a peer has expired without response.
  407. this.emitError(
  408. PeerErrorType.PeerUnavailable,
  409. `Could not connect to peer ${peerId}`,
  410. );
  411. // Emit an error on all connections with this peer.
  412. const connections = (this._connections.get(peerId) ?? []).filter(
  413. (c) => c.peer === peerId,
  414. );
  415. for (const conn of connections) {
  416. conn.emitError(
  417. BaseConnectionErrorType.PeerUnavailable,
  418. `${peerId} is unavailable`,
  419. );
  420. }
  421. break;
  422. case ServerMessageType.Offer: {
  423. // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  424. const connectionId = payload.connectionId;
  425. let connection = this.getConnection(peerId, connectionId);
  426. if (connection) {
  427. connection.close();
  428. logger.warn(
  429. `Offer received for existing Connection ID:${connectionId}`,
  430. );
  431. }
  432. // Create a new connection.
  433. if (payload.type === ConnectionType.Media) {
  434. const mediaConnection = new MediaConnection(peerId, this, {
  435. connectionId: connectionId,
  436. _payload: payload,
  437. metadata: payload.metadata,
  438. });
  439. connection = mediaConnection;
  440. this._addConnection(peerId, connection);
  441. this.emit("call", mediaConnection);
  442. } else if (payload.type === ConnectionType.Data) {
  443. const dataConnection = new this._serializers[payload.serialization](
  444. peerId,
  445. this,
  446. {
  447. connectionId: connectionId,
  448. _payload: payload,
  449. metadata: payload.metadata,
  450. label: payload.label,
  451. serialization: payload.serialization,
  452. reliable: payload.reliable,
  453. },
  454. );
  455. connection = dataConnection;
  456. this._addConnection(peerId, connection);
  457. this.emit("connection", dataConnection);
  458. } else {
  459. logger.warn(`Received malformed connection type:${payload.type}`);
  460. return;
  461. }
  462. // Find messages.
  463. const messages = this._getMessages(connectionId);
  464. for (const message of messages) {
  465. connection.handleMessage(message);
  466. }
  467. break;
  468. }
  469. default: {
  470. if (!payload) {
  471. logger.warn(
  472. `You received a malformed message from ${peerId} of type ${type}`,
  473. );
  474. return;
  475. }
  476. const connectionId = payload.connectionId;
  477. const connection = this.getConnection(peerId, connectionId);
  478. if (connection && connection.peerConnection) {
  479. // Pass it on.
  480. connection.handleMessage(message);
  481. } else if (connectionId) {
  482. // Store for possible later use
  483. this._storeMessage(connectionId, message);
  484. } else {
  485. logger.warn("You received an unrecognized message:", message);
  486. }
  487. break;
  488. }
  489. }
  490. }
  491. /** Stores messages without a set up connection, to be claimed later. */
  492. private _storeMessage(connectionId: string, message: ServerMessage): void {
  493. if (!this._lostMessages.has(connectionId)) {
  494. this._lostMessages.set(connectionId, []);
  495. }
  496. this._lostMessages.get(connectionId).push(message);
  497. }
  498. /**
  499. * Retrieve messages from lost message store
  500. * @internal
  501. */
  502. //TODO Change it to private
  503. public _getMessages(connectionId: string): ServerMessage[] {
  504. const messages = this._lostMessages.get(connectionId);
  505. if (messages) {
  506. this._lostMessages.delete(connectionId);
  507. return messages;
  508. }
  509. return [];
  510. }
  511. connect(peer: string, options: PeerConnectOption = {}): DataConnection {
  512. options = {
  513. serialization: "default",
  514. ...options,
  515. };
  516. if (this.disconnected) {
  517. logger.warn(
  518. "You cannot connect to a new Peer because you called " +
  519. ".disconnect() on this Peer and ended your connection with the " +
  520. "server. You can create a new Peer to reconnect, or call reconnect " +
  521. "on this peer if you believe its ID to still be available.",
  522. );
  523. this.emitError(
  524. PeerErrorType.Disconnected,
  525. "Cannot connect to new Peer after disconnecting from server.",
  526. );
  527. return;
  528. }
  529. const dataConnection = new this._serializers[options.serialization](
  530. peer,
  531. this,
  532. options,
  533. );
  534. this._addConnection(peer, dataConnection);
  535. return dataConnection;
  536. }
  537. call(
  538. peer: string,
  539. stream: MediaStream,
  540. options: CallOption = {},
  541. ): MediaConnection {
  542. if (this.disconnected) {
  543. logger.warn(
  544. "You cannot connect to a new Peer because you called " +
  545. ".disconnect() on this Peer and ended your connection with the " +
  546. "server. You can create a new Peer to reconnect.",
  547. );
  548. this.emitError(
  549. PeerErrorType.Disconnected,
  550. "Cannot connect to new Peer after disconnecting from server.",
  551. );
  552. return;
  553. }
  554. if (!stream) {
  555. logger.error(
  556. "To call a peer, you must provide a stream from your browser's `getUserMedia`.",
  557. );
  558. return;
  559. }
  560. const mediaConnection = new MediaConnection(peer, this, {
  561. ...options,
  562. _stream: stream,
  563. });
  564. this._addConnection(peer, mediaConnection);
  565. return mediaConnection;
  566. }
  567. /** Add a data/media connection to this peer. */
  568. private _addConnection(
  569. peerId: string,
  570. connection: MediaConnection | DataConnection,
  571. ): void {
  572. logger.log(
  573. `add connection ${connection.type}:${connection.connectionId} to peerId:${peerId}`,
  574. );
  575. if (!this._connections.has(peerId)) {
  576. this._connections.set(peerId, []);
  577. }
  578. this._connections.get(peerId).push(connection);
  579. }
  580. //TODO should be private
  581. _removeConnection(connection: DataConnection | MediaConnection): void {
  582. const connections = this._connections.get(connection.peer);
  583. if (connections) {
  584. const index = connections.indexOf(connection);
  585. if (index !== -1) {
  586. connections.splice(index, 1);
  587. }
  588. }
  589. //remove from lost messages
  590. this._lostMessages.delete(connection.connectionId);
  591. }
  592. getConnection(
  593. peerId: string,
  594. connectionId: string,
  595. ): null | DataConnection | MediaConnection {
  596. const connections = this._connections.get(peerId);
  597. if (!connections) {
  598. return null;
  599. }
  600. for (const connection of connections) {
  601. if (connection.connectionId === connectionId) {
  602. return connection;
  603. }
  604. }
  605. return null;
  606. }
  607. private _delayedAbort(type: PeerErrorType, message: string | Error): void {
  608. setTimeout(() => {
  609. this._abort(type, message);
  610. }, 0);
  611. }
  612. /**
  613. * Emits an error message and destroys the Peer.
  614. * The Peer is not destroyed if it's in a disconnected state, in which case
  615. * it retains its disconnected state and its existing connections.
  616. */
  617. private _abort(type: PeerErrorType, message: string | Error): void {
  618. logger.error("Aborting!");
  619. this.emitError(type, message);
  620. if (!this._lastServerId) {
  621. this.destroy();
  622. } else {
  623. this.disconnect();
  624. }
  625. }
  626. destroy(): void {
  627. if (this.destroyed) {
  628. return;
  629. }
  630. logger.log(`Destroy peer with ID:${this.id}`);
  631. this.disconnect();
  632. this._cleanup();
  633. this._destroyed = true;
  634. this.emit("close");
  635. }
  636. /** Disconnects every connection on this peer. */
  637. private _cleanup(): void {
  638. for (const peerId of this._connections.keys()) {
  639. this._cleanupPeer(peerId);
  640. this._connections.delete(peerId);
  641. }
  642. this.socket.removeAllListeners();
  643. }
  644. /** Closes all connections to this peer. */
  645. private _cleanupPeer(peerId: string): void {
  646. const connections = this._connections.get(peerId);
  647. if (!connections) return;
  648. for (const connection of connections) {
  649. connection.close();
  650. }
  651. }
  652. disconnect(): void {
  653. if (this.disconnected) {
  654. return;
  655. }
  656. const currentId = this.id;
  657. logger.log(`Disconnect peer with ID:${currentId}`);
  658. this._disconnected = true;
  659. this._open = false;
  660. this.socket.close();
  661. this._lastServerId = currentId;
  662. this._id = null;
  663. this.emit("disconnected", currentId);
  664. }
  665. reconnect(): void {
  666. if (this.disconnected && !this.destroyed) {
  667. logger.log(
  668. `Attempting reconnection to server with ID ${this._lastServerId}`,
  669. );
  670. this._disconnected = false;
  671. this._initialize(this._lastServerId!);
  672. } else if (this.destroyed) {
  673. throw new Error(
  674. "This peer cannot reconnect to the server. It has already been destroyed.",
  675. );
  676. } else if (!this.disconnected && !this.open) {
  677. // Do nothing. We're still connecting the first time.
  678. logger.error(
  679. "In a hurry? We're still trying to make the initial connection!",
  680. );
  681. } else {
  682. throw new Error(
  683. `Peer ${this.id} cannot reconnect because it is not disconnected from the server!`,
  684. );
  685. }
  686. }
  687. /**
  688. * Get a list of available peer IDs. If you're running your own server, you'll
  689. * want to set allow_discovery: true in the PeerServer options. If you're using
  690. * the cloud server, email team@peerjs.com to get the functionality enabled for
  691. * your key.
  692. */
  693. listAllPeers(cb = (_: any[]) => {}): void {
  694. this._api
  695. .listAllPeers()
  696. .then((peers) => cb(peers))
  697. .catch((error) => this._abort(PeerErrorType.ServerError, error));
  698. }
  699. }