@electrum-cash/web-socket 1.0.0

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 ADDED
@@ -0,0 +1,93 @@
1
+ # Electrum-Cash Web Socket
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.
@@ -0,0 +1,51 @@
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
@@ -0,0 +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;IAiCzB;;;;;;;;;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 ADDED
@@ -0,0 +1,168 @@
1
+ import {WebSocket as $dvphU$WebSocket} from "@monsterbitar/isomorphic-ws";
2
+ import {EventEmitter as $dvphU$EventEmitter} from "eventemitter3";
3
+ import $dvphU$electrumcashdebuglogs from "@electrum-cash/debug-logs";
4
+
5
+
6
+ function $parcel$export(e, n, v, s) {
7
+ Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
8
+ }
9
+ var $05743633fea447d4$exports = {};
10
+
11
+ $parcel$export($05743633fea447d4$exports, "ElectrumWebSocket", () => $05743633fea447d4$export$25b4633f61498e1);
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();
42
+ this.host = host;
43
+ this.port = port;
44
+ this.encrypted = encrypted;
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))
51
+ };
52
+ }
53
+ /**
54
+ * Returns a string for the host identifier for usage in debug messages.
55
+ */ get hostIdentifier() {
56
+ return `${this.host}:${this.port}`;
57
+ }
58
+ /**
59
+ * Connect to host:port using the specified transport
60
+ */ connect() {
61
+ // Check that no existing socket exists before initiating a new connection.
62
+ if (this.webSocket) throw new Error("Cannot initiate a new socket connection when an existing connection exists");
63
+ // Set a timer to force disconnect after `timeout` seconds
64
+ this.disconnectTimer = setTimeout(()=>this.disconnectOnTimeout(), this.timeout);
65
+ // Remove the timer if a connection is successfully established
66
+ this.once("connected", this.clearDisconnectTimerOnTimeout);
67
+ // Set a named connection type for logging purposes.
68
+ const connectionType = this.encrypted ? "an encrypted WebSocket" : "a WebSocket";
69
+ // Log that we are trying to establish a connection.
70
+ (0, $dvphU$electrumcashdebuglogs).network(`Initiating ${connectionType} connection to '${this.host}:${this.port}'.`);
71
+ if (this.encrypted) // Initialize this.webSocket (rejecting self-signed certificates).
72
+ // We reject self-signed certificates to match functionality of browsers.
73
+ this.webSocket = new (0, $dvphU$WebSocket)(`wss://${this.host}:${this.port}`);
74
+ else // Initialize this.webSocket.
75
+ this.webSocket = new (0, $dvphU$WebSocket)(`ws://${this.host}:${this.port}`);
76
+ // Trigger successful connection events.
77
+ this.webSocket.addEventListener("open", this.onConnect.bind(this));
78
+ // Forward the encountered errors.
79
+ this.webSocket.addEventListener("error", this.eventForwarders.wsError);
80
+ }
81
+ /**
82
+ * Sets up forwarding of events related to the connection.
83
+ */ onConnect() {
84
+ // If the onConnect function has already run, do not execute it again.
85
+ if (this.onConnectHasRun) return;
86
+ // Set a named connection type for logging purposes.
87
+ const connectionType = this.encrypted ? "an encrypted WebSocket" : "a WebSocket";
88
+ // Log that the connection has been established.
89
+ (0, $dvphU$electrumcashdebuglogs).network(`Established ${connectionType} connection with '${this.host}:${this.port}'.`);
90
+ // Forward the socket events
91
+ this.webSocket.addEventListener("close", this.eventForwarders.disconnect);
92
+ this.webSocket.addEventListener("message", this.eventForwarders.wsData);
93
+ // Indicate that the onConnect function has run.
94
+ this.onConnectHasRun = true;
95
+ // Emit the connect event.
96
+ this.emit("connected");
97
+ }
98
+ /**
99
+ * Clears the disconnect timer if it is still active.
100
+ */ clearDisconnectTimerOnTimeout() {
101
+ // Clear the retry timer if it is still active.
102
+ if (this.disconnectTimer) clearTimeout(this.disconnectTimer);
103
+ }
104
+ /**
105
+ * Forcibly terminate the connection.
106
+ *
107
+ * @throws {Error} if no connection was found
108
+ */ disconnect() {
109
+ // Clear the disconnect timer so that the socket does not try to disconnect again later.
110
+ this.clearDisconnectTimerOnTimeout();
111
+ try {
112
+ // Remove all event forwarders.
113
+ this.webSocket.removeEventListener("close", this.eventForwarders.disconnect);
114
+ this.webSocket.removeEventListener("message", this.eventForwarders.wsData);
115
+ this.webSocket.removeEventListener("error", this.eventForwarders.wsError);
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
@@ -0,0 +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;aAPE,OAAA;aACA,OAAA;aACA,YAAA;aACA,UAAA;aAvBA,kBAAkB;aAGlB,kBACR;YACC,YAAY,IAAqB,IAAI,CAAC,IAAI,CAAC;YAC3C,QAAQ,CAAC,QAAwB,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,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,CAAC,EA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,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// 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 ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@electrum-cash/web-socket",
3
+ "version": "1.0.0",
4
+ "description": "@electrum-cash/web-socket implements the ElectrumSocket interface using web sockets.",
5
+ "keywords": [
6
+ "electrum",
7
+ "bitcoin",
8
+ "bitcoin cash"
9
+ ],
10
+ "homepage": "https://gitlab.com/electrum-cash/web-socket#readme",
11
+ "bugs": {
12
+ "url": "https://gitlab.com/electrum-cash/web-socket/issues"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://gitlab.com/electrum-cash/web-socket.git"
17
+ },
18
+ "author": "Jonathan Silverblood",
19
+ "license": "MIT",
20
+ "source": "./source/index.ts",
21
+ "type": "module",
22
+ "types": "./dist/index.d.ts",
23
+ "module": "./dist/index.mjs",
24
+ "exports": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.mjs"
27
+ },
28
+ "files": [
29
+ "dist"
30
+ ],
31
+ "scripts": {
32
+ "clean": "del ./dist",
33
+ "build": "npm run clean && parcel build",
34
+ "analyze": "parcel build --reporter @parcel/reporter-bundle-analyzer",
35
+ "docs": "typedoc --hideGenerator --categorizeByGroup",
36
+ "lint": "eslint . --ext .ts",
37
+ "syntax": "tsc --noEmit",
38
+ "spellcheck": "cspell 'source/**' 'test/**' 'examples/**'",
39
+ "test": "vitest --dir test/ --test-timeout=15000 --passWithNoTests --run --coverage"
40
+ },
41
+ "devDependencies": {
42
+ "@electrum-cash/network": "^4.0.2-development.8063220996",
43
+ "@generalprotocols/cspell-dictionary": "git+https://gitlab.com/GeneralProtocols/cspell-dictionary.git",
44
+ "@generalprotocols/eslint-config": "git+https://gitlab.com/GeneralProtocols/eslint-config.git",
45
+ "@parcel/packager-ts": "^2.12.0",
46
+ "@parcel/transformer-typescript-types": "^2.12.0",
47
+ "@types/debug": "^4.1.6",
48
+ "@typescript-eslint/eslint-plugin": "^6.8.0",
49
+ "@vitest/coverage-v8": "^1.3.1",
50
+ "cspell": "^8.6.0",
51
+ "del-cli": "^5.0.0",
52
+ "eslint": "^8.42.0",
53
+ "eslint-plugin-import": "^2.23.4",
54
+ "events": "^3.3.0",
55
+ "parcel": "^2.12.0",
56
+ "typedoc": "^0.25.12",
57
+ "typedoc-plugin-coverage": "^3.1.0",
58
+ "typescript": "^5.1.3",
59
+ "vitest": "^1.3.1"
60
+ },
61
+ "dependencies": {
62
+ "@electrum-cash/debug-logs": "^1.0.0",
63
+ "@monsterbitar/isomorphic-ws": "^5.3.0",
64
+ "@types/ws": "^8.5.5",
65
+ "async-mutex": "^0.5.0",
66
+ "eventemitter3": "^5.0.1",
67
+ "lossless-json": "^4.0.1",
68
+ "ws": "^8.13.0"
69
+ }
70
+ }