@electrum-cash/web-socket 1.0.3 → 1.1.0-development.12711255916
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/README.md +1 -91
- package/dist/index.d.mts +139 -0
- package/dist/index.mjs +122 -165
- package/dist/index.mjs.map +1 -1
- package/package.json +15 -15
- package/dist/index.d.ts +0 -51
- package/dist/index.d.ts.map +0 -1
package/README.md
CHANGED
|
@@ -1,93 +1,3 @@
|
|
|
1
1
|
# Electrum-Cash Web Socket
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
## Getting started
|
|
6
|
-
|
|
7
|
-
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
|
8
|
-
|
|
9
|
-
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
|
10
|
-
|
|
11
|
-
## Add your files
|
|
12
|
-
|
|
13
|
-
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
|
|
14
|
-
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
|
|
15
|
-
|
|
16
|
-
```
|
|
17
|
-
cd existing_repo
|
|
18
|
-
git remote add origin https://gitlab.com/electrum-cash/web-socket.git
|
|
19
|
-
git branch -M main
|
|
20
|
-
git push -uf origin main
|
|
21
|
-
```
|
|
22
|
-
|
|
23
|
-
## Integrate with your tools
|
|
24
|
-
|
|
25
|
-
- [ ] [Set up project integrations](https://gitlab.com/electrum-cash/web-socket/-/settings/integrations)
|
|
26
|
-
|
|
27
|
-
## Collaborate with your team
|
|
28
|
-
|
|
29
|
-
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
|
|
30
|
-
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
|
|
31
|
-
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
|
|
32
|
-
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
|
|
33
|
-
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
|
|
34
|
-
|
|
35
|
-
## Test and Deploy
|
|
36
|
-
|
|
37
|
-
Use the built-in continuous integration in GitLab.
|
|
38
|
-
|
|
39
|
-
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
|
|
40
|
-
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
|
|
41
|
-
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
|
|
42
|
-
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
|
43
|
-
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
|
44
|
-
|
|
45
|
-
***
|
|
46
|
-
|
|
47
|
-
# Editing this README
|
|
48
|
-
|
|
49
|
-
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
|
50
|
-
|
|
51
|
-
## Suggestions for a good README
|
|
52
|
-
|
|
53
|
-
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
|
54
|
-
|
|
55
|
-
## Name
|
|
56
|
-
Choose a self-explaining name for your project.
|
|
57
|
-
|
|
58
|
-
## Description
|
|
59
|
-
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
|
60
|
-
|
|
61
|
-
## Badges
|
|
62
|
-
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
|
63
|
-
|
|
64
|
-
## Visuals
|
|
65
|
-
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
|
66
|
-
|
|
67
|
-
## Installation
|
|
68
|
-
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
|
69
|
-
|
|
70
|
-
## Usage
|
|
71
|
-
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
|
72
|
-
|
|
73
|
-
## Support
|
|
74
|
-
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
|
75
|
-
|
|
76
|
-
## Roadmap
|
|
77
|
-
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
|
78
|
-
|
|
79
|
-
## Contributing
|
|
80
|
-
State if you are open to contributions and what your requirements are for accepting them.
|
|
81
|
-
|
|
82
|
-
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
|
83
|
-
|
|
84
|
-
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
|
85
|
-
|
|
86
|
-
## Authors and acknowledgment
|
|
87
|
-
Show your appreciation to those who have contributed to the project.
|
|
88
|
-
|
|
89
|
-
## License
|
|
90
|
-
For open source projects, say how it is licensed.
|
|
91
|
-
|
|
92
|
-
## Project status
|
|
93
|
-
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
|
3
|
+
This package provides an `ElectrumSocket` implementation using a web socket from the `@monsterbitar/isomorphic-ws` package.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { EventEmitter } from "eventemitter3";
|
|
2
|
+
|
|
3
|
+
//#region node_modules/@electrum-cash/network/dist/index.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* List of events emitted by the ElectrumSocket.
|
|
7
|
+
* @event
|
|
8
|
+
* @ignore
|
|
9
|
+
*/
|
|
10
|
+
interface ElectrumSocketEvents {
|
|
11
|
+
/**
|
|
12
|
+
* Emitted when data has been received over the socket.
|
|
13
|
+
* @eventProperty
|
|
14
|
+
*/
|
|
15
|
+
'data': [string];
|
|
16
|
+
/**
|
|
17
|
+
* Emitted when a socket connects.
|
|
18
|
+
* @eventProperty
|
|
19
|
+
*/
|
|
20
|
+
'connected': [];
|
|
21
|
+
/**
|
|
22
|
+
* Emitted when a socket disconnects.
|
|
23
|
+
* @eventProperty
|
|
24
|
+
*/
|
|
25
|
+
'disconnected': [];
|
|
26
|
+
/**
|
|
27
|
+
* Emitted when the socket has failed in some way.
|
|
28
|
+
* @eventProperty
|
|
29
|
+
*/
|
|
30
|
+
'error': [Error];
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Abstract socket used when communicating with Electrum servers.
|
|
34
|
+
*/
|
|
35
|
+
interface ElectrumSocket extends EventEmitter<ElectrumSocketEvents>, ElectrumSocketEvents {
|
|
36
|
+
/**
|
|
37
|
+
* Utility function to provide a human accessible host identifier.
|
|
38
|
+
*/
|
|
39
|
+
get hostIdentifier(): string;
|
|
40
|
+
/**
|
|
41
|
+
* Fully qualified domain name or IP address of the host
|
|
42
|
+
*/
|
|
43
|
+
host: string;
|
|
44
|
+
/**
|
|
45
|
+
* Network port for the host to connect to, defaults to the standard TLS port
|
|
46
|
+
*/
|
|
47
|
+
port: number;
|
|
48
|
+
/**
|
|
49
|
+
* If false, uses an unencrypted connection instead of the default on TLS
|
|
50
|
+
*/
|
|
51
|
+
encrypted: boolean;
|
|
52
|
+
/**
|
|
53
|
+
* If no connection is established after `timeout` ms, the connection is terminated
|
|
54
|
+
*/
|
|
55
|
+
timeout: number;
|
|
56
|
+
/**
|
|
57
|
+
* Connects to an Electrum server using the socket.
|
|
58
|
+
*/
|
|
59
|
+
connect(): void;
|
|
60
|
+
/**
|
|
61
|
+
* Disconnects from the Electrum server from the socket.
|
|
62
|
+
*/
|
|
63
|
+
disconnect(): void;
|
|
64
|
+
/**
|
|
65
|
+
* Write data to the Electrum server on the socket.
|
|
66
|
+
*
|
|
67
|
+
* @param data - Data to be written to the socket
|
|
68
|
+
* @param callback - Callback function to be called when the write has completed
|
|
69
|
+
*/
|
|
70
|
+
write(data: Uint8Array | string, callback?: (err?: Error) => void): boolean;
|
|
71
|
+
}
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region source/web.d.ts
|
|
74
|
+
/**
|
|
75
|
+
* Web Socket used when communicating with Electrum servers.
|
|
76
|
+
*/
|
|
77
|
+
declare class ElectrumWebSocket extends EventEmitter<ElectrumSocketEvents> implements ElectrumSocket {
|
|
78
|
+
host: string;
|
|
79
|
+
port: number;
|
|
80
|
+
encrypted: boolean;
|
|
81
|
+
timeout: number;
|
|
82
|
+
private webSocket;
|
|
83
|
+
private disconnectTimer?;
|
|
84
|
+
private onConnectHasRun;
|
|
85
|
+
private eventForwarders;
|
|
86
|
+
/**
|
|
87
|
+
* Creates a socket configured with connection information for a given Electrum server.
|
|
88
|
+
*
|
|
89
|
+
* @param host Fully qualified domain name or IP address of the host
|
|
90
|
+
* @param port Network port for the host to connect to, defaults to the standard TLS port
|
|
91
|
+
* @param encrypted If false, uses an unencrypted connection instead of the default on TLS
|
|
92
|
+
* @param timeout If no connection is established after `timeout` ms, the connection is terminated
|
|
93
|
+
*/
|
|
94
|
+
constructor(host: string, port?: number, encrypted?: boolean, timeout?: number);
|
|
95
|
+
/**
|
|
96
|
+
* Returns a string for the host identifier for usage in debug messages.
|
|
97
|
+
*/
|
|
98
|
+
get hostIdentifier(): string;
|
|
99
|
+
/**
|
|
100
|
+
* Connect to host:port using the specified transport
|
|
101
|
+
*/
|
|
102
|
+
connect(): void;
|
|
103
|
+
/**
|
|
104
|
+
* Sets up forwarding of events related to the connection.
|
|
105
|
+
*/
|
|
106
|
+
private onConnect;
|
|
107
|
+
/**
|
|
108
|
+
* Clears the disconnect timer if it is still active.
|
|
109
|
+
*/
|
|
110
|
+
private clearDisconnectTimerOnTimeout;
|
|
111
|
+
/**
|
|
112
|
+
* Forcibly terminate the connection.
|
|
113
|
+
*
|
|
114
|
+
* @throws {Error} if no connection was found
|
|
115
|
+
*/
|
|
116
|
+
disconnect(): void;
|
|
117
|
+
/**
|
|
118
|
+
* Write data to the socket
|
|
119
|
+
*
|
|
120
|
+
* @param data Data to be written to the socket
|
|
121
|
+
* @param callback Callback function to be called when the write has completed
|
|
122
|
+
*
|
|
123
|
+
* @throws {Error} if no connection was found
|
|
124
|
+
* @returns true if the message was fully flushed to the socket, false if part of the message
|
|
125
|
+
* is queued in the user memory
|
|
126
|
+
*/
|
|
127
|
+
write(data: Uint8Array | string, callback?: (err?: Error) => void): boolean;
|
|
128
|
+
/**
|
|
129
|
+
* Force a disconnection if no connection is established after `timeout` milliseconds.
|
|
130
|
+
*/
|
|
131
|
+
private disconnectOnTimeout;
|
|
132
|
+
readonly connected: [];
|
|
133
|
+
readonly disconnected: [];
|
|
134
|
+
readonly data: [string];
|
|
135
|
+
readonly error: [Error];
|
|
136
|
+
}
|
|
137
|
+
//#endregion
|
|
138
|
+
export { ElectrumWebSocket };
|
|
139
|
+
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.mjs
CHANGED
|
@@ -1,168 +1,125 @@
|
|
|
1
|
-
import {WebSocket
|
|
2
|
-
import {EventEmitter
|
|
3
|
-
import
|
|
1
|
+
import { WebSocket } from "@monsterbitar/isomorphic-ws";
|
|
2
|
+
import { EventEmitter } from "eventemitter3";
|
|
3
|
+
import debug from "@electrum-cash/debug-logs";
|
|
4
4
|
|
|
5
|
+
//#region source/constants.ts
|
|
6
|
+
const defaultTimeout = 30 * 1e3;
|
|
5
7
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
//#endregion
|
|
9
|
+
//#region source/web.ts
|
|
10
|
+
/**
|
|
11
|
+
* Web Socket used when communicating with Electrum servers.
|
|
12
|
+
*/
|
|
13
|
+
var ElectrumWebSocket = class extends EventEmitter {
|
|
14
|
+
webSocket;
|
|
15
|
+
disconnectTimer;
|
|
16
|
+
onConnectHasRun = false;
|
|
17
|
+
eventForwarders = {
|
|
18
|
+
disconnect: () => this.emit("disconnected"),
|
|
19
|
+
wsData: (event) => this.emit("data", `${event.data}\n`),
|
|
20
|
+
wsError: (event) => this.emit("error", new Error(event.error))
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Creates a socket configured with connection information for a given Electrum server.
|
|
24
|
+
*
|
|
25
|
+
* @param host Fully qualified domain name or IP address of the host
|
|
26
|
+
* @param port Network port for the host to connect to, defaults to the standard TLS port
|
|
27
|
+
* @param encrypted If false, uses an unencrypted connection instead of the default on TLS
|
|
28
|
+
* @param timeout If no connection is established after `timeout` ms, the connection is terminated
|
|
29
|
+
*/
|
|
30
|
+
constructor(host, port = 50004, encrypted = true, timeout = defaultTimeout) {
|
|
31
|
+
super();
|
|
32
|
+
this.host = host;
|
|
33
|
+
this.port = port;
|
|
34
|
+
this.encrypted = encrypted;
|
|
35
|
+
this.timeout = timeout;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Returns a string for the host identifier for usage in debug messages.
|
|
39
|
+
*/
|
|
40
|
+
get hostIdentifier() {
|
|
41
|
+
return `${this.host}:${this.port}`;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Connect to host:port using the specified transport
|
|
45
|
+
*/
|
|
46
|
+
connect() {
|
|
47
|
+
if (this.webSocket) throw /* @__PURE__ */ new Error("Cannot initiate a new socket connection when an existing connection exists");
|
|
48
|
+
this.disconnectTimer = setTimeout(() => this.disconnectOnTimeout(), this.timeout);
|
|
49
|
+
this.once("connected", this.clearDisconnectTimerOnTimeout);
|
|
50
|
+
const connectionType = this.encrypted ? "an encrypted WebSocket" : "a WebSocket";
|
|
51
|
+
debug.network(`Initiating ${connectionType} connection to '${this.host}:${this.port}'.`);
|
|
52
|
+
if (this.encrypted) this.webSocket = new WebSocket(`wss://${this.host}:${this.port}`);
|
|
53
|
+
else this.webSocket = new WebSocket(`ws://${this.host}:${this.port}`);
|
|
54
|
+
this.webSocket.addEventListener("open", this.onConnect.bind(this));
|
|
55
|
+
this.webSocket.addEventListener("error", this.eventForwarders.wsError);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Sets up forwarding of events related to the connection.
|
|
59
|
+
*/
|
|
60
|
+
onConnect() {
|
|
61
|
+
if (this.onConnectHasRun) return;
|
|
62
|
+
const connectionType = this.encrypted ? "an encrypted WebSocket" : "a WebSocket";
|
|
63
|
+
debug.network(`Established ${connectionType} connection with '${this.host}:${this.port}'.`);
|
|
64
|
+
this.webSocket.addEventListener("close", this.eventForwarders.disconnect);
|
|
65
|
+
this.webSocket.addEventListener("message", this.eventForwarders.wsData);
|
|
66
|
+
this.onConnectHasRun = true;
|
|
67
|
+
this.emit("connected");
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Clears the disconnect timer if it is still active.
|
|
71
|
+
*/
|
|
72
|
+
clearDisconnectTimerOnTimeout() {
|
|
73
|
+
if (this.disconnectTimer) clearTimeout(this.disconnectTimer);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Forcibly terminate the connection.
|
|
77
|
+
*
|
|
78
|
+
* @throws {Error} if no connection was found
|
|
79
|
+
*/
|
|
80
|
+
disconnect() {
|
|
81
|
+
this.clearDisconnectTimerOnTimeout();
|
|
82
|
+
try {
|
|
83
|
+
this.webSocket.removeEventListener("close", this.eventForwarders.disconnect);
|
|
84
|
+
this.webSocket.removeEventListener("message", this.eventForwarders.wsData);
|
|
85
|
+
this.webSocket.removeEventListener("error", this.eventForwarders.wsError);
|
|
86
|
+
this.webSocket.addEventListener("error", (_ignored) => {}, { once: true });
|
|
87
|
+
this.webSocket.close();
|
|
88
|
+
} catch (_ignored) {} finally {
|
|
89
|
+
this.webSocket = void 0;
|
|
90
|
+
}
|
|
91
|
+
this.onConnectHasRun = false;
|
|
92
|
+
this.emit("disconnected");
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Write data to the socket
|
|
96
|
+
*
|
|
97
|
+
* @param data Data to be written to the socket
|
|
98
|
+
* @param callback Callback function to be called when the write has completed
|
|
99
|
+
*
|
|
100
|
+
* @throws {Error} if no connection was found
|
|
101
|
+
* @returns true if the message was fully flushed to the socket, false if part of the message
|
|
102
|
+
* is queued in the user memory
|
|
103
|
+
*/
|
|
104
|
+
write(data, callback) {
|
|
105
|
+
if (!this.webSocket) throw /* @__PURE__ */ new Error("Cannot write to socket when there is no active connection");
|
|
106
|
+
this.webSocket.send(data, callback);
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Force a disconnection if no connection is established after `timeout` milliseconds.
|
|
111
|
+
*/
|
|
112
|
+
disconnectOnTimeout() {
|
|
113
|
+
this.removeListener("connected", this.clearDisconnectTimerOnTimeout);
|
|
114
|
+
this.emit("error", /* @__PURE__ */ new Error(`Connection to '${this.host}:${this.port}' timed out after ${this.timeout} milliseconds`));
|
|
115
|
+
this.disconnect();
|
|
116
|
+
}
|
|
117
|
+
connected;
|
|
118
|
+
disconnected;
|
|
119
|
+
data;
|
|
120
|
+
error;
|
|
121
|
+
};
|
|
10
122
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
// Export a default timeout value of 30 seconds.
|
|
16
|
-
const $d801b1f9b7fc3074$export$1bddf2b96e25d075 = 30000;
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
class $05743633fea447d4$export$25b4633f61498e1 extends (0, $dvphU$EventEmitter) {
|
|
20
|
-
host;
|
|
21
|
-
port;
|
|
22
|
-
encrypted;
|
|
23
|
-
timeout;
|
|
24
|
-
// Declare an empty WebSocket.
|
|
25
|
-
webSocket;
|
|
26
|
-
// Used to disconnect after some time if initial connection is too slow.
|
|
27
|
-
disconnectTimer;
|
|
28
|
-
// Initialize boolean that indicates whether the onConnect function has run (initialize to false).
|
|
29
|
-
onConnectHasRun;
|
|
30
|
-
// Initialize event forwarding functions.
|
|
31
|
-
eventForwarders;
|
|
32
|
-
/**
|
|
33
|
-
* Creates a socket configured with connection information for a given Electrum server.
|
|
34
|
-
*
|
|
35
|
-
* @param host Fully qualified domain name or IP address of the host
|
|
36
|
-
* @param port Network port for the host to connect to, defaults to the standard TLS port
|
|
37
|
-
* @param encrypted If false, uses an unencrypted connection instead of the default on TLS
|
|
38
|
-
* @param timeout If no connection is established after `timeout` ms, the connection is terminated
|
|
39
|
-
*/ constructor(host, port = 50004, encrypted = true, timeout = (0, $d801b1f9b7fc3074$export$1bddf2b96e25d075)){
|
|
40
|
-
// Initialize the event emitter.
|
|
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))
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Returns a string for the host identifier for usage in debug messages.
|
|
49
|
-
*/ get hostIdentifier() {
|
|
50
|
-
return `${this.host}:${this.port}`;
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Connect to host:port using the specified transport
|
|
54
|
-
*/ connect() {
|
|
55
|
-
// Check that no existing socket exists before initiating a new connection.
|
|
56
|
-
if (this.webSocket) throw new Error('Cannot initiate a new socket connection when an existing connection exists');
|
|
57
|
-
// Set a timer to force disconnect after `timeout` seconds
|
|
58
|
-
this.disconnectTimer = setTimeout(()=>this.disconnectOnTimeout(), this.timeout);
|
|
59
|
-
// Remove the timer if a connection is successfully established
|
|
60
|
-
this.once('connected', this.clearDisconnectTimerOnTimeout);
|
|
61
|
-
// Set a named connection type for logging purposes.
|
|
62
|
-
const connectionType = this.encrypted ? 'an encrypted WebSocket' : 'a WebSocket';
|
|
63
|
-
// Log that we are trying to establish a connection.
|
|
64
|
-
(0, $dvphU$electrumcashdebuglogs).network(`Initiating ${connectionType} connection to '${this.host}:${this.port}'.`);
|
|
65
|
-
if (this.encrypted) // Initialize this.webSocket (rejecting self-signed certificates).
|
|
66
|
-
// We reject self-signed certificates to match functionality of browsers.
|
|
67
|
-
this.webSocket = new (0, $dvphU$WebSocket)(`wss://${this.host}:${this.port}`);
|
|
68
|
-
else // Initialize this.webSocket.
|
|
69
|
-
this.webSocket = new (0, $dvphU$WebSocket)(`ws://${this.host}:${this.port}`);
|
|
70
|
-
// Trigger successful connection events.
|
|
71
|
-
this.webSocket.addEventListener('open', this.onConnect.bind(this));
|
|
72
|
-
// Forward the encountered errors.
|
|
73
|
-
this.webSocket.addEventListener('error', this.eventForwarders.wsError);
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* Sets up forwarding of events related to the connection.
|
|
77
|
-
*/ onConnect() {
|
|
78
|
-
// If the onConnect function has already run, do not execute it again.
|
|
79
|
-
if (this.onConnectHasRun) return;
|
|
80
|
-
// Set a named connection type for logging purposes.
|
|
81
|
-
const connectionType = this.encrypted ? 'an encrypted WebSocket' : 'a WebSocket';
|
|
82
|
-
// Log that the connection has been established.
|
|
83
|
-
(0, $dvphU$electrumcashdebuglogs).network(`Established ${connectionType} connection with '${this.host}:${this.port}'.`);
|
|
84
|
-
// Forward the socket events
|
|
85
|
-
this.webSocket.addEventListener('close', this.eventForwarders.disconnect);
|
|
86
|
-
this.webSocket.addEventListener('message', this.eventForwarders.wsData);
|
|
87
|
-
// Indicate that the onConnect function has run.
|
|
88
|
-
this.onConnectHasRun = true;
|
|
89
|
-
// Emit the connect event.
|
|
90
|
-
this.emit('connected');
|
|
91
|
-
}
|
|
92
|
-
/**
|
|
93
|
-
* Clears the disconnect timer if it is still active.
|
|
94
|
-
*/ clearDisconnectTimerOnTimeout() {
|
|
95
|
-
// Clear the retry timer if it is still active.
|
|
96
|
-
if (this.disconnectTimer) clearTimeout(this.disconnectTimer);
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Forcibly terminate the connection.
|
|
100
|
-
*
|
|
101
|
-
* @throws {Error} if no connection was found
|
|
102
|
-
*/ disconnect() {
|
|
103
|
-
// Clear the disconnect timer so that the socket does not try to disconnect again later.
|
|
104
|
-
this.clearDisconnectTimerOnTimeout();
|
|
105
|
-
try {
|
|
106
|
-
// Remove all event forwarders.
|
|
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.addEventListener('error', (ignored)=>{}, {
|
|
114
|
-
once: true
|
|
115
|
-
});
|
|
116
|
-
// Gracefully terminate the connection
|
|
117
|
-
this.webSocket.close();
|
|
118
|
-
} catch (ignored) {
|
|
119
|
-
// close() will throw an error if the connection has not been established yet.
|
|
120
|
-
// We ignore this error, since no similar error gets thrown in the TLS Socket.
|
|
121
|
-
} finally{
|
|
122
|
-
// Remove the stored socket regardless of any thrown errors.
|
|
123
|
-
this.webSocket = undefined;
|
|
124
|
-
}
|
|
125
|
-
// Indicate that the onConnect function has not run and it has to be run again.
|
|
126
|
-
this.onConnectHasRun = false;
|
|
127
|
-
// Emit a disconnect event
|
|
128
|
-
this.emit('disconnected');
|
|
129
|
-
}
|
|
130
|
-
/**
|
|
131
|
-
* Write data to the socket
|
|
132
|
-
*
|
|
133
|
-
* @param data Data to be written to the socket
|
|
134
|
-
* @param callback Callback function to be called when the write has completed
|
|
135
|
-
*
|
|
136
|
-
* @throws {Error} if no connection was found
|
|
137
|
-
* @returns true if the message was fully flushed to the socket, false if part of the message
|
|
138
|
-
* is queued in the user memory
|
|
139
|
-
*/ write(data, callback) {
|
|
140
|
-
// Throw an error if no active connection is found
|
|
141
|
-
if (!this.webSocket) throw new Error('Cannot write to socket when there is no active connection');
|
|
142
|
-
// Write data to the WebSocket
|
|
143
|
-
this.webSocket.send(data, callback);
|
|
144
|
-
// WebSockets always fit everything in a single request, so we return true
|
|
145
|
-
return true;
|
|
146
|
-
}
|
|
147
|
-
/**
|
|
148
|
-
* Force a disconnection if no connection is established after `timeout` milliseconds.
|
|
149
|
-
*/ disconnectOnTimeout() {
|
|
150
|
-
// Remove the connect listener.
|
|
151
|
-
this.removeListener('connected', this.clearDisconnectTimerOnTimeout);
|
|
152
|
-
// Emit an error event so that connect is rejected upstream.
|
|
153
|
-
this.emit('error', new Error(`Connection to '${this.host}:${this.port}' timed out after ${this.timeout} milliseconds`));
|
|
154
|
-
// Forcibly disconnect to clean up the connection on timeout
|
|
155
|
-
this.disconnect();
|
|
156
|
-
}
|
|
157
|
-
// Add magic glue that makes typedoc happy so that we can have the events listed on the class.
|
|
158
|
-
connected;
|
|
159
|
-
disconnected;
|
|
160
|
-
data;
|
|
161
|
-
error;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
export {$05743633fea447d4$export$25b4633f61498e1 as ElectrumWebSocket};
|
|
168
|
-
//# sourceMappingURL=index.mjs.map
|
|
123
|
+
//#endregion
|
|
124
|
+
export { ElectrumWebSocket };
|
|
125
|
+
//# sourceMappingURL=index.mjs.map
|
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,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,IAAI,CAAC,EAAE,CAAC;YACpE,SAAS,CAAC,QAAuB,IAAI,CAAC,IAAI,CAAC,SAAS,IAAI,MAAM,MAAM,KAAK;QAC1E;IAoBA;IAEA;;EAEC,GACD,IAAI,iBACJ;QACC,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,EAAE;IACnC;IAEA;;EAEC,GACD,UACA;QACC,2EAA2E;QAC3E,IAAG,IAAI,CAAC,SAAS,EAEhB,MAAM,IAAI,MAAM;QAGjB,0DAA0D;QAC1D,IAAI,CAAC,eAAe,GAAG,WAAW,IAAM,I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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.addEventListener('error', (ignored) => {}, { once: true });\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
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../source/constants.ts","../source/web.ts"],"sourcesContent":["// Export a default timeout value of 30 seconds.\nexport const defaultTimeout = 30 * 1000;\n","import { WebSocket } from '@monsterbitar/isomorphic-ws';\nimport { EventEmitter } from 'eventemitter3';\nimport debug from '@electrum-cash/debug-logs';\nimport { defaultTimeout } from './constants.ts';\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.addEventListener('error', (_ignored) => {}, { once: true });\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"],"mappings":";;;;;AACA,MAAa,iBAAiB,KAAK;;;;;;;ACUnC,IAAa,oBAAb,cAAuC,aACvC;CAEC,AAAQ;CAGR,AAAQ;CAGR,AAAQ,kBAAkB;CAG1B,AAAQ,kBACR;EACC,kBAAiC,KAAK,KAAK,eAAe;EAC1D,SAAS,UAAwB,KAAK,KAAK,QAAQ,GAAG,MAAM,KAAK,IAAI;EACrE,UAAU,UAAuB,KAAK,KAAK,SAAS,IAAI,MAAM,MAAM,MAAM,CAAC;EAC3E;;;;;;;;;CAUD,AAAO,YAEN,AAAO,MACP,AAAO,OAAe,OACtB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AoB,WAAW,KAAK,gBAAgB,OAAO;AAC1E,QAAK,UAAU,oBAAoB,SAAS,KAAK,gBAAgB,QAAQ;AAKzE,QAAK,UAAU,iBAAiB,UAAU,aAAa,IAAI,EAAE,MAAM,MAAM,CAAC;AAG1E,QAAK,UAAU,OAAO;WAEhB,UACP,WAKA;AAEC,QAAK,YAAY;;AAIlB,OAAK,kBAAkB;AAGvB,OAAK,KAAK,eAAe;;;;;;;;;;;;CAa1B,AAAO,MAAM,MAA2B,UACxC;AAEC,MAAG,CAAC,KAAK,UAER,uBAAM,IAAI,MAAM,4DAA4D;AAI7E,OAAK,UAAU,KAAK,MAAM,SAAS;AAGnC,SAAO;;;;;CAMR,AAAQ,sBACR;AAEC,OAAK,eAAe,aAAa,KAAK,8BAA8B;AAGpE,OAAK,KAAK,yBAAS,IAAI,MAAM,kBAAkB,KAAK,KAAK,GAAG,KAAK,KAAK,oBAAoB,KAAK,QAAQ,eAAe,CAAC;AAGvH,OAAK,YAAY;;CAIlB,AAAgB;CAChB,AAAgB;CAChB,AAAgB;CAChB,AAAgB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@electrum-cash/web-socket",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.1.0-development.12711255916",
|
|
4
4
|
"description": "@electrum-cash/web-socket implements the ElectrumSocket interface using web sockets.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"electrum",
|
|
@@ -19,43 +19,43 @@
|
|
|
19
19
|
"license": "MIT",
|
|
20
20
|
"source": "./source/index.ts",
|
|
21
21
|
"type": "module",
|
|
22
|
-
"types": "./dist/index.d.
|
|
22
|
+
"types": "./dist/index.d.mts",
|
|
23
23
|
"module": "./dist/index.mjs",
|
|
24
24
|
"exports": {
|
|
25
|
-
"types": "./dist/index.d.
|
|
25
|
+
"types": "./dist/index.d.mts",
|
|
26
26
|
"default": "./dist/index.mjs"
|
|
27
27
|
},
|
|
28
28
|
"files": [
|
|
29
29
|
"dist"
|
|
30
30
|
],
|
|
31
31
|
"scripts": {
|
|
32
|
-
"
|
|
33
|
-
"
|
|
34
|
-
"analyze": "parcel build --reporter @parcel/reporter-bundle-analyzer",
|
|
32
|
+
"build": "tsdown --clean --sourcemap source/index.ts",
|
|
33
|
+
"analyze": "tsdown --clean --no-fixed-extension --sourcemap source/index.ts && esbuild-analyzer dist/",
|
|
35
34
|
"docs": "typedoc --hideGenerator --categorizeByGroup",
|
|
36
|
-
"lint": "eslint
|
|
35
|
+
"lint": "eslint",
|
|
37
36
|
"syntax": "tsc --noEmit",
|
|
38
37
|
"spellcheck": "cspell 'source/**' 'test/**' 'examples/**'",
|
|
39
38
|
"test": "vitest --dir test/ --test-timeout=15000 --passWithNoTests --run --coverage"
|
|
40
39
|
},
|
|
41
40
|
"devDependencies": {
|
|
41
|
+
"@chalp/eslint-airbnb": "^1.3.0",
|
|
42
|
+
"@electrum-cash/eslint-config": "^1.1.0",
|
|
42
43
|
"@electrum-cash/network": "^4.0.2-development.8063220996",
|
|
43
44
|
"@generalprotocols/cspell-dictionary": "git+https://gitlab.com/GeneralProtocols/cspell-dictionary.git",
|
|
44
|
-
"@
|
|
45
|
-
"@parcel/packager-ts": "^2.12.0",
|
|
46
|
-
"@parcel/transformer-typescript-types": "^2.12.0",
|
|
45
|
+
"@stylistic/eslint-plugin": "^5.7.0",
|
|
47
46
|
"@types/debug": "^4.1.6",
|
|
48
|
-
"@typescript-eslint/eslint-plugin": "^
|
|
47
|
+
"@typescript-eslint/eslint-plugin": "^8.53.0",
|
|
48
|
+
"@typescript-eslint/parser": "^8.53.0",
|
|
49
49
|
"@vitest/coverage-v8": "^3.2.4",
|
|
50
|
+
"@viz-kit/esbuild-analyzer": "^1.0.0",
|
|
50
51
|
"cspell": "^8.6.0",
|
|
51
|
-
"
|
|
52
|
-
"eslint": "^8.42.0",
|
|
53
|
-
"eslint-plugin-import": "^2.23.4",
|
|
52
|
+
"eslint": "^9.39.2",
|
|
54
53
|
"events": "^3.3.0",
|
|
55
|
-
"
|
|
54
|
+
"tsdown": "^0.20.0-beta.1",
|
|
56
55
|
"typedoc": "^0.25.12",
|
|
57
56
|
"typedoc-plugin-coverage": "^3.1.0",
|
|
58
57
|
"typescript": "^5.1.3",
|
|
58
|
+
"typescript-eslint": "^8.53.0",
|
|
59
59
|
"vitest": "^3.2.4"
|
|
60
60
|
},
|
|
61
61
|
"dependencies": {
|
package/dist/index.d.ts
DELETED
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
import { EventEmitter } from "eventemitter3";
|
|
2
|
-
import { ElectrumSocket, ElectrumSocketEvents } from "@electrum-cash/network";
|
|
3
|
-
/**
|
|
4
|
-
* Web Socket used when communicating with Electrum servers.
|
|
5
|
-
*/
|
|
6
|
-
export class ElectrumWebSocket extends EventEmitter<ElectrumSocketEvents> implements ElectrumSocket {
|
|
7
|
-
host: string;
|
|
8
|
-
port: number;
|
|
9
|
-
encrypted: boolean;
|
|
10
|
-
timeout: number;
|
|
11
|
-
/**
|
|
12
|
-
* Creates a socket configured with connection information for a given Electrum server.
|
|
13
|
-
*
|
|
14
|
-
* @param host Fully qualified domain name or IP address of the host
|
|
15
|
-
* @param port Network port for the host to connect to, defaults to the standard TLS port
|
|
16
|
-
* @param encrypted If false, uses an unencrypted connection instead of the default on TLS
|
|
17
|
-
* @param timeout If no connection is established after `timeout` ms, the connection is terminated
|
|
18
|
-
*/
|
|
19
|
-
constructor(host: string, port?: number, encrypted?: boolean, timeout?: number);
|
|
20
|
-
/**
|
|
21
|
-
* Returns a string for the host identifier for usage in debug messages.
|
|
22
|
-
*/
|
|
23
|
-
get hostIdentifier(): string;
|
|
24
|
-
/**
|
|
25
|
-
* Connect to host:port using the specified transport
|
|
26
|
-
*/
|
|
27
|
-
connect(): void;
|
|
28
|
-
/**
|
|
29
|
-
* Forcibly terminate the connection.
|
|
30
|
-
*
|
|
31
|
-
* @throws {Error} if no connection was found
|
|
32
|
-
*/
|
|
33
|
-
disconnect(): void;
|
|
34
|
-
/**
|
|
35
|
-
* Write data to the socket
|
|
36
|
-
*
|
|
37
|
-
* @param data Data to be written to the socket
|
|
38
|
-
* @param callback Callback function to be called when the write has completed
|
|
39
|
-
*
|
|
40
|
-
* @throws {Error} if no connection was found
|
|
41
|
-
* @returns true if the message was fully flushed to the socket, false if part of the message
|
|
42
|
-
* is queued in the user memory
|
|
43
|
-
*/
|
|
44
|
-
write(data: Uint8Array | string, callback?: (err?: Error) => void): boolean;
|
|
45
|
-
readonly connected: [];
|
|
46
|
-
readonly disconnected: [];
|
|
47
|
-
readonly data: [string];
|
|
48
|
-
readonly error: [Error];
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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"}
|