walter-ws 0.0.0-stage → 1.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/README.md CHANGED
@@ -1,3 +1,76 @@
1
- # Temporary Holding Version
1
+ # walter-ws ⚡
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Sıfır dış bağımlılığa sahip (**zero-dependency**), tamamen saf Node.js üzerinde çalışan ultra hızlı **RFC 6455 WebSocket Sunucu & İstemci** kütüphanesi.
4
+
5
+ Standart `ws` paketinin birebir **drop-in** (doğrudan) alternatifidir ve pre-encoded broadcast, 32-bit blok maskeleme ve zero-copy `socket.cork()` mimarisiyle çoklu istemci ve büyük veri transferlerinde yüksek performans sunar.
6
+
7
+ ---
8
+
9
+ ## Kurulum
10
+
11
+ ```bash
12
+ # NPM üzerinden kurulum:
13
+ npm i walter-ws
14
+
15
+ # Veya "walter" takma adıyla (alias) kullanmak için:
16
+ npm i walter@npm:walter-ws
17
+ ```
18
+
19
+ ---
20
+
21
+ ## Kullanım (CommonJS & ES Modules)
22
+
23
+ ### 1. Sunucu Oluşturma
24
+
25
+ ```js
26
+ // CommonJS:
27
+ const { WebSocketServer } = require('walter-ws');
28
+ // veya: const { WalterServer } = require('walter-ws');
29
+ // veya ESM: import { WebSocketServer } from 'walter-ws';
30
+
31
+ const wss = new WebSocketServer({
32
+ port: 8080,
33
+ maxPayload: 1024 * 1024, // 1 MB limit
34
+ heartbeatInterval: 30000, // Otomatik ping/pong kontrolü
35
+ });
36
+
37
+ wss.on('connection', (ws, req) => {
38
+ ws.send('Merhaba walter-ws!');
39
+
40
+ ws.on('message', (data, isBinary) => {
41
+ // Gönderen hariç herkese tek seferde pre-encoded yayın (Broadcast)
42
+ wss.broadcast(data, { except: ws, binary: isBinary });
43
+ });
44
+ });
45
+ ```
46
+
47
+ ### 2. İstemci (Client) Kullanımı
48
+
49
+ ```js
50
+ const WebSocket = require('walter-ws');
51
+
52
+ const ws = new WebSocket('ws://127.0.0.1:8080');
53
+
54
+ ws.on('open', () => {
55
+ ws.send('Selam sunucu!');
56
+ ws.sendJSON({ event: 'ping', ts: Date.now() });
57
+ });
58
+
59
+ ws.on('message', (data, isBinary) => {
60
+ console.log('Gelen mesaj:', data);
61
+ });
62
+ ```
63
+
64
+ ---
65
+
66
+ ## CLI (Komut Satırı Aracı)
67
+
68
+ Global kurulduğunda veya `npx` ile doğrudan terminalden WebSocket sunucusu açabilir ya da herhangi bir WebSocket adresine bağlanabilirsiniz:
69
+
70
+ ```bash
71
+ # 8080 portunda hızlı test sunucusu başlatır
72
+ walter server 8080
73
+
74
+ # Bir WebSocket sunucusuna interaktif terminal istemcisiyle bağlanır
75
+ walter connect ws://127.0.0.1:8080
76
+ ```
@@ -0,0 +1,104 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const readline = require('node:readline');
5
+ const { WalterServer, WalterClient } = require('../src');
6
+
7
+ const args = process.argv.slice(2);
8
+ const command = args[0];
9
+
10
+ function printHelp() {
11
+ console.log(`
12
+ walter-ws — Ultra-Fast Zero-Dependency RFC 6455 WebSocket CLI
13
+
14
+ Kullanım:
15
+ walter-ws server [port] [host] WebSocket Echo & Broadcast sunucusu başlatır (Varsayılan: 8080)
16
+ walter-ws connect <ws://url> Belirtilen WebSocket sunucusuna interaktif bağlanır
17
+ walter-ws --help Bu yardım mesajını gösterir
18
+
19
+ Örnekler:
20
+ walter-ws server 8080
21
+ walter-ws connect ws://127.0.0.1:8080
22
+ `);
23
+ }
24
+
25
+ if (!command || command === '--help' || command === '-h') {
26
+ printHelp();
27
+ process.exit(0);
28
+ }
29
+
30
+ if (command === 'server' || command === 'serve') {
31
+ const port = Number(args[1]) || Number(process.env.PORT) || 8080;
32
+ const host = args[2] || process.env.HOST || '127.0.0.1';
33
+
34
+ const wss = new WalterServer({ port, host, heartbeatInterval: 30000 });
35
+
36
+ wss.on('listening', (addr) => {
37
+ console.log(`[walter-ws] Sunucu dinleniyor: ws://${addr.address}:${addr.port}`);
38
+ });
39
+
40
+ wss.on('connection', (ws, req) => {
41
+ console.log(`[+] Bağlantı açıldı (#${ws.id}) - ${req.socket.remoteAddress}`);
42
+
43
+ ws.on('message', (data, isBinary) => {
44
+ console.log(`[#${ws.id}] -> ${isBinary ? `<Binary ${data.length}B>` : data}`);
45
+ ws.send(data, { binary: isBinary });
46
+ });
47
+
48
+ ws.on('close', (code, reason) => {
49
+ console.log(`[-] Bağlantı kapandı (#${ws.id}) [Kod: ${code}${reason ? `, Sebep: ${reason}` : ''}]`);
50
+ });
51
+ });
52
+ } else if (command === 'connect' || command === 'client' || command.startsWith('ws://') || command.startsWith('wss://')) {
53
+ const targetUrl = command.startsWith('ws') ? command : args[1];
54
+ if (!targetUrl) {
55
+ console.error('Hata: Bağlanılacak bir ws:// veya wss:// adresi belirtin.');
56
+ process.exit(1);
57
+ }
58
+
59
+ const client = new WalterClient(targetUrl);
60
+
61
+ const rl = readline.createInterface({
62
+ input: process.stdin,
63
+ output: process.stdout,
64
+ prompt: 'walter-ws> ',
65
+ });
66
+
67
+ client.on('open', () => {
68
+ console.log(`[walter-ws] Bağlandı: ${targetUrl}`);
69
+ rl.prompt();
70
+ });
71
+
72
+ client.on('message', (data, isBinary) => {
73
+ process.stdout.clearLine?.(0);
74
+ process.stdout.cursorTo?.(0);
75
+ console.log(`< ${isBinary ? `<Binary ${data.length}B>` : data}`);
76
+ rl.prompt();
77
+ });
78
+
79
+ client.on('close', (code, reason) => {
80
+ console.log(`\n[walter-ws] Bağlantı kapandı (Kod: ${code}${reason ? `, Sebep: ${reason}` : ''})`);
81
+ process.exit(0);
82
+ });
83
+
84
+ client.on('error', (err) => {
85
+ console.error(`\n[walter-ws] Hata: ${err.message}`);
86
+ });
87
+
88
+ rl.on('line', (line) => {
89
+ const trimmed = line.trim();
90
+ if (trimmed === '/quit' || trimmed === '/exit') {
91
+ client.close(1000, 'Client exited');
92
+ rl.close();
93
+ return;
94
+ }
95
+ if (client.readyState === 1 && trimmed.length > 0) {
96
+ client.send(trimmed);
97
+ }
98
+ rl.prompt();
99
+ });
100
+ } else {
101
+ console.error(`Bilinmeyen komut: ${command}`);
102
+ printHelp();
103
+ process.exit(1);
104
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "walter-ws",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Ultra-fast zero-dependency RFC 6455 WebSocket Server & Client implementation in pure Node.js",
5
+ "main": "./src/index.js",
6
+ "module": "./src/index.mjs",
7
+ "types": "./src/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.d.ts",
11
+ "import": "./src/index.mjs",
12
+ "require": "./src/index.js",
13
+ "default": "./src/index.js"
14
+ }
15
+ },
16
+ "bin": {
17
+ "walter-ws": "bin/walter-ws.js",
18
+ "walter": "bin/walter-ws.js"
19
+ },
20
+ "files": [
21
+ "src/",
22
+ "bin/",
23
+ "README.md"
24
+ ],
25
+ "scripts": {
26
+ "start": "node examples/server.js",
27
+ "live": "node examples/live-crypto.js",
28
+ "test": "node --test test/walter-ws.test.js",
29
+ "bench": "node benchmark/vs.js"
30
+ },
31
+ "keywords": [
32
+ "websocket",
33
+ "rfc6455",
34
+ "ws",
35
+ "walter",
36
+ "walter-ws",
37
+ "zero-dependency"
38
+ ],
39
+ "author": "",
40
+ "license": "MIT",
41
+ "engines": {
42
+ "node": ">=18.0.0"
43
+ },
44
+ "devDependencies": {
45
+ "ws": "^8.20.0"
46
+ }
47
+ }
package/src/client.js ADDED
@@ -0,0 +1,395 @@
1
+ 'use strict';
2
+
3
+ const http = require('node:http');
4
+ const https = require('node:https');
5
+ const crypto = require('node:crypto');
6
+ const { EventEmitter } = require('node:events');
7
+ const { READY_STATES, CLOSE_CODES } = require('./constants');
8
+ const { WalterConnection } = require('./connection');
9
+ const { computeAcceptKey } = require('./server');
10
+
11
+ const KEY_POOL_SIZE = 4096;
12
+ const keyPool = Buffer.allocUnsafe(KEY_POOL_SIZE);
13
+ crypto.randomFillSync(keyPool);
14
+ let keyPoolOffset = 0;
15
+
16
+ function generateSecWebSocketKey() {
17
+ if (keyPoolOffset + 16 > KEY_POOL_SIZE) {
18
+ crypto.randomFillSync(keyPool);
19
+ keyPoolOffset = 0;
20
+ }
21
+ const key = keyPool.subarray(keyPoolOffset, keyPoolOffset + 16).toString('base64');
22
+ keyPoolOffset += 16;
23
+ return key;
24
+ }
25
+
26
+ /**
27
+ * Pure Node.js RFC 6455 WebSocket Client ("walter-ws").
28
+ */
29
+ class WalterClient extends EventEmitter {
30
+ /**
31
+ * @param {string|URL} url - WebSocket URL (ws:// or wss://)
32
+ * @param {object} [options]
33
+ * @param {Record<string, string>} [options.headers] - Custom HTTP headers for the handshake
34
+ * @param {string|string[]} [options.protocols] - Optional subprotocol(s)
35
+ * @param {number} [options.maxPayload=1048576] - Max allowed incoming frame/message payload size in bytes
36
+ * @param {number} [options.handshakeTimeout=10000] - Handshake timeout in ms
37
+ * @param {boolean} [options.autoReconnect=false] - Automatically reconnect on unexpected disconnect
38
+ * @param {number} [options.reconnectInterval=1000] - Initial reconnect delay in ms
39
+ * @param {number} [options.maxReconnectInterval=30000] - Maximum backoff delay in ms
40
+ * @param {number} [options.maxReconnectAttempts=Infinity] - Max reconnect attempts
41
+ * @param {boolean} [options.offlineQueue=false] - Queue outgoing messages while connecting/reconnecting
42
+ */
43
+ constructor(url, options = {}) {
44
+ super();
45
+
46
+ this.url = typeof url === 'string' ? new URL(url) : url;
47
+ if (this.url.protocol !== 'ws:' && this.url.protocol !== 'wss:') {
48
+ throw new Error(`Invalid WebSocket URL protocol: ${this.url.protocol}`);
49
+ }
50
+
51
+ this.options = {
52
+ headers: options.headers || {},
53
+ protocols: options.protocols || null,
54
+ maxPayload: options.maxPayload ?? 1024 * 1024,
55
+ handshakeTimeout: options.handshakeTimeout ?? 10000,
56
+ autoReconnect: options.autoReconnect ?? false,
57
+ reconnectInterval: options.reconnectInterval ?? 1000,
58
+ maxReconnectInterval: options.maxReconnectInterval ?? 30000,
59
+ maxReconnectAttempts: options.maxReconnectAttempts ?? Infinity,
60
+ offlineQueue: options.offlineQueue ?? false,
61
+ };
62
+
63
+ this.readyState = READY_STATES.CONNECTING;
64
+ /** @type {WalterConnection|null} */
65
+ this._connection = null;
66
+ this._req = null;
67
+
68
+ this._explicitClose = false;
69
+ this._reconnectAttempts = 0;
70
+ this._reconnectTimer = null;
71
+ /** @type {Array<{ data: any, options: any, callback: any }>} */
72
+ this._sendQueue = [];
73
+
74
+ // W3C callback properties
75
+ this.onopen = null;
76
+ this.onmessage = null;
77
+ this.onclose = null;
78
+ this.onerror = null;
79
+
80
+ this._connect();
81
+ }
82
+
83
+ /**
84
+ * Initiates the HTTP Upgrade handshake with the remote server.
85
+ */
86
+ _connect() {
87
+ const isSecure = this.url.protocol === 'wss:';
88
+ const transport = isSecure ? https : http;
89
+ const key = generateSecWebSocketKey();
90
+ const expectedAccept = computeAcceptKey(key);
91
+
92
+ const headers = {
93
+ ...this.options.headers,
94
+ Upgrade: 'websocket',
95
+ Connection: 'Upgrade',
96
+ 'Sec-WebSocket-Key': key,
97
+ 'Sec-WebSocket-Version': '13',
98
+ };
99
+
100
+ if (this.options.protocols) {
101
+ const protoList = Array.isArray(this.options.protocols)
102
+ ? this.options.protocols.join(', ')
103
+ : String(this.options.protocols);
104
+ headers['Sec-WebSocket-Protocol'] = protoList;
105
+ }
106
+
107
+ const reqOptions = {
108
+ protocol: isSecure ? 'https:' : 'http:',
109
+ hostname: this.url.hostname,
110
+ port: this.url.port || (isSecure ? 443 : 80),
111
+ path: `${this.url.pathname}${this.url.search}`,
112
+ method: 'GET',
113
+ headers,
114
+ agent: false,
115
+ timeout: this.options.handshakeTimeout,
116
+ };
117
+
118
+ const req = transport.request(reqOptions);
119
+ this._req = req;
120
+
121
+ req.on('timeout', () => {
122
+ req.destroy(new Error('WebSocket opening handshake timed out'));
123
+ });
124
+
125
+ req.on('error', (err) => {
126
+ if (this.readyState !== READY_STATES.CLOSED) {
127
+ this.readyState = READY_STATES.CLOSED;
128
+ if (this.listenerCount('error') > 0) {
129
+ this.emit('error', err);
130
+ }
131
+ if (typeof this.onerror === 'function') {
132
+ this.onerror({ error: err, message: err.message, target: this });
133
+ }
134
+ this._handleDisconnect(CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
135
+ }
136
+ });
137
+
138
+ req.on('response', (res) => {
139
+ const err = new Error(`Unexpected server response: ${res.statusCode}`);
140
+ this.readyState = READY_STATES.CLOSED;
141
+ res.resume();
142
+ if (this.listenerCount('error') > 0) {
143
+ this.emit('error', err);
144
+ }
145
+ if (typeof this.onerror === 'function') {
146
+ this.onerror({ error: err, message: err.message, target: this });
147
+ }
148
+ this._handleDisconnect(CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
149
+ });
150
+
151
+ req.on('upgrade', (res, socket, head) => {
152
+ const acceptHeader = res.headers['sec-websocket-accept'];
153
+ if (acceptHeader !== expectedAccept) {
154
+ socket.destroy();
155
+ const err = new Error(
156
+ `Invalid Sec-WebSocket-Accept header: expected ${expectedAccept}, got ${acceptHeader}`
157
+ );
158
+ this.readyState = READY_STATES.CLOSED;
159
+ if (this.listenerCount('error') > 0) {
160
+ this.emit('error', err);
161
+ }
162
+ if (typeof this.onerror === 'function') {
163
+ this.onerror({ error: err, message: err.message, target: this });
164
+ }
165
+ this._handleDisconnect(CLOSE_CODES.PROTOCOL_ERROR, err.message);
166
+ return;
167
+ }
168
+
169
+ this._connection = new WalterConnection(socket, {
170
+ isServer: false, // Client masks outgoing frames and expects unmasked server frames
171
+ maxPayload: this.options.maxPayload,
172
+ });
173
+
174
+ this.readyState = READY_STATES.OPEN;
175
+ this._reconnectAttempts = 0;
176
+ this.protocol = res.headers['sec-websocket-protocol'] || null;
177
+
178
+ this._connection.on('message', (data, isBinary) => {
179
+ this.emit('message', data, isBinary);
180
+ if (typeof this.onmessage === 'function') {
181
+ this.onmessage({ data, isBinary, target: this });
182
+ }
183
+ });
184
+
185
+ this._connection.on('ping', (data) => {
186
+ this.emit('ping', data);
187
+ });
188
+
189
+ this._connection.on('pong', (data) => {
190
+ this.emit('pong', data);
191
+ });
192
+
193
+ this._connection.on('error', (err) => {
194
+ if (this.listenerCount('error') > 0) {
195
+ this.emit('error', err);
196
+ }
197
+ if (typeof this.onerror === 'function') {
198
+ this.onerror({ error: err, message: err.message, target: this });
199
+ }
200
+ });
201
+
202
+ this._connection.on('close', (code, reason) => {
203
+ this.readyState = READY_STATES.CLOSED;
204
+ this._handleDisconnect(code, reason);
205
+ });
206
+
207
+ this.emit('open');
208
+ if (typeof this.onopen === 'function') {
209
+ this.onopen({ target: this });
210
+ }
211
+
212
+ this._flushOfflineQueue();
213
+
214
+ if (head && head.length > 0) {
215
+ this._connection._onSocketData(head);
216
+ }
217
+ });
218
+
219
+ req.end();
220
+ }
221
+
222
+ /**
223
+ * Handles disconnection and schedules automatic reconnect if enabled.
224
+ * @param {number} code
225
+ * @param {string} reason
226
+ */
227
+ _handleDisconnect(code, reason) {
228
+ this.emit('close', code, reason);
229
+ if (typeof this.onclose === 'function') {
230
+ this.onclose({ code, reason, target: this });
231
+ }
232
+
233
+ if (
234
+ this.options.autoReconnect &&
235
+ !this._explicitClose &&
236
+ this._reconnectAttempts < this.options.maxReconnectAttempts
237
+ ) {
238
+ const attempt = this._reconnectAttempts++;
239
+ const delay = Math.min(
240
+ this.options.reconnectInterval * Math.pow(1.5, attempt),
241
+ this.options.maxReconnectInterval
242
+ );
243
+ this.emit('reconnecting', attempt + 1, delay);
244
+ this._reconnectTimer = setTimeout(() => {
245
+ this.readyState = READY_STATES.CONNECTING;
246
+ this._connect();
247
+ }, delay);
248
+ this._reconnectTimer.unref?.();
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Flushes any messages queued while the client was connecting/reconnecting.
254
+ */
255
+ _flushOfflineQueue() {
256
+ if (this._sendQueue.length === 0) return;
257
+ const queue = this._sendQueue;
258
+ this._sendQueue = [];
259
+ for (const item of queue) {
260
+ if (this.readyState === READY_STATES.OPEN && this._connection) {
261
+ this._connection.send(item.data, item.options, item.callback);
262
+ }
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Sends a text or binary message to the server.
268
+ * If `offlineQueue` is true and the connection is not yet OPEN, queues the message automatically.
269
+ *
270
+ * @param {string|Buffer|Uint8Array} data
271
+ * @param {object} [options]
272
+ * @param {Function} [callback]
273
+ */
274
+ send(data, options, callback) {
275
+ if (!this._connection || this.readyState !== READY_STATES.OPEN) {
276
+ if (this.options.offlineQueue && !this._explicitClose) {
277
+ this._sendQueue.push({ data, options, callback });
278
+ return;
279
+ }
280
+ throw new Error(`WebSocket is not open: readyState ${this.readyState}`);
281
+ }
282
+ this._connection.send(data, options, callback);
283
+ }
284
+
285
+ /**
286
+ * Sends an object serialized as JSON text.
287
+ * @param {any} obj
288
+ * @param {Function} [callback]
289
+ */
290
+ sendJSON(obj, callback) {
291
+ this.send(JSON.stringify(obj), { binary: false }, callback);
292
+ }
293
+
294
+ /**
295
+ * Sends a Ping frame to the server.
296
+ * @param {Buffer|string} [data]
297
+ * @param {Function} [callback]
298
+ */
299
+ ping(data, callback) {
300
+ if (!this._connection || this.readyState !== READY_STATES.OPEN) return;
301
+ this._connection.ping(data, callback);
302
+ }
303
+
304
+ /**
305
+ * Sends a Pong frame to the server.
306
+ * @param {Buffer|string} [data]
307
+ * @param {Function} [callback]
308
+ */
309
+ pong(data, callback) {
310
+ if (!this._connection || this.readyState !== READY_STATES.OPEN) return;
311
+ this._connection.pong(data, callback);
312
+ }
313
+
314
+ /**
315
+ * Initiates a clean closing handshake and stops any auto-reconnect timer.
316
+ * @param {number} [code=1000]
317
+ * @param {string} [reason='']
318
+ */
319
+ close(code = CLOSE_CODES.NORMAL_CLOSURE, reason = '') {
320
+ this._explicitClose = true;
321
+ if (this._reconnectTimer) {
322
+ clearTimeout(this._reconnectTimer);
323
+ this._reconnectTimer = null;
324
+ }
325
+
326
+ if (this.readyState === READY_STATES.CLOSED || this.readyState === READY_STATES.CLOSING) {
327
+ return;
328
+ }
329
+ this.readyState = READY_STATES.CLOSING;
330
+ if (this._connection) {
331
+ this._connection.close(code, reason);
332
+ } else if (this._req) {
333
+ this._req.destroy();
334
+ }
335
+ }
336
+
337
+ /**
338
+ * W3C EventTarget compatibility: addEventListener
339
+ * @param {string} type
340
+ * @param {Function} listener
341
+ * @param {object|boolean} [options]
342
+ */
343
+ addEventListener(type, listener, options) {
344
+ if (typeof listener !== 'function') return;
345
+ const once = typeof options === 'object' && options !== null && options.once;
346
+ const wrapped = (arg1, arg2) => {
347
+ if (type === 'message') {
348
+ listener({ data: arg1, isBinary: arg2, target: this });
349
+ } else if (type === 'close') {
350
+ listener({ code: arg1, reason: arg2, target: this });
351
+ } else if (type === 'error') {
352
+ listener({ error: arg1, message: arg1?.message, target: this });
353
+ } else {
354
+ listener({ target: this });
355
+ }
356
+ };
357
+ listener._walterWrapped = wrapped;
358
+ if (once) {
359
+ this.once(type, wrapped);
360
+ } else {
361
+ this.on(type, wrapped);
362
+ }
363
+ }
364
+
365
+ /**
366
+ * W3C EventTarget compatibility: removeEventListener
367
+ * @param {string} type
368
+ * @param {Function} listener
369
+ */
370
+ removeEventListener(type, listener) {
371
+ if (!listener) return;
372
+ this.removeListener(type, listener._walterWrapped || listener);
373
+ }
374
+
375
+ /**
376
+ * Immediately terminates the underlying socket connection.
377
+ */
378
+ terminate() {
379
+ this._explicitClose = true;
380
+ if (this._reconnectTimer) {
381
+ clearTimeout(this._reconnectTimer);
382
+ this._reconnectTimer = null;
383
+ }
384
+ this.readyState = READY_STATES.CLOSED;
385
+ if (this._connection) {
386
+ this._connection.terminate();
387
+ } else if (this._req) {
388
+ this._req.destroy();
389
+ }
390
+ }
391
+ }
392
+
393
+ module.exports = {
394
+ WalterClient,
395
+ };