@zero-server/sdk 0.9.0 → 0.9.2

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.
Files changed (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -437
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +460 -460
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +136 -136
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +254 -254
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/cluster.d.ts +75 -75
  113. package/types/env.d.ts +80 -80
  114. package/types/errors.d.ts +316 -316
  115. package/types/fetch.d.ts +43 -43
  116. package/types/grpc.d.ts +432 -432
  117. package/types/index.d.ts +384 -384
  118. package/types/lifecycle.d.ts +60 -60
  119. package/types/middleware.d.ts +320 -320
  120. package/types/observe.d.ts +304 -304
  121. package/types/orm.d.ts +1887 -1887
  122. package/types/request.d.ts +109 -109
  123. package/types/response.d.ts +157 -157
  124. package/types/router.d.ts +78 -78
  125. package/types/sse.d.ts +78 -78
  126. package/types/websocket.d.ts +126 -126
@@ -1,451 +1,451 @@
1
- /**
2
- * @module ws/connection
3
- * @description Full-featured WebSocket connection wrapper over a raw TCP socket.
4
- * Implements RFC 6455 framing for text, binary, ping, pong, and close.
5
- */
6
-
7
- const log = require('../debug')('zero:ws');
8
-
9
- /** Auto-incrementing connection ID counter. */
10
- let _wsIdCounter = 0;
11
-
12
- /**
13
- * WebSocket ready-state constants (mirrors the browser WebSocket API).
14
- * @enum {number}
15
- */
16
- const WS_READY_STATE = {
17
- CONNECTING: 0,
18
- OPEN: 1,
19
- CLOSING: 2,
20
- CLOSED: 3,
21
- };
22
-
23
- /**
24
- * Full-featured WebSocket connection wrapper over a raw TCP socket.
25
- * Implements RFC 6455 framing for text, binary, ping, pong, and close.
26
- *
27
- * @class
28
- *
29
- * @example
30
- * app.ws('/chat', (ws, req) => {
31
- * console.log('connected:', ws.id, 'from', ws.ip);
32
- *
33
- * ws.on('message', data => {
34
- * console.log('received:', data);
35
- * ws.sendJSON({ echo: data });
36
- * });
37
- *
38
- * ws.on('close', (code, reason) => {
39
- * console.log('disconnected:', code, reason);
40
- * });
41
- * });
42
- */
43
- class WebSocketConnection
44
- {
45
- /**
46
- * @constructor
47
- * @param {import('net').Socket} socket - The upgraded TCP socket.
48
- * @param {object} [meta] - Connection metadata from the upgrade handshake.
49
- * @param {number} [meta.maxPayload=1048576] - Maximum incoming frame size in bytes.
50
- * @param {number} [meta.pingInterval=30000] - Auto-ping interval in ms (0 to disable).
51
- * @param {string} [meta.protocol] - Negotiated WebSocket sub-protocol.
52
- * @param {string} [meta.extensions] - Negotiated WebSocket extensions.
53
- * @param {object} [meta.headers] - HTTP headers from the upgrade request.
54
- * @param {string} [meta.ip] - Remote IP address of the client.
55
- * @param {object} [meta.query] - Parsed query-string parameters from the upgrade URL.
56
- * @param {string} [meta.url] - The request URL path.
57
- * @param {boolean} [meta.secure=false] - Whether the connection is over TLS.
58
- */
59
- constructor(socket, meta = {})
60
- {
61
- this._socket = socket;
62
- this._buffer = Buffer.alloc(0);
63
-
64
- /** Unique connection identifier. */
65
- this.id = 'ws_' + (++_wsIdCounter) + '_' + Date.now().toString(36);
66
- log.info('connection opened id=%s ip=%s', this.id, socket.remoteAddress);
67
-
68
- /** Current ready state. */
69
- this.readyState = WS_READY_STATE.OPEN;
70
-
71
- /** Negotiated sub-protocol. */
72
- this.protocol = meta.protocol || '';
73
-
74
- /** Requested extensions. */
75
- this.extensions = meta.extensions || '';
76
-
77
- /** Request headers from the upgrade. */
78
- this.headers = meta.headers || {};
79
-
80
- /** Remote IP address. */
81
- this.ip = meta.ip || (socket.remoteAddress || null);
82
-
83
- /** Parsed query params from the upgrade URL. */
84
- this.query = meta.query || {};
85
-
86
- /** Full upgrade URL. */
87
- this.url = meta.url || '';
88
-
89
- /** `true` when the underlying connection is over TLS (WSS). */
90
- this.secure = !!meta.secure;
91
-
92
- /** Maximum incoming frame payload in bytes (default 1 MB). */
93
- this.maxPayload = meta.maxPayload || 1048576;
94
-
95
- /** Timestamp (ms) when the connection was established. */
96
- this.connectedAt = Date.now();
97
-
98
- /** Arbitrary user-data store. Attach anything you need. */
99
- this.data = {};
100
-
101
- /** @type {Object<string, Function[]>} */
102
- this._listeners = {};
103
-
104
- /** @private */
105
- this._pingTimer = null;
106
-
107
- // Set up auto-ping keep-alive
108
- const pingInterval = meta.pingInterval !== undefined ? meta.pingInterval : 30000;
109
- if (pingInterval > 0)
110
- {
111
- this._pingTimer = setInterval(() => this.ping(), pingInterval);
112
- if (this._pingTimer.unref) this._pingTimer.unref();
113
- }
114
-
115
- socket.on('data', (chunk) => this._onData(chunk));
116
- socket.on('close', () =>
117
- {
118
- if (this.readyState !== WS_READY_STATE.CLOSED)
119
- {
120
- this.readyState = WS_READY_STATE.CLOSED;
121
- this._clearPing();
122
- log.info('connection closed id=%s', this.id);
123
- this._emit('close', 1006, '');
124
- }
125
- });
126
- socket.on('error', (err) => { log.error('socket error id=%s: %s', this.id, err.message); this._emit('error', err); });
127
- socket.on('drain', () => this._emit('drain'));
128
- }
129
-
130
- // -- Event Emitter ---------------------------------
131
-
132
- /**
133
- * Register an event listener.
134
- * @param {'message'|'close'|'error'|'pong'|'ping'|'drain'} event - Event name.
135
- * @param {Function} fn - Callback function.
136
- * @returns {WebSocketConnection} this
137
- */
138
- on(event, fn)
139
- {
140
- if (!this._listeners[event]) this._listeners[event] = [];
141
- this._listeners[event].push(fn);
142
- return this;
143
- }
144
-
145
- /**
146
- * Register a one-time event listener.
147
- * @param {'message'|'close'|'error'|'pong'|'ping'|'drain'} event - Event name.
148
- * @param {Function} fn - Callback function.
149
- * @returns {WebSocketConnection} this
150
- */
151
- once(event, fn)
152
- {
153
- const wrapper = (...args) => { this.off(event, wrapper); fn(...args); };
154
- wrapper._original = fn;
155
- return this.on(event, wrapper);
156
- }
157
-
158
- /**
159
- * Remove a specific event listener.
160
- * @param {string} event - Event name.
161
- * @param {Function} fn - Callback function.
162
- * @returns {WebSocketConnection} this
163
- */
164
- off(event, fn)
165
- {
166
- const list = this._listeners[event];
167
- if (!list) return this;
168
- this._listeners[event] = list.filter(f => f !== fn && f._original !== fn);
169
- return this;
170
- }
171
-
172
- /**
173
- * Remove all listeners for an event, or all events if none specified.
174
- * @param {string} [event] - Event name.
175
- * @returns {WebSocketConnection} this
176
- */
177
- removeAllListeners(event)
178
- {
179
- if (event) delete this._listeners[event];
180
- else this._listeners = {};
181
- return this;
182
- }
183
-
184
- /**
185
- * Count listeners for a given event.
186
- * @param {string} event - Event name.
187
- * @returns {number} Number of listeners registered for the event.
188
- */
189
- listenerCount(event)
190
- {
191
- return (this._listeners[event] || []).length;
192
- }
193
-
194
- /** @private */
195
- _emit(event, ...args)
196
- {
197
- const fns = this._listeners[event];
198
- if (fns) fns.slice().forEach(fn => { try { fn(...args); } catch (e) { } });
199
- }
200
-
201
- // -- Sending ---------------------------------------
202
-
203
- /**
204
- * Send a text or binary message.
205
- * @param {string|Buffer} data - Payload.
206
- * @param {object} [opts] - Configuration options.
207
- * @param {boolean} [opts.binary] - Force binary frame (opcode 0x02).
208
- * @param {Function} [opts.callback] - Called after the data is flushed.
209
- * @returns {boolean} `false` if the socket buffer is full (backpressure).
210
- */
211
- send(data, opts)
212
- {
213
- if (this.readyState !== WS_READY_STATE.OPEN) return false;
214
- const cb = opts && opts.callback;
215
- const forceBinary = opts && opts.binary;
216
- const isBinary = forceBinary || Buffer.isBuffer(data);
217
- const opcode = isBinary ? 0x02 : 0x01;
218
- const payload = isBinary ? (Buffer.isBuffer(data) ? data : Buffer.from(data)) : Buffer.from(String(data), 'utf8');
219
- const frame = this._buildFrame(opcode, payload);
220
- try { return this._socket.write(frame, cb); } catch (e) { return false; }
221
- }
222
-
223
- /**
224
- * Send a JSON-serialised message (sets text frame).
225
- * @param {*} obj - Value to serialise.
226
- * @param {Function} [cb] - Called after the data is flushed.
227
- * @returns {boolean} `false` if the connection is not open or serialisation fails.
228
- */
229
- sendJSON(obj, cb)
230
- {
231
- let json;
232
- try { json = JSON.stringify(obj); }
233
- catch (e)
234
- {
235
- this._emit('error', new Error('Failed to serialize JSON: ' + e.message));
236
- return false;
237
- }
238
- return this.send(json, { callback: cb });
239
- }
240
-
241
- /**
242
- * Send a ping frame.
243
- * @param {string|Buffer} [payload] - Optional payload (max 125 bytes).
244
- * @param {Function} [cb] - Called after the frame is flushed.
245
- * @returns {boolean} `false` if the connection is not open.
246
- */
247
- ping(payload, cb)
248
- {
249
- if (this.readyState !== WS_READY_STATE.OPEN) return false;
250
- const data = payload ? (Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload))) : Buffer.alloc(0);
251
- try { return this._socket.write(this._buildFrame(0x09, data), cb); } catch (e) { return false; }
252
- }
253
-
254
- /**
255
- * Send a pong frame.
256
- * @param {string|Buffer} [payload] - Optional payload.
257
- * @param {Function} [cb] - Called after the frame is flushed.
258
- * @returns {boolean} `false` if the connection is not open.
259
- */
260
- pong(payload, cb)
261
- {
262
- if (this.readyState !== WS_READY_STATE.OPEN) return false;
263
- const data = payload ? (Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload))) : Buffer.alloc(0);
264
- try { return this._socket.write(this._buildFrame(0x0A, data), cb); } catch (e) { return false; }
265
- }
266
-
267
- /**
268
- * Close the WebSocket connection.
269
- * @param {number} [code=1000] - Close status code.
270
- * @param {string} [reason] - Close reason string.
271
- */
272
- close(code, reason)
273
- {
274
- if (this.readyState === WS_READY_STATE.CLOSED || this.readyState === WS_READY_STATE.CLOSING) return;
275
- this.readyState = WS_READY_STATE.CLOSING;
276
- this._clearPing();
277
- const statusCode = code || 1000;
278
- const reasonBuf = reason ? Buffer.from(String(reason), 'utf8') : Buffer.alloc(0);
279
- const payload = Buffer.alloc(2 + reasonBuf.length);
280
- payload.writeUInt16BE(statusCode, 0);
281
- reasonBuf.copy(payload, 2);
282
- try
283
- {
284
- this._socket.write(this._buildFrame(0x08, payload));
285
- this._socket.end();
286
- }
287
- catch (e) { }
288
- }
289
-
290
- /**
291
- * Forcefully destroy the underlying socket without a close frame.
292
- */
293
- terminate()
294
- {
295
- this.readyState = WS_READY_STATE.CLOSED;
296
- this._clearPing();
297
- try { this._socket.destroy(); } catch (e) { }
298
- }
299
-
300
- // -- Computed Properties ---------------------------
301
-
302
- /**
303
- * Bytes waiting in the send buffer.
304
- * @type {number}
305
- */
306
- get bufferedAmount()
307
- {
308
- return this._socket ? (this._socket.writableLength || 0) : 0;
309
- }
310
-
311
- /**
312
- * How long this connection has been alive (ms).
313
- * @type {number}
314
- */
315
- get uptime()
316
- {
317
- return Date.now() - this.connectedAt;
318
- }
319
-
320
- // -- Internals -------------------------------------
321
-
322
- /** @private */
323
- _clearPing()
324
- {
325
- if (this._pingTimer) { clearInterval(this._pingTimer); this._pingTimer = null; }
326
- }
327
-
328
- /** @private Build a WebSocket frame. */
329
- _buildFrame(opcode, payload)
330
- {
331
- const len = payload.length;
332
- let header;
333
- if (len < 126)
334
- {
335
- header = Buffer.alloc(2);
336
- header[0] = 0x80 | opcode; // FIN + opcode
337
- header[1] = len;
338
- }
339
- else if (len < 65536)
340
- {
341
- header = Buffer.alloc(4);
342
- header[0] = 0x80 | opcode;
343
- header[1] = 126;
344
- header.writeUInt16BE(len, 2);
345
- }
346
- else
347
- {
348
- header = Buffer.alloc(10);
349
- header[0] = 0x80 | opcode;
350
- header[1] = 127;
351
- header.writeUInt32BE(0, 2);
352
- header.writeUInt32BE(len, 6);
353
- }
354
- return Buffer.concat([header, payload]);
355
- }
356
-
357
- /** @private Parse incoming WebSocket frames. */
358
- _onData(chunk)
359
- {
360
- this._buffer = Buffer.concat([this._buffer, chunk]);
361
-
362
- while (this._buffer.length >= 2)
363
- {
364
- const firstByte = this._buffer[0];
365
- const secondByte = this._buffer[1];
366
- const opcode = firstByte & 0x0F;
367
- const masked = (secondByte & 0x80) !== 0;
368
- let payloadLen = secondByte & 0x7F;
369
- let offset = 2;
370
-
371
- if (payloadLen === 126)
372
- {
373
- if (this._buffer.length < 4) return;
374
- payloadLen = this._buffer.readUInt16BE(2);
375
- offset = 4;
376
- }
377
- else if (payloadLen === 127)
378
- {
379
- if (this._buffer.length < 10) return;
380
- // RFC 6455: 64-bit unsigned integer; read upper and lower 32-bit halves
381
- const upper = this._buffer.readUInt32BE(2);
382
- const lower = this._buffer.readUInt32BE(6);
383
- // Reject frames where upper 32 bits are set (>4GB not supported)
384
- if (upper > 0) { this.close(1009, 'Message too big'); this._buffer = Buffer.alloc(0); return; }
385
- payloadLen = lower;
386
- offset = 10;
387
- }
388
-
389
- // Enforce max payload
390
- if (payloadLen > this.maxPayload)
391
- {
392
- this.close(1009, 'Message too big');
393
- this._buffer = Buffer.alloc(0);
394
- return;
395
- }
396
-
397
- const maskSize = masked ? 4 : 0;
398
- const totalLen = offset + maskSize + payloadLen;
399
- if (this._buffer.length < totalLen) return;
400
-
401
- let payload = this._buffer.slice(offset + maskSize, totalLen);
402
- if (masked)
403
- {
404
- const mask = this._buffer.slice(offset, offset + 4);
405
- payload = Buffer.alloc(payloadLen);
406
- for (let i = 0; i < payloadLen; i++)
407
- {
408
- payload[i] = this._buffer[offset + maskSize + i] ^ mask[i & 3];
409
- }
410
- }
411
-
412
- this._buffer = this._buffer.slice(totalLen);
413
-
414
- switch (opcode)
415
- {
416
- case 0x01: // text
417
- this._emit('message', payload.toString('utf8'));
418
- break;
419
- case 0x02: // binary
420
- this._emit('message', payload);
421
- break;
422
- case 0x08: // close
423
- {
424
- const closeCode = payload.length >= 2 ? payload.readUInt16BE(0) : 1005;
425
- const closeReason = payload.length > 2 ? payload.slice(2).toString('utf8') : '';
426
- this.readyState = WS_READY_STATE.CLOSED;
427
- this._clearPing();
428
- try { this._socket.write(this._buildFrame(0x08, payload)); } catch (e) { }
429
- this._socket.end();
430
- this._emit('close', closeCode, closeReason);
431
- return;
432
- }
433
- case 0x09: // ping
434
- this._emit('ping', payload);
435
- try { this._socket.write(this._buildFrame(0x0A, payload)); } catch (e) { }
436
- break;
437
- case 0x0A: // pong
438
- this._emit('pong', payload);
439
- break;
440
- }
441
- }
442
- }
443
- }
444
-
445
- /** Ready-state constants exposed on the class for convenience. */
446
- WebSocketConnection.CONNECTING = WS_READY_STATE.CONNECTING;
447
- WebSocketConnection.OPEN = WS_READY_STATE.OPEN;
448
- WebSocketConnection.CLOSING = WS_READY_STATE.CLOSING;
449
- WebSocketConnection.CLOSED = WS_READY_STATE.CLOSED;
450
-
451
- module.exports = WebSocketConnection;
1
+ /**
2
+ * @module ws/connection
3
+ * @description Full-featured WebSocket connection wrapper over a raw TCP socket.
4
+ * Implements RFC 6455 framing for text, binary, ping, pong, and close.
5
+ */
6
+
7
+ const log = require('../debug')('zero:ws');
8
+
9
+ /** Auto-incrementing connection ID counter. */
10
+ let _wsIdCounter = 0;
11
+
12
+ /**
13
+ * WebSocket ready-state constants (mirrors the browser WebSocket API).
14
+ * @enum {number}
15
+ */
16
+ const WS_READY_STATE = {
17
+ CONNECTING: 0,
18
+ OPEN: 1,
19
+ CLOSING: 2,
20
+ CLOSED: 3,
21
+ };
22
+
23
+ /**
24
+ * Full-featured WebSocket connection wrapper over a raw TCP socket.
25
+ * Implements RFC 6455 framing for text, binary, ping, pong, and close.
26
+ *
27
+ * @class
28
+ *
29
+ * @example
30
+ * app.ws('/chat', (ws, req) => {
31
+ * console.log('connected:', ws.id, 'from', ws.ip);
32
+ *
33
+ * ws.on('message', data => {
34
+ * console.log('received:', data);
35
+ * ws.sendJSON({ echo: data });
36
+ * });
37
+ *
38
+ * ws.on('close', (code, reason) => {
39
+ * console.log('disconnected:', code, reason);
40
+ * });
41
+ * });
42
+ */
43
+ class WebSocketConnection
44
+ {
45
+ /**
46
+ * @constructor
47
+ * @param {import('net').Socket} socket - The upgraded TCP socket.
48
+ * @param {object} [meta] - Connection metadata from the upgrade handshake.
49
+ * @param {number} [meta.maxPayload=1048576] - Maximum incoming frame size in bytes.
50
+ * @param {number} [meta.pingInterval=30000] - Auto-ping interval in ms (0 to disable).
51
+ * @param {string} [meta.protocol] - Negotiated WebSocket sub-protocol.
52
+ * @param {string} [meta.extensions] - Negotiated WebSocket extensions.
53
+ * @param {object} [meta.headers] - HTTP headers from the upgrade request.
54
+ * @param {string} [meta.ip] - Remote IP address of the client.
55
+ * @param {object} [meta.query] - Parsed query-string parameters from the upgrade URL.
56
+ * @param {string} [meta.url] - The request URL path.
57
+ * @param {boolean} [meta.secure=false] - Whether the connection is over TLS.
58
+ */
59
+ constructor(socket, meta = {})
60
+ {
61
+ this._socket = socket;
62
+ this._buffer = Buffer.alloc(0);
63
+
64
+ /** Unique connection identifier. */
65
+ this.id = 'ws_' + (++_wsIdCounter) + '_' + Date.now().toString(36);
66
+ log.info('connection opened id=%s ip=%s', this.id, socket.remoteAddress);
67
+
68
+ /** Current ready state. */
69
+ this.readyState = WS_READY_STATE.OPEN;
70
+
71
+ /** Negotiated sub-protocol. */
72
+ this.protocol = meta.protocol || '';
73
+
74
+ /** Requested extensions. */
75
+ this.extensions = meta.extensions || '';
76
+
77
+ /** Request headers from the upgrade. */
78
+ this.headers = meta.headers || {};
79
+
80
+ /** Remote IP address. */
81
+ this.ip = meta.ip || (socket.remoteAddress || null);
82
+
83
+ /** Parsed query params from the upgrade URL. */
84
+ this.query = meta.query || {};
85
+
86
+ /** Full upgrade URL. */
87
+ this.url = meta.url || '';
88
+
89
+ /** `true` when the underlying connection is over TLS (WSS). */
90
+ this.secure = !!meta.secure;
91
+
92
+ /** Maximum incoming frame payload in bytes (default 1 MB). */
93
+ this.maxPayload = meta.maxPayload || 1048576;
94
+
95
+ /** Timestamp (ms) when the connection was established. */
96
+ this.connectedAt = Date.now();
97
+
98
+ /** Arbitrary user-data store. Attach anything you need. */
99
+ this.data = {};
100
+
101
+ /** @type {Object<string, Function[]>} */
102
+ this._listeners = {};
103
+
104
+ /** @private */
105
+ this._pingTimer = null;
106
+
107
+ // Set up auto-ping keep-alive
108
+ const pingInterval = meta.pingInterval !== undefined ? meta.pingInterval : 30000;
109
+ if (pingInterval > 0)
110
+ {
111
+ this._pingTimer = setInterval(() => this.ping(), pingInterval);
112
+ if (this._pingTimer.unref) this._pingTimer.unref();
113
+ }
114
+
115
+ socket.on('data', (chunk) => this._onData(chunk));
116
+ socket.on('close', () =>
117
+ {
118
+ if (this.readyState !== WS_READY_STATE.CLOSED)
119
+ {
120
+ this.readyState = WS_READY_STATE.CLOSED;
121
+ this._clearPing();
122
+ log.info('connection closed id=%s', this.id);
123
+ this._emit('close', 1006, '');
124
+ }
125
+ });
126
+ socket.on('error', (err) => { log.error('socket error id=%s: %s', this.id, err.message); this._emit('error', err); });
127
+ socket.on('drain', () => this._emit('drain'));
128
+ }
129
+
130
+ // -- Event Emitter ---------------------------------
131
+
132
+ /**
133
+ * Register an event listener.
134
+ * @param {'message'|'close'|'error'|'pong'|'ping'|'drain'} event - Event name.
135
+ * @param {Function} fn - Callback function.
136
+ * @returns {WebSocketConnection} this
137
+ */
138
+ on(event, fn)
139
+ {
140
+ if (!this._listeners[event]) this._listeners[event] = [];
141
+ this._listeners[event].push(fn);
142
+ return this;
143
+ }
144
+
145
+ /**
146
+ * Register a one-time event listener.
147
+ * @param {'message'|'close'|'error'|'pong'|'ping'|'drain'} event - Event name.
148
+ * @param {Function} fn - Callback function.
149
+ * @returns {WebSocketConnection} this
150
+ */
151
+ once(event, fn)
152
+ {
153
+ const wrapper = (...args) => { this.off(event, wrapper); fn(...args); };
154
+ wrapper._original = fn;
155
+ return this.on(event, wrapper);
156
+ }
157
+
158
+ /**
159
+ * Remove a specific event listener.
160
+ * @param {string} event - Event name.
161
+ * @param {Function} fn - Callback function.
162
+ * @returns {WebSocketConnection} this
163
+ */
164
+ off(event, fn)
165
+ {
166
+ const list = this._listeners[event];
167
+ if (!list) return this;
168
+ this._listeners[event] = list.filter(f => f !== fn && f._original !== fn);
169
+ return this;
170
+ }
171
+
172
+ /**
173
+ * Remove all listeners for an event, or all events if none specified.
174
+ * @param {string} [event] - Event name.
175
+ * @returns {WebSocketConnection} this
176
+ */
177
+ removeAllListeners(event)
178
+ {
179
+ if (event) delete this._listeners[event];
180
+ else this._listeners = {};
181
+ return this;
182
+ }
183
+
184
+ /**
185
+ * Count listeners for a given event.
186
+ * @param {string} event - Event name.
187
+ * @returns {number} Number of listeners registered for the event.
188
+ */
189
+ listenerCount(event)
190
+ {
191
+ return (this._listeners[event] || []).length;
192
+ }
193
+
194
+ /** @private */
195
+ _emit(event, ...args)
196
+ {
197
+ const fns = this._listeners[event];
198
+ if (fns) fns.slice().forEach(fn => { try { fn(...args); } catch (e) { } });
199
+ }
200
+
201
+ // -- Sending ---------------------------------------
202
+
203
+ /**
204
+ * Send a text or binary message.
205
+ * @param {string|Buffer} data - Payload.
206
+ * @param {object} [opts] - Configuration options.
207
+ * @param {boolean} [opts.binary] - Force binary frame (opcode 0x02).
208
+ * @param {Function} [opts.callback] - Called after the data is flushed.
209
+ * @returns {boolean} `false` if the socket buffer is full (backpressure).
210
+ */
211
+ send(data, opts)
212
+ {
213
+ if (this.readyState !== WS_READY_STATE.OPEN) return false;
214
+ const cb = opts && opts.callback;
215
+ const forceBinary = opts && opts.binary;
216
+ const isBinary = forceBinary || Buffer.isBuffer(data);
217
+ const opcode = isBinary ? 0x02 : 0x01;
218
+ const payload = isBinary ? (Buffer.isBuffer(data) ? data : Buffer.from(data)) : Buffer.from(String(data), 'utf8');
219
+ const frame = this._buildFrame(opcode, payload);
220
+ try { return this._socket.write(frame, cb); } catch (e) { return false; }
221
+ }
222
+
223
+ /**
224
+ * Send a JSON-serialised message (sets text frame).
225
+ * @param {*} obj - Value to serialise.
226
+ * @param {Function} [cb] - Called after the data is flushed.
227
+ * @returns {boolean} `false` if the connection is not open or serialisation fails.
228
+ */
229
+ sendJSON(obj, cb)
230
+ {
231
+ let json;
232
+ try { json = JSON.stringify(obj); }
233
+ catch (e)
234
+ {
235
+ this._emit('error', new Error('Failed to serialize JSON: ' + e.message));
236
+ return false;
237
+ }
238
+ return this.send(json, { callback: cb });
239
+ }
240
+
241
+ /**
242
+ * Send a ping frame.
243
+ * @param {string|Buffer} [payload] - Optional payload (max 125 bytes).
244
+ * @param {Function} [cb] - Called after the frame is flushed.
245
+ * @returns {boolean} `false` if the connection is not open.
246
+ */
247
+ ping(payload, cb)
248
+ {
249
+ if (this.readyState !== WS_READY_STATE.OPEN) return false;
250
+ const data = payload ? (Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload))) : Buffer.alloc(0);
251
+ try { return this._socket.write(this._buildFrame(0x09, data), cb); } catch (e) { return false; }
252
+ }
253
+
254
+ /**
255
+ * Send a pong frame.
256
+ * @param {string|Buffer} [payload] - Optional payload.
257
+ * @param {Function} [cb] - Called after the frame is flushed.
258
+ * @returns {boolean} `false` if the connection is not open.
259
+ */
260
+ pong(payload, cb)
261
+ {
262
+ if (this.readyState !== WS_READY_STATE.OPEN) return false;
263
+ const data = payload ? (Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload))) : Buffer.alloc(0);
264
+ try { return this._socket.write(this._buildFrame(0x0A, data), cb); } catch (e) { return false; }
265
+ }
266
+
267
+ /**
268
+ * Close the WebSocket connection.
269
+ * @param {number} [code=1000] - Close status code.
270
+ * @param {string} [reason] - Close reason string.
271
+ */
272
+ close(code, reason)
273
+ {
274
+ if (this.readyState === WS_READY_STATE.CLOSED || this.readyState === WS_READY_STATE.CLOSING) return;
275
+ this.readyState = WS_READY_STATE.CLOSING;
276
+ this._clearPing();
277
+ const statusCode = code || 1000;
278
+ const reasonBuf = reason ? Buffer.from(String(reason), 'utf8') : Buffer.alloc(0);
279
+ const payload = Buffer.alloc(2 + reasonBuf.length);
280
+ payload.writeUInt16BE(statusCode, 0);
281
+ reasonBuf.copy(payload, 2);
282
+ try
283
+ {
284
+ this._socket.write(this._buildFrame(0x08, payload));
285
+ this._socket.end();
286
+ }
287
+ catch (e) { }
288
+ }
289
+
290
+ /**
291
+ * Forcefully destroy the underlying socket without a close frame.
292
+ */
293
+ terminate()
294
+ {
295
+ this.readyState = WS_READY_STATE.CLOSED;
296
+ this._clearPing();
297
+ try { this._socket.destroy(); } catch (e) { }
298
+ }
299
+
300
+ // -- Computed Properties ---------------------------
301
+
302
+ /**
303
+ * Bytes waiting in the send buffer.
304
+ * @type {number}
305
+ */
306
+ get bufferedAmount()
307
+ {
308
+ return this._socket ? (this._socket.writableLength || 0) : 0;
309
+ }
310
+
311
+ /**
312
+ * How long this connection has been alive (ms).
313
+ * @type {number}
314
+ */
315
+ get uptime()
316
+ {
317
+ return Date.now() - this.connectedAt;
318
+ }
319
+
320
+ // -- Internals -------------------------------------
321
+
322
+ /** @private */
323
+ _clearPing()
324
+ {
325
+ if (this._pingTimer) { clearInterval(this._pingTimer); this._pingTimer = null; }
326
+ }
327
+
328
+ /** @private Build a WebSocket frame. */
329
+ _buildFrame(opcode, payload)
330
+ {
331
+ const len = payload.length;
332
+ let header;
333
+ if (len < 126)
334
+ {
335
+ header = Buffer.alloc(2);
336
+ header[0] = 0x80 | opcode; // FIN + opcode
337
+ header[1] = len;
338
+ }
339
+ else if (len < 65536)
340
+ {
341
+ header = Buffer.alloc(4);
342
+ header[0] = 0x80 | opcode;
343
+ header[1] = 126;
344
+ header.writeUInt16BE(len, 2);
345
+ }
346
+ else
347
+ {
348
+ header = Buffer.alloc(10);
349
+ header[0] = 0x80 | opcode;
350
+ header[1] = 127;
351
+ header.writeUInt32BE(0, 2);
352
+ header.writeUInt32BE(len, 6);
353
+ }
354
+ return Buffer.concat([header, payload]);
355
+ }
356
+
357
+ /** @private Parse incoming WebSocket frames. */
358
+ _onData(chunk)
359
+ {
360
+ this._buffer = Buffer.concat([this._buffer, chunk]);
361
+
362
+ while (this._buffer.length >= 2)
363
+ {
364
+ const firstByte = this._buffer[0];
365
+ const secondByte = this._buffer[1];
366
+ const opcode = firstByte & 0x0F;
367
+ const masked = (secondByte & 0x80) !== 0;
368
+ let payloadLen = secondByte & 0x7F;
369
+ let offset = 2;
370
+
371
+ if (payloadLen === 126)
372
+ {
373
+ if (this._buffer.length < 4) return;
374
+ payloadLen = this._buffer.readUInt16BE(2);
375
+ offset = 4;
376
+ }
377
+ else if (payloadLen === 127)
378
+ {
379
+ if (this._buffer.length < 10) return;
380
+ // RFC 6455: 64-bit unsigned integer; read upper and lower 32-bit halves
381
+ const upper = this._buffer.readUInt32BE(2);
382
+ const lower = this._buffer.readUInt32BE(6);
383
+ // Reject frames where upper 32 bits are set (>4GB not supported)
384
+ if (upper > 0) { this.close(1009, 'Message too big'); this._buffer = Buffer.alloc(0); return; }
385
+ payloadLen = lower;
386
+ offset = 10;
387
+ }
388
+
389
+ // Enforce max payload
390
+ if (payloadLen > this.maxPayload)
391
+ {
392
+ this.close(1009, 'Message too big');
393
+ this._buffer = Buffer.alloc(0);
394
+ return;
395
+ }
396
+
397
+ const maskSize = masked ? 4 : 0;
398
+ const totalLen = offset + maskSize + payloadLen;
399
+ if (this._buffer.length < totalLen) return;
400
+
401
+ let payload = this._buffer.slice(offset + maskSize, totalLen);
402
+ if (masked)
403
+ {
404
+ const mask = this._buffer.slice(offset, offset + 4);
405
+ payload = Buffer.alloc(payloadLen);
406
+ for (let i = 0; i < payloadLen; i++)
407
+ {
408
+ payload[i] = this._buffer[offset + maskSize + i] ^ mask[i & 3];
409
+ }
410
+ }
411
+
412
+ this._buffer = this._buffer.slice(totalLen);
413
+
414
+ switch (opcode)
415
+ {
416
+ case 0x01: // text
417
+ this._emit('message', payload.toString('utf8'));
418
+ break;
419
+ case 0x02: // binary
420
+ this._emit('message', payload);
421
+ break;
422
+ case 0x08: // close
423
+ {
424
+ const closeCode = payload.length >= 2 ? payload.readUInt16BE(0) : 1005;
425
+ const closeReason = payload.length > 2 ? payload.slice(2).toString('utf8') : '';
426
+ this.readyState = WS_READY_STATE.CLOSED;
427
+ this._clearPing();
428
+ try { this._socket.write(this._buildFrame(0x08, payload)); } catch (e) { }
429
+ this._socket.end();
430
+ this._emit('close', closeCode, closeReason);
431
+ return;
432
+ }
433
+ case 0x09: // ping
434
+ this._emit('ping', payload);
435
+ try { this._socket.write(this._buildFrame(0x0A, payload)); } catch (e) { }
436
+ break;
437
+ case 0x0A: // pong
438
+ this._emit('pong', payload);
439
+ break;
440
+ }
441
+ }
442
+ }
443
+ }
444
+
445
+ /** Ready-state constants exposed on the class for convenience. */
446
+ WebSocketConnection.CONNECTING = WS_READY_STATE.CONNECTING;
447
+ WebSocketConnection.OPEN = WS_READY_STATE.OPEN;
448
+ WebSocketConnection.CLOSING = WS_READY_STATE.CLOSING;
449
+ WebSocketConnection.CLOSED = WS_READY_STATE.CLOSED;
450
+
451
+ module.exports = WebSocketConnection;