@electrum-cash/web-socket 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +25 -27
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":";;ACQA;;GAEG;AACH,8BAA+B,SAAQ,aAAa,oBAAoB,CAAE,YAAW,cAAc;IA6B1F,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,SAAS,EAAE,OAAO;IAClB,OAAO,EAAE,MAAM;IAbvB;;;;;;;OAOG;gBAGK,IAAI,EAAE,MAAM,EACZ,IAAI,GAAE,MAAc,EACpB,SAAS,GAAE,OAAc,EACzB,OAAO,GAAE,MAAuB;IAOxC;;OAEG;IACH,IAAI,cAAc,IAAI,MAAM,CAG3B;IAED;;OAEG;IACH,OAAO,IAAI,IAAI;IA4Ef;;;;OAIG;IACI,UAAU,IAAI,IAAI;
|
|
1
|
+
{"mappings":";;ACQA;;GAEG;AACH,8BAA+B,SAAQ,aAAa,oBAAoB,CAAE,YAAW,cAAc;IA6B1F,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,SAAS,EAAE,OAAO;IAClB,OAAO,EAAE,MAAM;IAbvB;;;;;;;OAOG;gBAGK,IAAI,EAAE,MAAM,EACZ,IAAI,GAAE,MAAc,EACpB,SAAS,GAAE,OAAc,EACzB,OAAO,GAAE,MAAuB;IAOxC;;OAEG;IACH,IAAI,cAAc,IAAI,MAAM,CAG3B;IAED;;OAEG;IACH,OAAO,IAAI,IAAI;IA4Ef;;;;OAIG;IACI,UAAU,IAAI,IAAI;IAsCzB;;;;;;;;;OASG;IACI,KAAK,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM,EAAE,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,KAAK,IAAI,GAAG,OAAO;IA+BlF,SAAgB,SAAS,EAAE,EAAE,CAAC;IAC9B,SAAgB,YAAY,EAAE,EAAE,CAAC;IACjC,SAAgB,IAAI,EAAE,CAAE,MAAM,CAAE,CAAC;IACjC,SAAgB,KAAK,EAAE,CAAE,KAAK,CAAE,CAAC;CACjC","sources":["source/source/constants.ts","source/source/web.ts","source/source/index.ts","source/index.ts"],"sourcesContent":[null,null,null,"export * from './web.ts';\n"],"names":[],"version":3,"file":"index.d.ts.map"}
|
package/dist/index.mjs
CHANGED
|
@@ -38,16 +38,10 @@ class $05743633fea447d4$export$25b4633f61498e1 extends (0, $dvphU$EventEmitter)
|
|
|
38
38
|
* @param timeout If no connection is established after `timeout` ms, the connection is terminated
|
|
39
39
|
*/ constructor(host, port = 50004, encrypted = true, timeout = (0, $d801b1f9b7fc3074$export$1bddf2b96e25d075)){
|
|
40
40
|
// Initialize the event emitter.
|
|
41
|
-
super()
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
this.timeout = timeout;
|
|
46
|
-
this.onConnectHasRun = false;
|
|
47
|
-
this.eventForwarders = {
|
|
48
|
-
disconnect: ()=>this.emit("disconnected"),
|
|
49
|
-
wsData: (event)=>this.emit("data", `${event.data}\n`),
|
|
50
|
-
wsError: (event)=>this.emit("error", new Error(event.error))
|
|
41
|
+
super(), this.host = host, this.port = port, this.encrypted = encrypted, this.timeout = timeout, this.onConnectHasRun = false, this.eventForwarders = {
|
|
42
|
+
disconnect: ()=>this.emit('disconnected'),
|
|
43
|
+
wsData: (event)=>this.emit('data', `${event.data}\n`),
|
|
44
|
+
wsError: (event)=>this.emit('error', new Error(event.error))
|
|
51
45
|
};
|
|
52
46
|
}
|
|
53
47
|
/**
|
|
@@ -59,13 +53,13 @@ class $05743633fea447d4$export$25b4633f61498e1 extends (0, $dvphU$EventEmitter)
|
|
|
59
53
|
* Connect to host:port using the specified transport
|
|
60
54
|
*/ connect() {
|
|
61
55
|
// Check that no existing socket exists before initiating a new connection.
|
|
62
|
-
if (this.webSocket) throw new Error(
|
|
56
|
+
if (this.webSocket) throw new Error('Cannot initiate a new socket connection when an existing connection exists');
|
|
63
57
|
// Set a timer to force disconnect after `timeout` seconds
|
|
64
58
|
this.disconnectTimer = setTimeout(()=>this.disconnectOnTimeout(), this.timeout);
|
|
65
59
|
// Remove the timer if a connection is successfully established
|
|
66
|
-
this.once(
|
|
60
|
+
this.once('connected', this.clearDisconnectTimerOnTimeout);
|
|
67
61
|
// Set a named connection type for logging purposes.
|
|
68
|
-
const connectionType = this.encrypted ?
|
|
62
|
+
const connectionType = this.encrypted ? 'an encrypted WebSocket' : 'a WebSocket';
|
|
69
63
|
// Log that we are trying to establish a connection.
|
|
70
64
|
(0, $dvphU$electrumcashdebuglogs).network(`Initiating ${connectionType} connection to '${this.host}:${this.port}'.`);
|
|
71
65
|
if (this.encrypted) // Initialize this.webSocket (rejecting self-signed certificates).
|
|
@@ -74,9 +68,9 @@ class $05743633fea447d4$export$25b4633f61498e1 extends (0, $dvphU$EventEmitter)
|
|
|
74
68
|
else // Initialize this.webSocket.
|
|
75
69
|
this.webSocket = new (0, $dvphU$WebSocket)(`ws://${this.host}:${this.port}`);
|
|
76
70
|
// Trigger successful connection events.
|
|
77
|
-
this.webSocket.addEventListener(
|
|
71
|
+
this.webSocket.addEventListener('open', this.onConnect.bind(this));
|
|
78
72
|
// Forward the encountered errors.
|
|
79
|
-
this.webSocket.addEventListener(
|
|
73
|
+
this.webSocket.addEventListener('error', this.eventForwarders.wsError);
|
|
80
74
|
}
|
|
81
75
|
/**
|
|
82
76
|
* Sets up forwarding of events related to the connection.
|
|
@@ -84,16 +78,16 @@ class $05743633fea447d4$export$25b4633f61498e1 extends (0, $dvphU$EventEmitter)
|
|
|
84
78
|
// If the onConnect function has already run, do not execute it again.
|
|
85
79
|
if (this.onConnectHasRun) return;
|
|
86
80
|
// Set a named connection type for logging purposes.
|
|
87
|
-
const connectionType = this.encrypted ?
|
|
81
|
+
const connectionType = this.encrypted ? 'an encrypted WebSocket' : 'a WebSocket';
|
|
88
82
|
// Log that the connection has been established.
|
|
89
83
|
(0, $dvphU$electrumcashdebuglogs).network(`Established ${connectionType} connection with '${this.host}:${this.port}'.`);
|
|
90
84
|
// Forward the socket events
|
|
91
|
-
this.webSocket.addEventListener(
|
|
92
|
-
this.webSocket.addEventListener(
|
|
85
|
+
this.webSocket.addEventListener('close', this.eventForwarders.disconnect);
|
|
86
|
+
this.webSocket.addEventListener('message', this.eventForwarders.wsData);
|
|
93
87
|
// Indicate that the onConnect function has run.
|
|
94
88
|
this.onConnectHasRun = true;
|
|
95
89
|
// Emit the connect event.
|
|
96
|
-
this.emit(
|
|
90
|
+
this.emit('connected');
|
|
97
91
|
}
|
|
98
92
|
/**
|
|
99
93
|
* Clears the disconnect timer if it is still active.
|
|
@@ -110,10 +104,14 @@ class $05743633fea447d4$export$25b4633f61498e1 extends (0, $dvphU$EventEmitter)
|
|
|
110
104
|
this.clearDisconnectTimerOnTimeout();
|
|
111
105
|
try {
|
|
112
106
|
// Remove all event forwarders.
|
|
113
|
-
this.webSocket.removeEventListener(
|
|
114
|
-
this.webSocket.removeEventListener(
|
|
115
|
-
this.webSocket.removeEventListener(
|
|
116
|
-
//
|
|
107
|
+
this.webSocket.removeEventListener('close', this.eventForwarders.disconnect);
|
|
108
|
+
this.webSocket.removeEventListener('message', this.eventForwarders.wsData);
|
|
109
|
+
this.webSocket.removeEventListener('error', this.eventForwarders.wsError);
|
|
110
|
+
// Add a one-time event listener for potential error events after closing the socket.
|
|
111
|
+
// NOTE: This is needed since the close() call might not result in an error itself, but the
|
|
112
|
+
// underlying network packets that are sent in order to do a graceful termination can fail.
|
|
113
|
+
this.webSocket.once('error', (ignored)=>{});
|
|
114
|
+
// Gracefully terminate the connection
|
|
117
115
|
this.webSocket.close();
|
|
118
116
|
} catch (ignored) {
|
|
119
117
|
// close() will throw an error if the connection has not been established yet.
|
|
@@ -125,7 +123,7 @@ class $05743633fea447d4$export$25b4633f61498e1 extends (0, $dvphU$EventEmitter)
|
|
|
125
123
|
// Indicate that the onConnect function has not run and it has to be run again.
|
|
126
124
|
this.onConnectHasRun = false;
|
|
127
125
|
// Emit a disconnect event
|
|
128
|
-
this.emit(
|
|
126
|
+
this.emit('disconnected');
|
|
129
127
|
}
|
|
130
128
|
/**
|
|
131
129
|
* Write data to the socket
|
|
@@ -138,7 +136,7 @@ class $05743633fea447d4$export$25b4633f61498e1 extends (0, $dvphU$EventEmitter)
|
|
|
138
136
|
* is queued in the user memory
|
|
139
137
|
*/ write(data, callback) {
|
|
140
138
|
// Throw an error if no active connection is found
|
|
141
|
-
if (!this.webSocket) throw new Error(
|
|
139
|
+
if (!this.webSocket) throw new Error('Cannot write to socket when there is no active connection');
|
|
142
140
|
// Write data to the WebSocket
|
|
143
141
|
this.webSocket.send(data, callback);
|
|
144
142
|
// WebSockets always fit everything in a single request, so we return true
|
|
@@ -148,9 +146,9 @@ class $05743633fea447d4$export$25b4633f61498e1 extends (0, $dvphU$EventEmitter)
|
|
|
148
146
|
* Force a disconnection if no connection is established after `timeout` milliseconds.
|
|
149
147
|
*/ disconnectOnTimeout() {
|
|
150
148
|
// Remove the connect listener.
|
|
151
|
-
this.removeListener(
|
|
149
|
+
this.removeListener('connected', this.clearDisconnectTimerOnTimeout);
|
|
152
150
|
// Emit an error event so that connect is rejected upstream.
|
|
153
|
-
this.emit(
|
|
151
|
+
this.emit('error', new Error(`Connection to '${this.host}:${this.port}' timed out after ${this.timeout} milliseconds`));
|
|
154
152
|
// Forcibly disconnect to clean up the connection on timeout
|
|
155
153
|
this.disconnect();
|
|
156
154
|
}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":";;;;;;;;;;;;;;AEAA,gDAAgD;AACzC,MAAM,4CAAiB;;;ADUvB,MAAM,iDAA0B,CAAA,GAAA,mBAAW;;;;;IAEjD,8BAA8B;IACtB,UAAqB;IAE7B,wEAAwE;IAChE,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B,KAAiB;IACjB,MAAiB;AAClC","sources":["source/index.ts","source/web.ts","source/constants.ts"],"sourcesContent":["export * from './web.ts';\n","import { WebSocket } from '@monsterbitar/isomorphic-ws';\nimport { EventEmitter } from 'eventemitter3';\nimport debug from '@electrum-cash/debug-logs';\nimport { defaultTimeout } from './constants';\n\nimport type { MessageEvent, ErrorEvent } from '@monsterbitar/isomorphic-ws';\nimport type { ElectrumSocket, ElectrumSocketEvents } from '@electrum-cash/network';\n\n/**\n * Web Socket used when communicating with Electrum servers.\n */\nexport class ElectrumWebSocket extends EventEmitter<ElectrumSocketEvents> implements ElectrumSocket\n{\n\t// Declare an empty WebSocket.\n\tprivate webSocket: WebSocket;\n\n\t// Used to disconnect after some time if initial connection is too slow.\n\tprivate disconnectTimer?: number;\n\n\t// Initialize boolean that indicates whether the onConnect function has run (initialize to false).\n\tprivate onConnectHasRun = false;\n\n\t// Initialize event forwarding functions.\n\tprivate eventForwarders =\n\t{\n\t\tdisconnect: () => this.emit('disconnected'),\n\t\twsData: (event: MessageEvent) => this.emit('data', `${event.data}\\n`),\n\t\twsError: (event: ErrorEvent) => this.emit('error', new Error(event.error)),\n\t};\n\n\t/**\n\t * Creates a socket configured with connection information for a given Electrum server.\n\t *\n\t * @param host Fully qualified domain name or IP address of the host\n\t * @param port Network port for the host to connect to, defaults to the standard TLS port\n\t * @param encrypted If false, uses an unencrypted connection instead of the default on TLS\n\t * @param timeout If no connection is established after `timeout` ms, the connection is terminated\n\t */\n\tpublic constructor\n\t(\n\t\tpublic host: string,\n\t\tpublic port: number = 50004,\n\t\tpublic encrypted: boolean = true,\n\t\tpublic timeout: number = defaultTimeout,\n\t)\n\t{\n\t\t// Initialize the event emitter.\n\t\tsuper();\n\t}\n\n\t/**\n\t * Returns a string for the host identifier for usage in debug messages.\n\t */\n\tget hostIdentifier(): string\n\t{\n\t\treturn `${this.host}:${this.port}`;\n\t}\n\n\t/**\n\t * Connect to host:port using the specified transport\n\t */\n\tconnect(): void\n\t{\n\t\t// Check that no existing socket exists before initiating a new connection.\n\t\tif(this.webSocket)\n\t\t{\n\t\t\tthrow(new Error('Cannot initiate a new socket connection when an existing connection exists'));\n\t\t}\n\n\t\t// Set a timer to force disconnect after `timeout` seconds\n\t\tthis.disconnectTimer = setTimeout(() => this.disconnectOnTimeout(), this.timeout) as unknown as number;\n\n\t\t// Remove the timer if a connection is successfully established\n\t\tthis.once('connected', this.clearDisconnectTimerOnTimeout);\n\n\t\t// Set a named connection type for logging purposes.\n\t\tconst connectionType = (this.encrypted ? 'an encrypted WebSocket' : 'a WebSocket');\n\n\t\t// Log that we are trying to establish a connection.\n\t\tdebug.network(`Initiating ${connectionType} connection to '${this.host}:${this.port}'.`);\n\n\t\tif(this.encrypted)\n\t\t{\n\t\t\t// Initialize this.webSocket (rejecting self-signed certificates).\n\t\t\t// We reject self-signed certificates to match functionality of browsers.\n\t\t\tthis.webSocket = new WebSocket(`wss://${this.host}:${this.port}`);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Initialize this.webSocket.\n\t\t\tthis.webSocket = new WebSocket(`ws://${this.host}:${this.port}`);\n\t\t}\n\n\t\t// Trigger successful connection events.\n\t\tthis.webSocket.addEventListener('open', this.onConnect.bind(this));\n\n\t\t// Forward the encountered errors.\n\t\tthis.webSocket.addEventListener('error', this.eventForwarders.wsError);\n\t}\n\n\t/**\n\t * Sets up forwarding of events related to the connection.\n\t */\n\tprivate onConnect(): void\n\t{\n\t\t// If the onConnect function has already run, do not execute it again.\n\t\tif(this.onConnectHasRun) return;\n\n\t\t// Set a named connection type for logging purposes.\n\t\tconst connectionType = (this.encrypted ? 'an encrypted WebSocket' : 'a WebSocket');\n\n\t\t// Log that the connection has been established.\n\t\tdebug.network(`Established ${connectionType} connection with '${this.host}:${this.port}'.`);\n\n\t\t// Forward the socket events\n\t\tthis.webSocket.addEventListener('close', this.eventForwarders.disconnect);\n\t\tthis.webSocket.addEventListener('message', this.eventForwarders.wsData);\n\n\t\t// Indicate that the onConnect function has run.\n\t\tthis.onConnectHasRun = true;\n\n\t\t// Emit the connect event.\n\t\tthis.emit('connected');\n\t}\n\n\t/**\n\t * Clears the disconnect timer if it is still active.\n\t */\n\tprivate clearDisconnectTimerOnTimeout(): void\n\t{\n\t\t// Clear the retry timer if it is still active.\n\t\tif(this.disconnectTimer)\n\t\t{\n\t\t\tclearTimeout(this.disconnectTimer);\n\t\t}\n\t}\n\n\t/**\n\t * Forcibly terminate the connection.\n\t *\n\t * @throws {Error} if no connection was found\n\t */\n\tpublic disconnect(): void\n\t{\n\t\t// Clear the disconnect timer so that the socket does not try to disconnect again later.\n\t\tthis.clearDisconnectTimerOnTimeout();\n\n\t\ttry\n\t\t{\n\t\t\t// Remove all event forwarders.\n\t\t\tthis.webSocket.removeEventListener('close', this.eventForwarders.disconnect);\n\t\t\tthis.webSocket.removeEventListener('message', this.eventForwarders.wsData);\n\t\t\tthis.webSocket.removeEventListener('error', this.eventForwarders.wsError);\n\n\t\t\t// Gracefully terminate the connection.\n\t\t\tthis.webSocket.close();\n\t\t}\n\t\tcatch(ignored)\n\t\t{\n\t\t\t// close() will throw an error if the connection has not been established yet.\n\t\t\t// We ignore this error, since no similar error gets thrown in the TLS Socket.\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\t// Remove the stored socket regardless of any thrown errors.\n\t\t\tthis.webSocket = undefined;\n\t\t}\n\n\t\t// Indicate that the onConnect function has not run and it has to be run again.\n\t\tthis.onConnectHasRun = false;\n\n\t\t// Emit a disconnect event\n\t\tthis.emit('disconnected');\n\t}\n\n\t/**\n\t * Write data to the socket\n\t *\n\t * @param data Data to be written to the socket\n\t * @param callback Callback function to be called when the write has completed\n\t *\n\t * @throws {Error} if no connection was found\n\t * @returns true if the message was fully flushed to the socket, false if part of the message\n\t * is queued in the user memory\n\t */\n\tpublic write(data: Uint8Array | string, callback?: (err?: Error) => void): boolean\n\t{\n\t\t// Throw an error if no active connection is found\n\t\tif(!this.webSocket)\n\t\t{\n\t\t\tthrow(new Error('Cannot write to socket when there is no active connection'));\n\t\t}\n\n\t\t// Write data to the WebSocket\n\t\tthis.webSocket.send(data, callback);\n\n\t\t// WebSockets always fit everything in a single request, so we return true\n\t\treturn true;\n\t}\n\n\t/**\n\t * Force a disconnection if no connection is established after `timeout` milliseconds.\n\t */\n\tprivate disconnectOnTimeout(): void\n\t{\n\t\t// Remove the connect listener.\n\t\tthis.removeListener('connected', this.clearDisconnectTimerOnTimeout);\n\n\t\t// Emit an error event so that connect is rejected upstream.\n\t\tthis.emit('error', new Error(`Connection to '${this.host}:${this.port}' timed out after ${this.timeout} milliseconds`));\n\n\t\t// Forcibly disconnect to clean up the connection on timeout\n\t\tthis.disconnect();\n\t}\n\n\t// Add magic glue that makes typedoc happy so that we can have the events listed on the class.\n\tpublic readonly connected: [];\n\tpublic readonly disconnected: [];\n\tpublic readonly data: [ string ];\n\tpublic readonly error: [ Error ];\n}\n","// Export a default timeout value of 30 seconds.\nexport const defaultTimeout = 30 * 1000;\n"],"names":[],"version":3,"file":"index.mjs.map"}
|
|
1
|
+
{"mappings":";;;;;;;;;;;;;;AEAA,gDAAgD;AACzC,MAAM,4CAAiB;;;ADUvB,MAAM,iDAA0B,CAAA,GAAA,mBAAW;;;;;IAEjD,8BAA8B;IACtB,UAAqB;IAE7B,wEAAwE;IAChE,gBAAyB;IAEjC,kGAAkG;IAC1F,gBAAwB;IAEhC,yCAAyC;IACjC,gBAKN;IAEF;;;;;;;EAOC,GACD,YAEC,AAAO,IAAY,EACnB,AAAO,OAAe,KAAK,EAC3B,AAAO,YAAqB,IAAI,EAChC,AAAO,UAAkB,CAAA,GAAA,yCAAa,CAAC,CAExC;QACC,gCAAgC;QAChC,KAAK,SAPE,OAAA,WACA,OAAA,WACA,YAAA,gBACA,UAAA,cAvBA,kBAAkB,YAGlB,kBACR;YACC,YAAY,IAAqB,IAAI,CAAC,IAAI,CAAC;YAC3C,QAAQ,CAAC,QAAwB,IAAI,CAAC,IAAI,CAAC,QAAQ,GAAG,MAAM,I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E3C,sCAAsC;YACtC,IAAI,CAAC,SAAS,CAAC,KAAK;QACrB,EACA,OAAM,SACN;QACC,8EAA8E;QAC9E,8EAA8E;QAC/E,SAEA;YACC,4DAA4D;YAC5D,IAAI,CAAC,SAAS,GAAG;QAClB;QAEA,+EAA+E;QAC/E,IAAI,CAAC,eAAe,GAAG;QAEvB,0BAA0B;QAC1B,IAAI,CAAC,IAAI,CAAC;IACX;IAEA;;;;;;;;;EASC,GACD,AAAO,MAAM,IAAyB,EAAE,QAAgC,EACxE;QACC,kDAAkD;QAClD,IAAG,CAAC,IAAI,CAAC,SAAS,EAEjB,MAAM,IAAI,MAAM;QAGjB,8BAA8B;QAC9B,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM;QAE1B,0EAA0E;QAC1E,OAAO;IACR;IAEA;;EAEC,GACD,AAAQ,sBACR;QACC,+BAA+B;QAC/B,IAAI,CAAC,cAAc,CAAC,aAAa,IAAI,CAAC,6BAA6B;QAEnE,4DAA4D;QAC5D,IAAI,CAAC,IAAI,CAAC,SAAS,IAAI,MAAM,CAAC,eAAe,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC;QAErH,4DAA4D;QAC5D,IAAI,CAAC,UAAU;IAChB;IAEA,8FAA8F;IAC9E,UAAc;IACd,aAAiB;IACjB,KAAiB;IACjB,MAAiB;AAClC","sources":["source/index.ts","source/web.ts","source/constants.ts"],"sourcesContent":["export * from './web.ts';\n","import { WebSocket } from '@monsterbitar/isomorphic-ws';\nimport { EventEmitter } from 'eventemitter3';\nimport debug from '@electrum-cash/debug-logs';\nimport { defaultTimeout } from './constants';\n\nimport type { MessageEvent, ErrorEvent } from '@monsterbitar/isomorphic-ws';\nimport type { ElectrumSocket, ElectrumSocketEvents } from '@electrum-cash/network';\n\n/**\n * Web Socket used when communicating with Electrum servers.\n */\nexport class ElectrumWebSocket extends EventEmitter<ElectrumSocketEvents> implements ElectrumSocket\n{\n\t// Declare an empty WebSocket.\n\tprivate webSocket: WebSocket;\n\n\t// Used to disconnect after some time if initial connection is too slow.\n\tprivate disconnectTimer?: number;\n\n\t// Initialize boolean that indicates whether the onConnect function has run (initialize to false).\n\tprivate onConnectHasRun = false;\n\n\t// Initialize event forwarding functions.\n\tprivate eventForwarders =\n\t{\n\t\tdisconnect: () => this.emit('disconnected'),\n\t\twsData: (event: MessageEvent) => this.emit('data', `${event.data}\\n`),\n\t\twsError: (event: ErrorEvent) => this.emit('error', new Error(event.error)),\n\t};\n\n\t/**\n\t * Creates a socket configured with connection information for a given Electrum server.\n\t *\n\t * @param host Fully qualified domain name or IP address of the host\n\t * @param port Network port for the host to connect to, defaults to the standard TLS port\n\t * @param encrypted If false, uses an unencrypted connection instead of the default on TLS\n\t * @param timeout If no connection is established after `timeout` ms, the connection is terminated\n\t */\n\tpublic constructor\n\t(\n\t\tpublic host: string,\n\t\tpublic port: number = 50004,\n\t\tpublic encrypted: boolean = true,\n\t\tpublic timeout: number = defaultTimeout,\n\t)\n\t{\n\t\t// Initialize the event emitter.\n\t\tsuper();\n\t}\n\n\t/**\n\t * Returns a string for the host identifier for usage in debug messages.\n\t */\n\tget hostIdentifier(): string\n\t{\n\t\treturn `${this.host}:${this.port}`;\n\t}\n\n\t/**\n\t * Connect to host:port using the specified transport\n\t */\n\tconnect(): void\n\t{\n\t\t// Check that no existing socket exists before initiating a new connection.\n\t\tif(this.webSocket)\n\t\t{\n\t\t\tthrow(new Error('Cannot initiate a new socket connection when an existing connection exists'));\n\t\t}\n\n\t\t// Set a timer to force disconnect after `timeout` seconds\n\t\tthis.disconnectTimer = setTimeout(() => this.disconnectOnTimeout(), this.timeout) as unknown as number;\n\n\t\t// Remove the timer if a connection is successfully established\n\t\tthis.once('connected', this.clearDisconnectTimerOnTimeout);\n\n\t\t// Set a named connection type for logging purposes.\n\t\tconst connectionType = (this.encrypted ? 'an encrypted WebSocket' : 'a WebSocket');\n\n\t\t// Log that we are trying to establish a connection.\n\t\tdebug.network(`Initiating ${connectionType} connection to '${this.host}:${this.port}'.`);\n\n\t\tif(this.encrypted)\n\t\t{\n\t\t\t// Initialize this.webSocket (rejecting self-signed certificates).\n\t\t\t// We reject self-signed certificates to match functionality of browsers.\n\t\t\tthis.webSocket = new WebSocket(`wss://${this.host}:${this.port}`);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Initialize this.webSocket.\n\t\t\tthis.webSocket = new WebSocket(`ws://${this.host}:${this.port}`);\n\t\t}\n\n\t\t// Trigger successful connection events.\n\t\tthis.webSocket.addEventListener('open', this.onConnect.bind(this));\n\n\t\t// Forward the encountered errors.\n\t\tthis.webSocket.addEventListener('error', this.eventForwarders.wsError);\n\t}\n\n\t/**\n\t * Sets up forwarding of events related to the connection.\n\t */\n\tprivate onConnect(): void\n\t{\n\t\t// If the onConnect function has already run, do not execute it again.\n\t\tif(this.onConnectHasRun) return;\n\n\t\t// Set a named connection type for logging purposes.\n\t\tconst connectionType = (this.encrypted ? 'an encrypted WebSocket' : 'a WebSocket');\n\n\t\t// Log that the connection has been established.\n\t\tdebug.network(`Established ${connectionType} connection with '${this.host}:${this.port}'.`);\n\n\t\t// Forward the socket events\n\t\tthis.webSocket.addEventListener('close', this.eventForwarders.disconnect);\n\t\tthis.webSocket.addEventListener('message', this.eventForwarders.wsData);\n\n\t\t// Indicate that the onConnect function has run.\n\t\tthis.onConnectHasRun = true;\n\n\t\t// Emit the connect event.\n\t\tthis.emit('connected');\n\t}\n\n\t/**\n\t * Clears the disconnect timer if it is still active.\n\t */\n\tprivate clearDisconnectTimerOnTimeout(): void\n\t{\n\t\t// Clear the retry timer if it is still active.\n\t\tif(this.disconnectTimer)\n\t\t{\n\t\t\tclearTimeout(this.disconnectTimer);\n\t\t}\n\t}\n\n\t/**\n\t * Forcibly terminate the connection.\n\t *\n\t * @throws {Error} if no connection was found\n\t */\n\tpublic disconnect(): void\n\t{\n\t\t// Clear the disconnect timer so that the socket does not try to disconnect again later.\n\t\tthis.clearDisconnectTimerOnTimeout();\n\n\t\ttry\n\t\t{\n\t\t\t// Remove all event forwarders.\n\t\t\tthis.webSocket.removeEventListener('close', this.eventForwarders.disconnect);\n\t\t\tthis.webSocket.removeEventListener('message', this.eventForwarders.wsData);\n\t\t\tthis.webSocket.removeEventListener('error', this.eventForwarders.wsError);\n\n\t\t\t// Add a one-time event listener for potential error events after closing the socket.\n\t\t\t// NOTE: This is needed since the close() call might not result in an error itself, but the\n\t\t\t// underlying network packets that are sent in order to do a graceful termination can fail.\n\t\t\tthis.webSocket.once('error', (ignored) => {});\n\n\t\t\t// Gracefully terminate the connection\n\t\t\tthis.webSocket.close();\n\t\t}\n\t\tcatch(ignored)\n\t\t{\n\t\t\t// close() will throw an error if the connection has not been established yet.\n\t\t\t// We ignore this error, since no similar error gets thrown in the TLS Socket.\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\t// Remove the stored socket regardless of any thrown errors.\n\t\t\tthis.webSocket = undefined;\n\t\t}\n\n\t\t// Indicate that the onConnect function has not run and it has to be run again.\n\t\tthis.onConnectHasRun = false;\n\n\t\t// Emit a disconnect event\n\t\tthis.emit('disconnected');\n\t}\n\n\t/**\n\t * Write data to the socket\n\t *\n\t * @param data Data to be written to the socket\n\t * @param callback Callback function to be called when the write has completed\n\t *\n\t * @throws {Error} if no connection was found\n\t * @returns true if the message was fully flushed to the socket, false if part of the message\n\t * is queued in the user memory\n\t */\n\tpublic write(data: Uint8Array | string, callback?: (err?: Error) => void): boolean\n\t{\n\t\t// Throw an error if no active connection is found\n\t\tif(!this.webSocket)\n\t\t{\n\t\t\tthrow(new Error('Cannot write to socket when there is no active connection'));\n\t\t}\n\n\t\t// Write data to the WebSocket\n\t\tthis.webSocket.send(data, callback);\n\n\t\t// WebSockets always fit everything in a single request, so we return true\n\t\treturn true;\n\t}\n\n\t/**\n\t * Force a disconnection if no connection is established after `timeout` milliseconds.\n\t */\n\tprivate disconnectOnTimeout(): void\n\t{\n\t\t// Remove the connect listener.\n\t\tthis.removeListener('connected', this.clearDisconnectTimerOnTimeout);\n\n\t\t// Emit an error event so that connect is rejected upstream.\n\t\tthis.emit('error', new Error(`Connection to '${this.host}:${this.port}' timed out after ${this.timeout} milliseconds`));\n\n\t\t// Forcibly disconnect to clean up the connection on timeout\n\t\tthis.disconnect();\n\t}\n\n\t// Add magic glue that makes typedoc happy so that we can have the events listed on the class.\n\tpublic readonly connected: [];\n\tpublic readonly disconnected: [];\n\tpublic readonly data: [ string ];\n\tpublic readonly error: [ Error ];\n}\n","// Export a default timeout value of 30 seconds.\nexport const defaultTimeout = 30 * 1000;\n"],"names":[],"version":3,"file":"index.mjs.map"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@electrum-cash/web-socket",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"description": "@electrum-cash/web-socket implements the ElectrumSocket interface using web sockets.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"electrum",
|
|
@@ -46,9 +46,9 @@
|
|
|
46
46
|
"@parcel/transformer-typescript-types": "^2.12.0",
|
|
47
47
|
"@types/debug": "^4.1.6",
|
|
48
48
|
"@typescript-eslint/eslint-plugin": "^6.8.0",
|
|
49
|
-
"@vitest/coverage-v8": "^
|
|
49
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
50
50
|
"cspell": "^8.6.0",
|
|
51
|
-
"del-cli": "^
|
|
51
|
+
"del-cli": "^7.0.0",
|
|
52
52
|
"eslint": "^8.42.0",
|
|
53
53
|
"eslint-plugin-import": "^2.23.4",
|
|
54
54
|
"events": "^3.3.0",
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
"typedoc": "^0.25.12",
|
|
57
57
|
"typedoc-plugin-coverage": "^3.1.0",
|
|
58
58
|
"typescript": "^5.1.3",
|
|
59
|
-
"vitest": "^
|
|
59
|
+
"vitest": "^3.2.4"
|
|
60
60
|
},
|
|
61
61
|
"dependencies": {
|
|
62
62
|
"@electrum-cash/debug-logs": "^1.0.0",
|