ws-heartbeat-manager 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 VastBlast
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # ws-heartbeat-manager
2
+
3
+ Lightweight heartbeat manager for `ws` server connections.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm i ws-heartbeat-manager
9
+ ```
10
+
11
+ Peer dependency: `ws@^8`.
12
+
13
+ ## What it does
14
+
15
+ - Tracks active clients.
16
+ - Sends periodic `ping` frames.
17
+ - Updates liveness on `pong`.
18
+ - Terminates timed-out or errored sockets.
19
+ - Cleans up listeners and timers automatically.
20
+
21
+ ## Basic usage
22
+
23
+ ```ts
24
+ import { WebSocketServer } from 'ws';
25
+ import { HeartbeatManager } from 'ws-heartbeat-manager';
26
+
27
+ const wss = new WebSocketServer({ port: 8080 });
28
+ const heartbeat = new HeartbeatManager();
29
+
30
+ wss.on('connection', (ws) => {
31
+ heartbeat.addClient(ws);
32
+ });
33
+
34
+ process.on('SIGTERM', () => {
35
+ heartbeat.shutdown();
36
+ wss.close();
37
+ });
38
+ ```
39
+
40
+ ## Custom timing
41
+
42
+ ```ts
43
+ const heartbeat = new HeartbeatManager({
44
+ intervalMs: 15_000, // send ping every 15s
45
+ timeoutMs: 30_000, // terminate if no pong for 30s
46
+ tickMs: 500, // internal sweep cadence
47
+ startJitterMs: 15_000 // stagger start time
48
+ });
49
+ ```
50
+
51
+ ## API
52
+
53
+ - `new HeartbeatManager(options?)`
54
+ - `addClient(ws)`
55
+ - `removeClient(ws)`
56
+ - `shutdown()`
57
+ - `clientCount`
package/dist/index.cjs ADDED
@@ -0,0 +1,137 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let node_perf_hooks = require("node:perf_hooks");
3
+ let node_timers = require("node:timers");
4
+
5
+ //#region src/heartbeatManager.ts
6
+ const WS_OPEN = 1;
7
+ var HeartbeatManager = class {
8
+ clients = /* @__PURE__ */ new Map();
9
+ buckets;
10
+ bucketIndex = 0;
11
+ startDelayTimer;
12
+ tickTimer;
13
+ intervalMs;
14
+ timeoutMs;
15
+ tickMs;
16
+ startJitterMs;
17
+ constructor(opts = {}) {
18
+ this.intervalMs = opts.intervalMs ?? 3e4;
19
+ this.timeoutMs = opts.timeoutMs ?? this.intervalMs * 2;
20
+ if (!Number.isFinite(this.intervalMs) || this.intervalMs <= 0) throw new RangeError("intervalMs must be a finite number > 0");
21
+ if (!Number.isFinite(this.timeoutMs) || this.timeoutMs < this.intervalMs) throw new RangeError("timeoutMs must be a finite number >= intervalMs");
22
+ const desiredTickMs = opts.tickMs ?? Math.min(1e3, this.intervalMs);
23
+ const maxBuckets = opts.maxBuckets ?? 60;
24
+ this.startJitterMs = opts.startJitterMs ?? this.intervalMs;
25
+ if (!Number.isFinite(desiredTickMs) || desiredTickMs <= 0) throw new RangeError("tickMs must be a finite number > 0");
26
+ if (!Number.isInteger(maxBuckets) || maxBuckets < 1) throw new RangeError("maxBuckets must be an integer >= 1");
27
+ if (!Number.isFinite(this.startJitterMs) || this.startJitterMs < 0) throw new RangeError("startJitterMs must be a finite number >= 0");
28
+ const bucketCount = Math.min(maxBuckets, Math.max(1, Math.round(this.intervalMs / Math.max(50, desiredTickMs))));
29
+ this.tickMs = Math.max(10, Math.round(this.intervalMs / bucketCount));
30
+ this.buckets = Array.from({ length: bucketCount }, () => /* @__PURE__ */ new Set());
31
+ }
32
+ get clientCount() {
33
+ return this.clients.size;
34
+ }
35
+ addClient(ws) {
36
+ if (this.clients.has(ws)) return;
37
+ const bucket = Math.floor(Math.random() * this.buckets.length);
38
+ const state = {
39
+ lastPongAt: node_perf_hooks.performance.now(),
40
+ bucket,
41
+ onPong: () => {
42
+ state.lastPongAt = node_perf_hooks.performance.now();
43
+ },
44
+ onClose: () => {
45
+ this.removeClient(ws);
46
+ },
47
+ onError: () => {
48
+ this.removeClient(ws, true);
49
+ }
50
+ };
51
+ this.clients.set(ws, state);
52
+ this.bucketAt(bucket).add(ws);
53
+ ws.on("pong", state.onPong);
54
+ ws.once("close", state.onClose);
55
+ ws.once("error", state.onError);
56
+ this.startTimersIfNeeded();
57
+ }
58
+ removeClient(ws, terminate = false) {
59
+ if (terminate) try {
60
+ ws.terminate();
61
+ } catch {}
62
+ const state = this.clients.get(ws);
63
+ if (!state) return;
64
+ ws.off("pong", state.onPong);
65
+ ws.off("close", state.onClose);
66
+ ws.off("error", state.onError);
67
+ this.bucketAt(state.bucket).delete(ws);
68
+ this.clients.delete(ws);
69
+ if (this.clients.size === 0) this.stopTimers();
70
+ }
71
+ shutdown() {
72
+ this.stopTimers();
73
+ for (const ws of Array.from(this.clients.keys())) this.removeClient(ws, true);
74
+ }
75
+ bucketAt(index) {
76
+ const first = this.buckets[0];
77
+ if (!first) throw new Error("HeartbeatManager misconfigured: no buckets");
78
+ return this.buckets[index] ?? first;
79
+ }
80
+ startTimersIfNeeded() {
81
+ if (this.tickTimer || this.startDelayTimer) return;
82
+ const delay = this.startJitterMs > 0 ? Math.floor(Math.random() * this.startJitterMs) : 0;
83
+ if (delay === 0) {
84
+ this.startTickTimer();
85
+ return;
86
+ }
87
+ this.startDelayTimer = (0, node_timers.setTimeout)(() => {
88
+ this.startDelayTimer = void 0;
89
+ if (this.clients.size > 0) this.startTickTimer();
90
+ }, delay);
91
+ this.startDelayTimer.unref();
92
+ }
93
+ startTickTimer() {
94
+ if (this.tickTimer) return;
95
+ this.tickTimer = (0, node_timers.setInterval)(() => this.tick(), this.tickMs);
96
+ this.tickTimer.unref();
97
+ }
98
+ stopTimers() {
99
+ if (this.startDelayTimer) {
100
+ (0, node_timers.clearTimeout)(this.startDelayTimer);
101
+ this.startDelayTimer = void 0;
102
+ }
103
+ if (this.tickTimer) {
104
+ (0, node_timers.clearInterval)(this.tickTimer);
105
+ this.tickTimer = void 0;
106
+ }
107
+ }
108
+ tick() {
109
+ const now = node_perf_hooks.performance.now();
110
+ const bucket = this.bucketAt(this.bucketIndex);
111
+ for (const ws of bucket) {
112
+ const state = this.clients.get(ws);
113
+ if (!state) {
114
+ bucket.delete(ws);
115
+ continue;
116
+ }
117
+ if (ws.readyState !== WS_OPEN) {
118
+ this.removeClient(ws);
119
+ continue;
120
+ }
121
+ if (now - state.lastPongAt > this.timeoutMs) {
122
+ this.removeClient(ws, true);
123
+ continue;
124
+ }
125
+ try {
126
+ ws.ping();
127
+ } catch {
128
+ this.removeClient(ws, true);
129
+ }
130
+ }
131
+ this.bucketIndex += 1;
132
+ if (this.bucketIndex >= this.buckets.length) this.bucketIndex = 0;
133
+ }
134
+ };
135
+
136
+ //#endregion
137
+ exports.HeartbeatManager = HeartbeatManager;
@@ -0,0 +1,33 @@
1
+ import { WebSocket } from "ws";
2
+
3
+ //#region src/heartbeatManager.d.ts
4
+ type HeartbeatManagerOptions = Readonly<{
5
+ intervalMs?: number;
6
+ timeoutMs?: number;
7
+ tickMs?: number;
8
+ startJitterMs?: number;
9
+ maxBuckets?: number;
10
+ }>;
11
+ declare class HeartbeatManager {
12
+ private readonly clients;
13
+ private readonly buckets;
14
+ private bucketIndex;
15
+ private startDelayTimer?;
16
+ private tickTimer?;
17
+ private readonly intervalMs;
18
+ private readonly timeoutMs;
19
+ private readonly tickMs;
20
+ private readonly startJitterMs;
21
+ constructor(opts?: HeartbeatManagerOptions);
22
+ get clientCount(): number;
23
+ addClient(ws: WebSocket): void;
24
+ removeClient(ws: WebSocket, terminate?: boolean): void;
25
+ shutdown(): void;
26
+ private bucketAt;
27
+ private startTimersIfNeeded;
28
+ private startTickTimer;
29
+ private stopTimers;
30
+ private tick;
31
+ }
32
+ //#endregion
33
+ export { HeartbeatManager, type HeartbeatManagerOptions };
@@ -0,0 +1,33 @@
1
+ import { WebSocket } from "ws";
2
+
3
+ //#region src/heartbeatManager.d.ts
4
+ type HeartbeatManagerOptions = Readonly<{
5
+ intervalMs?: number;
6
+ timeoutMs?: number;
7
+ tickMs?: number;
8
+ startJitterMs?: number;
9
+ maxBuckets?: number;
10
+ }>;
11
+ declare class HeartbeatManager {
12
+ private readonly clients;
13
+ private readonly buckets;
14
+ private bucketIndex;
15
+ private startDelayTimer?;
16
+ private tickTimer?;
17
+ private readonly intervalMs;
18
+ private readonly timeoutMs;
19
+ private readonly tickMs;
20
+ private readonly startJitterMs;
21
+ constructor(opts?: HeartbeatManagerOptions);
22
+ get clientCount(): number;
23
+ addClient(ws: WebSocket): void;
24
+ removeClient(ws: WebSocket, terminate?: boolean): void;
25
+ shutdown(): void;
26
+ private bucketAt;
27
+ private startTimersIfNeeded;
28
+ private startTickTimer;
29
+ private stopTimers;
30
+ private tick;
31
+ }
32
+ //#endregion
33
+ export { HeartbeatManager, type HeartbeatManagerOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,136 @@
1
+ import { performance } from "node:perf_hooks";
2
+ import { clearInterval, clearTimeout, setInterval, setTimeout } from "node:timers";
3
+
4
+ //#region src/heartbeatManager.ts
5
+ const WS_OPEN = 1;
6
+ var HeartbeatManager = class {
7
+ clients = /* @__PURE__ */ new Map();
8
+ buckets;
9
+ bucketIndex = 0;
10
+ startDelayTimer;
11
+ tickTimer;
12
+ intervalMs;
13
+ timeoutMs;
14
+ tickMs;
15
+ startJitterMs;
16
+ constructor(opts = {}) {
17
+ this.intervalMs = opts.intervalMs ?? 3e4;
18
+ this.timeoutMs = opts.timeoutMs ?? this.intervalMs * 2;
19
+ if (!Number.isFinite(this.intervalMs) || this.intervalMs <= 0) throw new RangeError("intervalMs must be a finite number > 0");
20
+ if (!Number.isFinite(this.timeoutMs) || this.timeoutMs < this.intervalMs) throw new RangeError("timeoutMs must be a finite number >= intervalMs");
21
+ const desiredTickMs = opts.tickMs ?? Math.min(1e3, this.intervalMs);
22
+ const maxBuckets = opts.maxBuckets ?? 60;
23
+ this.startJitterMs = opts.startJitterMs ?? this.intervalMs;
24
+ if (!Number.isFinite(desiredTickMs) || desiredTickMs <= 0) throw new RangeError("tickMs must be a finite number > 0");
25
+ if (!Number.isInteger(maxBuckets) || maxBuckets < 1) throw new RangeError("maxBuckets must be an integer >= 1");
26
+ if (!Number.isFinite(this.startJitterMs) || this.startJitterMs < 0) throw new RangeError("startJitterMs must be a finite number >= 0");
27
+ const bucketCount = Math.min(maxBuckets, Math.max(1, Math.round(this.intervalMs / Math.max(50, desiredTickMs))));
28
+ this.tickMs = Math.max(10, Math.round(this.intervalMs / bucketCount));
29
+ this.buckets = Array.from({ length: bucketCount }, () => /* @__PURE__ */ new Set());
30
+ }
31
+ get clientCount() {
32
+ return this.clients.size;
33
+ }
34
+ addClient(ws) {
35
+ if (this.clients.has(ws)) return;
36
+ const bucket = Math.floor(Math.random() * this.buckets.length);
37
+ const state = {
38
+ lastPongAt: performance.now(),
39
+ bucket,
40
+ onPong: () => {
41
+ state.lastPongAt = performance.now();
42
+ },
43
+ onClose: () => {
44
+ this.removeClient(ws);
45
+ },
46
+ onError: () => {
47
+ this.removeClient(ws, true);
48
+ }
49
+ };
50
+ this.clients.set(ws, state);
51
+ this.bucketAt(bucket).add(ws);
52
+ ws.on("pong", state.onPong);
53
+ ws.once("close", state.onClose);
54
+ ws.once("error", state.onError);
55
+ this.startTimersIfNeeded();
56
+ }
57
+ removeClient(ws, terminate = false) {
58
+ if (terminate) try {
59
+ ws.terminate();
60
+ } catch {}
61
+ const state = this.clients.get(ws);
62
+ if (!state) return;
63
+ ws.off("pong", state.onPong);
64
+ ws.off("close", state.onClose);
65
+ ws.off("error", state.onError);
66
+ this.bucketAt(state.bucket).delete(ws);
67
+ this.clients.delete(ws);
68
+ if (this.clients.size === 0) this.stopTimers();
69
+ }
70
+ shutdown() {
71
+ this.stopTimers();
72
+ for (const ws of Array.from(this.clients.keys())) this.removeClient(ws, true);
73
+ }
74
+ bucketAt(index) {
75
+ const first = this.buckets[0];
76
+ if (!first) throw new Error("HeartbeatManager misconfigured: no buckets");
77
+ return this.buckets[index] ?? first;
78
+ }
79
+ startTimersIfNeeded() {
80
+ if (this.tickTimer || this.startDelayTimer) return;
81
+ const delay = this.startJitterMs > 0 ? Math.floor(Math.random() * this.startJitterMs) : 0;
82
+ if (delay === 0) {
83
+ this.startTickTimer();
84
+ return;
85
+ }
86
+ this.startDelayTimer = setTimeout(() => {
87
+ this.startDelayTimer = void 0;
88
+ if (this.clients.size > 0) this.startTickTimer();
89
+ }, delay);
90
+ this.startDelayTimer.unref();
91
+ }
92
+ startTickTimer() {
93
+ if (this.tickTimer) return;
94
+ this.tickTimer = setInterval(() => this.tick(), this.tickMs);
95
+ this.tickTimer.unref();
96
+ }
97
+ stopTimers() {
98
+ if (this.startDelayTimer) {
99
+ clearTimeout(this.startDelayTimer);
100
+ this.startDelayTimer = void 0;
101
+ }
102
+ if (this.tickTimer) {
103
+ clearInterval(this.tickTimer);
104
+ this.tickTimer = void 0;
105
+ }
106
+ }
107
+ tick() {
108
+ const now = performance.now();
109
+ const bucket = this.bucketAt(this.bucketIndex);
110
+ for (const ws of bucket) {
111
+ const state = this.clients.get(ws);
112
+ if (!state) {
113
+ bucket.delete(ws);
114
+ continue;
115
+ }
116
+ if (ws.readyState !== WS_OPEN) {
117
+ this.removeClient(ws);
118
+ continue;
119
+ }
120
+ if (now - state.lastPongAt > this.timeoutMs) {
121
+ this.removeClient(ws, true);
122
+ continue;
123
+ }
124
+ try {
125
+ ws.ping();
126
+ } catch {
127
+ this.removeClient(ws, true);
128
+ }
129
+ }
130
+ this.bucketIndex += 1;
131
+ if (this.bucketIndex >= this.buckets.length) this.bucketIndex = 0;
132
+ }
133
+ };
134
+
135
+ //#endregion
136
+ export { HeartbeatManager };
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "ws-heartbeat-manager",
3
+ "version": "0.1.0",
4
+ "description": "Lightweight WebSocket heartbeat manager for ws servers.",
5
+ "scripts": {
6
+ "build": "tsdown",
7
+ "build:watch": "tsdown --watch",
8
+ "lint": "oxlint --type-aware",
9
+ "lint:fix": "oxlint --fix --type-aware",
10
+ "check:types": "tsgo --noEmit",
11
+ "check": "npm run lint && npm run check:types",
12
+ "test": "vitest",
13
+ "prepublishOnly": "npm test -- --run && npm run check && npm run build"
14
+ },
15
+ "keywords": [
16
+ "websocket",
17
+ "ws",
18
+ "heartbeat",
19
+ "ping",
20
+ "pong"
21
+ ],
22
+ "author": "VastBlast",
23
+ "license": "MIT",
24
+ "files": [
25
+ "dist/"
26
+ ],
27
+ "sideEffects": false,
28
+ "peerDependencies": {
29
+ "ws": "^8.0.0"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^24.10.3",
33
+ "@types/ws": "^8.18.1",
34
+ "@typescript/native-preview": "^7.0.0-dev.20251223.1",
35
+ "oxlint": "^1.35.0",
36
+ "oxlint-tsgolint": "^0.14.2",
37
+ "tsdown": "^0.20.3",
38
+ "typescript": "^5.8.3",
39
+ "vitest": "^4.0.16"
40
+ },
41
+ "type": "module",
42
+ "main": "./dist/index.cjs",
43
+ "module": "./dist/index.mjs",
44
+ "types": "./dist/index.d.cts",
45
+ "exports": {
46
+ ".": {
47
+ "import": "./dist/index.mjs",
48
+ "require": "./dist/index.cjs"
49
+ },
50
+ "./package.json": "./package.json"
51
+ }
52
+ }