@@ -11,6 +11,7 @@ import { BaseConnection, type BaseConnectionEvents } from "../baseconnection";
1111import type { ServerMessage } from "../servermessage" ;
1212import type { EventsWithError } from "../peerError" ;
1313import { randomToken } from "../utils/randomToken" ;
14+ import { PeerError } from "../peerError" ;
1415
1516export interface DataConnectionEvents
1617 extends EventsWithError < DataConnectionErrorType | BaseConnectionErrorType > ,
@@ -25,6 +26,14 @@ export interface DataConnectionEvents
2526 open : ( ) => void ;
2627}
2728
29+ export interface IDataConnection
30+ extends BaseConnection < DataConnectionEvents , DataConnectionErrorType > {
31+ /** Allows user to close connection. */
32+ close ( options ?: { flush ?: boolean } ) : void ;
33+ /** Allows user to send data. */
34+ send ( data : any , chunked ?: boolean ) : void ;
35+ }
36+
2837/**
2938 * Wraps a DataChannel between two Peers.
3039 */
@@ -38,6 +47,10 @@ export abstract class DataConnection extends BaseConnection<
3847 private _negotiator : Negotiator < DataConnectionEvents , this> ;
3948 abstract readonly serialization : string ;
4049 readonly reliable : boolean ;
50+ private then : (
51+ onfulfilled ?: ( value : IDataConnection ) => any ,
52+ onrejected ?: ( reason : PeerError < DataConnectionErrorType > ) => any ,
53+ ) => void ;
4154
4255 public get type ( ) {
4356 return ConnectionType . Data ;
@@ -46,6 +59,20 @@ export abstract class DataConnection extends BaseConnection<
4659 constructor ( peerId : string , provider : Peer , options : any ) {
4760 super ( peerId , provider , options ) ;
4861
62+ this . then = (
63+ onfulfilled ?: ( value : IDataConnection ) => any ,
64+ onrejected ?: ( reason : PeerError < DataConnectionErrorType > ) => any ,
65+ ) => {
66+ // Remove 'then' to prevent potential recursion issues
67+ // `await` will wait for a Promise-like to resolve recursively
68+ delete this . then ;
69+
70+ // We don’t need to worry about cleaning up listeners here
71+ // `await`ing a Promise will make sure only one of the paths executes
72+ this . once ( "open" , ( ) => onfulfilled ( this ) ) ;
73+ this . once ( "error" , onrejected ) ;
74+ } ;
75+
4976 this . connectionId =
5077 this . options . connectionId || DataConnection . ID_PREFIX + randomToken ( ) ;
5178
@@ -87,7 +114,6 @@ export abstract class DataConnection extends BaseConnection<
87114 * Exposed functionality for users.
88115 */
89116
90- /** Allows user to close connection. */
91117 close ( options ?: { flush ?: boolean } ) : void {
92118 if ( options ?. flush ) {
93119 this . send ( {
@@ -126,7 +152,6 @@ export abstract class DataConnection extends BaseConnection<
126152
127153 protected abstract _send ( data : any , chunked : boolean ) : void ;
128154
129- /** Allows user to send data. */
130155 public send ( data : any , chunked = false ) {
131156 if ( ! this . open ) {
132157 this . emitError (
0 commit comments