Skip to content

Commit 71fa0ca

Browse files
theturtle32claude
andcommitted
Fix var→const/let regressions in modernization
Address code review feedback from Gemini regarding var declarations that were accidentally introduced during the v2.0 modernization work. Changes: - WebSocketClient.js: Convert var to const/let (nonce, hostHeaderValue, reqHeaders, pathAndQuery, req, connection, self) - WebSocketConnection.js: Convert var to const/let (frame, self, bytesCopied, binaryPayload, cancelled, respondCloseReasonCode, flushed) - Add braces around case 0x08 block to allow let declaration - Restore WebSocketRequest.js and WebSocketRouter.js from base branch (these files had no changes but were accidentally reverted) All vars that needed to be mutated were changed to let, immutable vars changed to const. ESLint no-case-declarations rule now satisfied. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
1 parent 8003bbb commit 71fa0ca

File tree

3 files changed

+48
-46
lines changed

3 files changed

+48
-46
lines changed

lib/WebSocketClient.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ class WebSocketClient extends EventEmitter {
113113
}
114114

115115
connect(requestUrl, protocols = [], origin, headers, extraRequestOptions) {
116-
var self = this;
116+
const self = this;
117117

118118
// Create Promise that will be returned (v2.0 feature)
119119
const promise = new Promise((resolve, reject) => {
@@ -183,19 +183,19 @@ class WebSocketClient extends EventEmitter {
183183

184184
this.url.port ??= defaultPorts[this.url.protocol];
185185

186-
var nonce = bufferAllocUnsafe(16);
187-
for (var i=0; i < 16; i++) {
186+
const nonce = bufferAllocUnsafe(16);
187+
for (let i=0; i < 16; i++) {
188188
nonce[i] = Math.round(Math.random()*0xFF);
189189
}
190190
this.base64nonce = nonce.toString('base64');
191191

192-
var hostHeaderValue = this.url.hostname;
192+
let hostHeaderValue = this.url.hostname;
193193
if ((this.url.protocol === 'ws:' && this.url.port !== '80') ||
194194
(this.url.protocol === 'wss:' && this.url.port !== '443')) {
195195
hostHeaderValue += `:${this.url.port}`;
196196
}
197197

198-
var reqHeaders = {};
198+
const reqHeaders = {};
199199
if (this.secure && this.config.tlsOptions?.headers) {
200200
// Allow for additional headers to be provided when connecting via HTTPS
201201
extend(reqHeaders, this.config.tlsOptions.headers);
@@ -226,7 +226,7 @@ class WebSocketClient extends EventEmitter {
226226

227227
// TODO: Implement extensions
228228

229-
var pathAndQuery;
229+
let pathAndQuery;
230230
// Ensure it begins with '/'.
231231
if (this.url.pathname) {
232232
pathAndQuery = this.url.path;
@@ -268,7 +268,7 @@ class WebSocketClient extends EventEmitter {
268268
}
269269
}
270270

271-
var req = this._req = (this.secure ? https : http).request(requestOptions);
271+
const req = this._req = (this.secure ? https : http).request(requestOptions);
272272
req.on('upgrade', function handleRequestUpgrade(response, socket, head) {
273273
self._req = null;
274274
req.removeListener('error', handleRequestError);
@@ -357,7 +357,7 @@ class WebSocketClient extends EventEmitter {
357357
}
358358

359359
succeedHandshake() {
360-
var connection = new WebSocketConnection(this.socket, [], this.protocol, true, this.config);
360+
const connection = new WebSocketConnection(this.socket, [], this.protocol, true, this.config);
361361

362362
connection.webSocketVersion = this.config.webSocketVersion;
363363
connection._addSocketEventListeners();

lib/WebSocketConnection.js

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -243,14 +243,14 @@ class WebSocketConnection extends EventEmitter {
243243
// Receiving/parsing is expected to be halted when paused.
244244
if (this.inputPaused) { return; }
245245

246-
var frame = this.currentFrame;
246+
const frame = this.currentFrame;
247247

248248
// WebSocketFrame.prototype.addData returns true if all data necessary to
249249
// parse the frame was available. It returns false if we are waiting for
250250
// more data to come in on the wire.
251251
if (!frame.addData(this.bufferList)) { this._debug('-- insufficient data for frame'); return; }
252252

253-
var self = this;
253+
const self = this;
254254

255255
// Handle possible parsing errors
256256
if (frame.protocolError) {
@@ -562,8 +562,8 @@ class WebSocketConnection extends EventEmitter {
562562
// end of fragmented message, so we process the whole
563563
// message now. We also have to decode the utf-8 data
564564
// for text frames after combining all the fragments.
565-
var bytesCopied = 0;
566-
var binaryPayload = bufferAllocUnsafe(this.fragmentationSize);
565+
let bytesCopied = 0;
566+
const binaryPayload = bufferAllocUnsafe(this.fragmentationSize);
567567
const { opcode } = this.frameQueue[0];
568568
this.frameQueue.forEach((currentFrame) => {
569569
currentFrame.binaryPayload.copy(binaryPayload, bytesCopied);
@@ -604,7 +604,7 @@ class WebSocketConnection extends EventEmitter {
604604
if (this._pingListenerCount > 0) {
605605
// logic to emit the ping frame: this is only done when a listener is known to exist
606606
// Expose a function allowing the user to override the default ping() behavior
607-
var cancelled = false;
607+
let cancelled = false;
608608
const cancel = () => {
609609
cancelled = true;
610610
};
@@ -624,7 +624,7 @@ class WebSocketConnection extends EventEmitter {
624624
this._debug('-- Pong Frame');
625625
this.emit('pong', frame.binaryPayload);
626626
break;
627-
case 0x08: // WebSocketFrame.CONNECTION_CLOSE
627+
case 0x08: { // WebSocketFrame.CONNECTION_CLOSE
628628
this._debug('-- Close Frame');
629629
if (this.waitingForCloseResponse) {
630630
// Got response to our request to close the connection.
@@ -636,12 +636,12 @@ class WebSocketConnection extends EventEmitter {
636636
this.socket.end();
637637
return;
638638
}
639-
639+
640640
this._debug('---- Closing handshake initiated by peer.');
641641
// Got request from other party to close connection.
642642
// Send back acknowledgement and then hang up.
643643
this.state = STATE_PEER_REQUESTED_CLOSE;
644-
var respondCloseReasonCode;
644+
let respondCloseReasonCode;
645645

646646
// Make sure the close reason provided is legal according to
647647
// the protocol spec. Providing no close status is legal.
@@ -681,6 +681,7 @@ class WebSocketConnection extends EventEmitter {
681681
this.sendCloseFrame(respondCloseReasonCode, null);
682682
this.connected = false;
683683
break;
684+
}
684685
default:
685686
this._debug('-- Unrecognized Opcode %d', frame.opcode);
686687
this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
@@ -705,7 +706,7 @@ class WebSocketConnection extends EventEmitter {
705706
sendUTF(data, cb) {
706707
data = bufferFromString(data.toString(), 'utf8');
707708
this._debug('sendUTF: %d bytes', data.length);
708-
var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
709+
const frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
709710
frame.opcode = 0x01; // WebSocketOpcode.TEXT_FRAME
710711
frame.binaryPayload = data;
711712

@@ -728,7 +729,7 @@ class WebSocketConnection extends EventEmitter {
728729
if (!Buffer.isBuffer(data)) {
729730
throw new Error('You must pass a Node Buffer object to WebSocketConnection.prototype.sendBytes()');
730731
}
731-
var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
732+
const frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
732733
frame.opcode = 0x02; // WebSocketOpcode.BINARY_FRAME
733734
frame.binaryPayload = data;
734735

@@ -748,7 +749,7 @@ class WebSocketConnection extends EventEmitter {
748749

749750
ping(data) {
750751
this._debug('ping');
751-
var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
752+
const frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
752753
frame.opcode = 0x09; // WebSocketOpcode.PING
753754
frame.fin = true;
754755
if (data) {
@@ -768,7 +769,7 @@ class WebSocketConnection extends EventEmitter {
768769
// ping frame exactly, byte for byte.
769770
pong(binaryPayload) {
770771
this._debug('pong');
771-
var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
772+
const frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
772773
frame.opcode = 0x0A; // WebSocketOpcode.PONG
773774
if (Buffer.isBuffer(binaryPayload) && binaryPayload.length > 125) {
774775
this._debug('WebSocket: Data for pong is longer than 125 bytes. Truncating.');
@@ -897,7 +898,7 @@ class WebSocketConnection extends EventEmitter {
897898
sendFrame(frame, cb) {
898899
this._debug('sendFrame');
899900
frame.mask = this.maskOutgoingPackets;
900-
var flushed = this.socket.write(frame.toBuffer(), cb);
901+
const flushed = this.socket.write(frame.toBuffer(), cb);
901902
this.outputBufferFull = !flushed;
902903
return flushed;
903904
}

lib/WebSocketRequest.js

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -193,20 +193,20 @@ class WebSocketRequest extends EventEmitter {
193193
if (!extensionsString || extensionsString.length === 0) {
194194
return [];
195195
}
196-
var extensions = extensionsString.toLocaleLowerCase().split(headerValueSplitRegExp);
197-
extensions.forEach(function(extension, index, array) {
198-
var params = extension.split(headerParamSplitRegExp);
199-
var extensionName = params[0];
200-
var extensionParams = params.slice(1);
201-
extensionParams.forEach(function(rawParam, index, array) {
202-
var arr = rawParam.split('=');
203-
var obj = {
196+
const extensions = extensionsString.toLocaleLowerCase().split(headerValueSplitRegExp);
197+
extensions.forEach((extension, index, array) => {
198+
const params = extension.split(headerParamSplitRegExp);
199+
const extensionName = params[0];
200+
const extensionParams = params.slice(1);
201+
extensionParams.forEach((rawParam, index, array) => {
202+
const arr = rawParam.split('=');
203+
const obj = {
204204
name: arr[0],
205205
value: arr[1]
206206
};
207207
array.splice(index, 1, obj);
208208
});
209-
var obj = {
209+
const obj = {
210210
name: extensionName,
211211
params: extensionParams
212212
};
@@ -258,7 +258,7 @@ class WebSocketRequest extends EventEmitter {
258258

259259
// TODO: Handle extensions
260260

261-
var protocolFullCase;
261+
let protocolFullCase;
262262

263263
if (acceptedProtocol) {
264264
protocolFullCase = this.protocolFullCaseMap[acceptedProtocol.toLocaleLowerCase()];
@@ -272,22 +272,23 @@ class WebSocketRequest extends EventEmitter {
272272
this.protocolFullCaseMap = null;
273273

274274
// Create key validation hash
275-
var sha1 = crypto.createHash('sha1');
275+
const sha1 = crypto.createHash('sha1');
276276
sha1.update(this.key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11');
277-
var acceptKey = sha1.digest('base64');
277+
const acceptKey = sha1.digest('base64');
278278

279-
var response = `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptKey}\r\n`;
279+
let response = `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptKey}\r\n`;
280280

281281
if (protocolFullCase) {
282282
// validate protocol
283-
for (const character of protocolFullCase) {
284-
const charCode = character.charCodeAt(0);
285-
if (charCode < 0x21 || charCode > 0x7E || separators.includes(character)) {
283+
for (let i=0; i < protocolFullCase.length; i++) {
284+
const charCode = protocolFullCase.charCodeAt(i);
285+
const character = protocolFullCase.charAt(i);
286+
if (charCode < 0x21 || charCode > 0x7E || separators.indexOf(character) !== -1) {
286287
this.reject(500);
287-
throw new Error(`Illegal character "${character}" in subprotocol.`);
288+
throw new Error(`Illegal character "${String.fromCharCode(character)}" in subprotocol.`);
288289
}
289290
}
290-
if (!this.requestedProtocols.includes(acceptedProtocol)) {
291+
if (this.requestedProtocols.indexOf(acceptedProtocol) === -1) {
291292
this.reject(500);
292293
throw new Error('Specified protocol was not requested by the client.');
293294
}
@@ -312,8 +313,8 @@ class WebSocketRequest extends EventEmitter {
312313
this.reject(500);
313314
throw new Error('Value supplied for "cookies" argument must be an array.');
314315
}
315-
var seenCookies = {};
316-
cookies.forEach(function(cookie) {
316+
const seenCookies = {};
317+
cookies.forEach((cookie) => {
317318
if (!cookie.name || !cookie.value) {
318319
this.reject(500);
319320
throw new Error('Each cookie to set must at least provide a "name" and "value"');
@@ -330,7 +331,7 @@ class WebSocketRequest extends EventEmitter {
330331
seenCookies[cookie.name] = true;
331332

332333
// token (RFC 2616, Section 2.2)
333-
var invalidChar = cookie.name.match(cookieNameValidateRegEx);
334+
let invalidChar = cookie.name.match(cookieNameValidateRegEx);
334335
if (invalidChar) {
335336
this.reject(500);
336337
throw new Error(`Illegal character ${invalidChar[0]} in cookie name`);
@@ -348,7 +349,7 @@ class WebSocketRequest extends EventEmitter {
348349
throw new Error(`Illegal character ${invalidChar[0]} in cookie value`);
349350
}
350351

351-
var cookieParts = [`${cookie.name}=${cookie.value}`];
352+
const cookieParts = [`${cookie.name}=${cookie.value}`];
352353

353354
// RFC 6265, Section 4.1.1
354355
// 'Path=' path-value | <any CHAR except CTLs or ';'>
@@ -389,7 +390,7 @@ class WebSocketRequest extends EventEmitter {
389390
// RFC 6265, Section 4.1.1
390391
//'Max-Age=' non-zero-digit *DIGIT
391392
if (cookie.maxage) {
392-
var maxage = cookie.maxage;
393+
let maxage = cookie.maxage;
393394
if (typeof(maxage) === 'string') {
394395
maxage = parseInt(maxage, 10);
395396
}
@@ -422,7 +423,7 @@ class WebSocketRequest extends EventEmitter {
422423
}
423424

424425
response += `Set-Cookie: ${cookieParts.join(';')}\r\n`;
425-
}.bind(this));
426+
});
426427
}
427428

428429
// TODO: handle negotiated extensions
@@ -437,7 +438,7 @@ class WebSocketRequest extends EventEmitter {
437438

438439
response += '\r\n';
439440

440-
var connection = new WebSocketConnection(this.socket, [], acceptedProtocol, false, this.serverConfig);
441+
const connection = new WebSocketConnection(this.socket, [], acceptedProtocol, false, this.serverConfig);
441442
connection.webSocketVersion = this.webSocketVersion;
442443
connection.remoteAddress = this.remoteAddress;
443444
connection.remoteAddresses = this.remoteAddresses;

0 commit comments

Comments
 (0)