peer.ts 21 KB

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