Skip to content

Commit 3061c00

Browse files
theturtle32claude
andcommitted
WIP: ES6 refactoring - complete core library modernization
- Convert var → const/let across 13 core library files - Apply template literals for string concatenation - Modernize variable scoping in loops and functions - Add ES6_REFACTORING_PLAN.md documenting progress and next steps - Maintain backward compatibility with Node.js 4.x+ Core files refactored: - lib/WebSocketConnection.js (extensive class conversion) - lib/WebSocketClient.js, lib/WebSocketServer.js - lib/WebSocketFrame.js, lib/WebSocketRequest.js - lib/W3CWebSocket.js, lib/Deprecation.js - lib/utils.js, lib/websocket.js, lib/browser.js - example/whiteboard/whiteboard.js 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent d87afb7 commit 3061c00

15 files changed

+1018
-855
lines changed

CLAUDE.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# WebSocket-Node Development Guide
2+
3+
## Build/Test Commands
4+
- Run all tests: `npm test`
5+
- Run single test: `npx tape test/unit/[filename].js`
6+
- Lint codebase: `npm run gulp` or `npx gulp lint`
7+
- Run autobahn tests: `cd test/autobahn && ./run-wstest.sh`
8+
9+
## Coding Style
10+
- Use tabs for indentation
11+
- Constants: ALL_CAPS with underscores
12+
- Variables/Functions: camelCase
13+
- Classes: PascalCase
14+
- Private properties: prefix with underscore (_propertyName)
15+
- Prefer const/let over var for new code
16+
- Use descriptive error messages with proper capitalization
17+
- Maintain backward compatibility with Node.js 4.x+
18+
- Use EventEmitter pattern for async events
19+
- Always catch and handle errors in Promise chains
20+
- Document API facing methods with clear JSDoc comments
21+
- Use utility functions from ./lib/utils.js for buffer operations
22+
- Add debug logging with the debug module at key points

ES6_REFACTORING_PLAN.md

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
# WebSocket-Node ES6 Refactoring Plan
2+
3+
## Current Status
4+
5+
The ES6 refactoring is **partially complete**. The following core library files have been refactored:
6+
7+
### ✅ Completed Files (13 files)
8+
- `lib/Deprecation.js` - Basic var → const conversion
9+
- `lib/W3CWebSocket.js` - var → const/let conversion
10+
- `lib/WebSocketClient.js` - var → const conversion
11+
- `lib/WebSocketConnection.js` - Extensive refactoring (1442 lines changed)
12+
- `lib/WebSocketFrame.js` - var → const conversion
13+
- `lib/WebSocketRequest.js` - var → const conversion
14+
- `lib/WebSocketRouter.js` - var → const conversion
15+
- `lib/WebSocketRouterRequest.js` - Basic var → const conversion
16+
- `lib/WebSocketServer.js` - var → const conversion
17+
- `lib/browser.js` - var → const conversion
18+
- `lib/utils.js` - var → const/let conversion + template literals
19+
- `lib/websocket.js` - var → const conversion
20+
- `example/whiteboard/whiteboard.js` - Example file refactored
21+
22+
### 🔄 Refactoring Patterns Applied
23+
1. **Variable Declarations**: `var``const`/`let` based on reassignment
24+
2. **Template Literals**: String concatenation → template literals (partial)
25+
3. **Block Scoping**: Proper const/let scoping in loops and functions
26+
4. **Modern Syntax**: Arrow functions in some contexts
27+
28+
## Remaining Work
29+
30+
### 1. **Unmodified Library Files** (1 file)
31+
- `lib/version.js` - Already uses modern `module.exports`, no changes needed
32+
33+
### 2. **Test Suite Refactoring** (15 files)
34+
**Priority: Medium** - Tests use old ES3/ES5 patterns
35+
36+
#### Unit Tests
37+
- `test/unit/request.js` - Uses `var`, old-style functions
38+
- `test/unit/dropBeforeAccept.js` - Needs var → const/let conversion
39+
- `test/unit/regressions.js` - Old variable declarations
40+
- `test/unit/w3cwebsocket.js` - var → const refactoring needed
41+
- `test/unit/websocketFrame.js` - Old-style variable declarations
42+
43+
#### Test Infrastructure
44+
- `test/shared/test-server.js` - Core test server utilities
45+
- `test/shared/start-echo-server.js` - Echo server for tests
46+
47+
#### Test Scripts
48+
- `test/scripts/memoryleak-server.js` - Memory leak testing
49+
- `test/scripts/memoryleak-client.js` - Memory leak client
50+
- `test/scripts/libwebsockets-test-server.js` - LibWebSockets compatibility
51+
- `test/scripts/libwebsockets-test-client.js` - LibWebSockets client
52+
- `test/scripts/fragmentation-test-client.js` - Fragmentation testing
53+
- `test/scripts/fragmentation-test-server.js` - Fragmentation server
54+
- `test/scripts/echo-server.js` - Basic echo server
55+
- `test/scripts/autobahn-test-client.js` - Autobahn test suite client
56+
57+
### 3. **Example Files** (1 file)
58+
**Priority: Low** - Examples should demonstrate modern patterns
59+
- `example/whiteboard/public/client.js` - Browser-side client code
60+
61+
### 4. **Code Quality Improvements**
62+
**Priority: High** - Enhance already-refactored files
63+
64+
#### A. **Enhanced Modern JavaScript Features**
65+
- **Arrow Functions**: Convert appropriate function expressions
66+
- **Destructuring**: Extract object/array properties modernly
67+
- **Template Literals**: Complete string concatenation replacement
68+
- **Default Parameters**: Replace manual parameter defaulting
69+
- **Enhanced Object Literals**: Use shorthand property syntax
70+
- **Spread Operator**: Replace `Array.prototype.slice.call()` patterns
71+
72+
#### B. **Async/Await Migration** (Optional)
73+
- Consider Promise-based APIs where appropriate
74+
- Maintain backward compatibility with callback patterns
75+
76+
#### C. **Class Syntax** (Evaluation Needed)
77+
- Evaluate prototype-based constructors for class conversion
78+
- Maintain inheritance patterns with extends/super
79+
- Consider impact on Node.js 4.x+ compatibility requirements
80+
81+
### 5. **Configuration & Build Updates**
82+
**Priority: Medium**
83+
- Update ESLint rules for ES6+ patterns
84+
- Verify Node.js 4.x+ compatibility maintained
85+
- Update package.json engines field if needed
86+
87+
### 6. **Documentation Updates**
88+
**Priority: Low**
89+
- Update code examples in README to use modern syntax
90+
- Ensure API documentation reflects any syntax changes
91+
92+
## Implementation Strategy
93+
94+
### Phase 1: Test Suite Modernization
95+
**Goal**: Ensure test reliability during refactoring
96+
1. Refactor unit tests (`test/unit/*.js`)
97+
2. Refactor test infrastructure (`test/shared/*.js`)
98+
3. Refactor test scripts (`test/scripts/*.js`)
99+
4. Run full test suite to ensure no regressions
100+
101+
### Phase 2: Code Quality Enhancements
102+
**Goal**: Maximize modern JavaScript usage in core library
103+
1. **Enhanced Template Literals** - Complete string concatenation replacement
104+
2. **Arrow Functions** - Convert appropriate callbacks and handlers
105+
3. **Destructuring** - Simplify object property extraction
106+
4. **Default Parameters** - Clean up manual parameter handling
107+
5. **Object Literal Enhancements** - Use shorthand syntax
108+
109+
### Phase 3: Advanced Features (Optional)
110+
**Goal**: Evaluate modern patterns without breaking changes
111+
1. **Class Syntax Evaluation** - Assess constructor → class conversion
112+
2. **Async/Await Integration** - Add Promise-based alternatives
113+
3. **Module System** - Consider ES6 imports (Node.js version dependent)
114+
115+
### Phase 4: Validation & Cleanup
116+
**Goal**: Ensure quality and compatibility
117+
1. Run complete test suite (`npm test`)
118+
2. Run autobahn compatibility tests
119+
3. Lint entire codebase (`npm run gulp`)
120+
4. Update documentation and examples
121+
5. Performance regression testing
122+
123+
## Compatibility Considerations
124+
125+
- **Node.js 4.x+ Support**: Maintain current compatibility requirements
126+
- **ES6 Feature Support**: All used features must work in Node.js 4.x+
127+
- **API Compatibility**: No breaking changes to public APIs
128+
- **Performance**: Ensure refactoring doesn't impact WebSocket performance
129+
130+
## Risk Assessment
131+
132+
**Low Risk**: Variable declaration changes (var → const/let)
133+
**Medium Risk**: Function expression → arrow function conversion
134+
**High Risk**: Constructor → class conversion, async/await integration
135+
136+
## Success Criteria
137+
138+
1. ✅ All tests pass (`npm test`)
139+
2. ✅ Autobahn tests pass (`cd test/autobahn && ./run-wstest.sh`)
140+
3. ✅ Linting passes (`npm run gulp`)
141+
4. ✅ No performance regressions
142+
5. ✅ Backward compatibility maintained
143+
6. ✅ Modern JavaScript patterns consistently applied

example/whiteboard/whiteboard.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@
1515
* limitations under the License.
1616
***********************************************************************/
1717

18-
var WebSocketServer = require('../../lib/websocket').server;
19-
var express = require('express');
18+
const WebSocketServer = require('../../lib/websocket').server;
19+
const express = require('express');
2020

21-
var app = express.createServer();
21+
const app = express.createServer();
2222

2323
app.configure(function() {
2424
app.use(express.static(__dirname + "/public"));
@@ -31,22 +31,22 @@ app.get('/', function(req, res) {
3131
app.listen(8080);
3232

3333

34-
var wsServer = new WebSocketServer({
34+
const wsServer = new WebSocketServer({
3535
httpServer: app,
3636

3737
// Firefox 7 alpha has a bug that drops the
3838
// connection on large fragmented messages
3939
fragmentOutgoingMessages: false
4040
});
4141

42-
var connections = [];
43-
var canvasCommands = [];
42+
const connections = [];
43+
const canvasCommands = [];
4444

4545
wsServer.on('request', function(request) {
46-
var connection = request.accept('whiteboard-example', request.origin);
46+
const connection = request.accept('whiteboard-example', request.origin);
4747
connections.push(connection);
4848

49-
console.log(connection.remoteAddress + " connected - Protocol Version " + connection.webSocketVersion);
49+
console.log(`${connection.remoteAddress} connected - Protocol Version ${connection.webSocketVersion}`);
5050

5151
// Send all the existing canvas commands to the new client
5252
connection.sendUTF(JSON.stringify({
@@ -56,9 +56,9 @@ wsServer.on('request', function(request) {
5656

5757
// Handle closed connections
5858
connection.on('close', function() {
59-
console.log(connection.remoteAddress + " disconnected");
59+
console.log(`${connection.remoteAddress} disconnected`);
6060

61-
var index = connections.indexOf(connection);
61+
const index = connections.indexOf(connection);
6262
if (index !== -1) {
6363
// remove the connection from the pool
6464
connections.splice(index, 1);
@@ -69,10 +69,10 @@ wsServer.on('request', function(request) {
6969
connection.on('message', function(message) {
7070
if (message.type === 'utf8') {
7171
try {
72-
var command = JSON.parse(message.utf8Data);
72+
const command = JSON.parse(message.utf8Data);
7373

7474
if (command.msg === 'clear') {
75-
canvasCommands = [];
75+
canvasCommands.length = 0; // Clear array without replacing reference
7676
}
7777
else {
7878
canvasCommands.push(command);

lib/Deprecation.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
* limitations under the License.
1515
***********************************************************************/
1616

17-
var Deprecation = {
17+
const Deprecation = {
1818
disableWarnings: false,
1919

2020
deprecationWarningMap: {
@@ -23,7 +23,7 @@ var Deprecation = {
2323

2424
warn: function(deprecationName) {
2525
if (!this.disableWarnings && this.deprecationWarningMap[deprecationName]) {
26-
console.warn('DEPRECATION WARNING: ' + this.deprecationWarningMap[deprecationName]);
26+
console.warn(`DEPRECATION WARNING: ${this.deprecationWarningMap[deprecationName]}`);
2727
this.deprecationWarningMap[deprecationName] = false;
2828
}
2929
}

lib/W3CWebSocket.js

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@
1414
* limitations under the License.
1515
***********************************************************************/
1616

17-
var WebSocketClient = require('./WebSocketClient');
18-
var toBuffer = require('typedarray-to-buffer');
19-
var yaeti = require('yaeti');
17+
const WebSocketClient = require('./WebSocketClient');
18+
const toBuffer = require('typedarray-to-buffer');
19+
const yaeti = require('yaeti');
2020

2121

2222
const CONNECTING = 0;
@@ -36,7 +36,7 @@ function W3CWebSocket(url, protocols, origin, headers, requestOptions, clientCon
3636
clientConfig = clientConfig || {};
3737
clientConfig.assembleFragments = true; // Required in the W3C API.
3838

39-
var self = this;
39+
const self = this;
4040

4141
this._url = url;
4242
this._readyState = CONNECTING;
@@ -190,7 +190,7 @@ function createMessageEvent(data) {
190190

191191

192192
function onConnect(connection) {
193-
var self = this;
193+
const self = this;
194194

195195
this._readyState = OPEN;
196196
this._connection = connection;
@@ -237,10 +237,10 @@ function onMessage(message) {
237237
// Must convert from Node Buffer to ArrayBuffer.
238238
// TODO: or to a Blob (which does not exist in Node!).
239239
if (this.binaryType === 'arraybuffer') {
240-
var buffer = message.binaryData;
241-
var arraybuffer = new ArrayBuffer(buffer.length);
242-
var view = new Uint8Array(arraybuffer);
243-
for (var i=0, len=buffer.length; i<len; ++i) {
240+
const buffer = message.binaryData;
241+
const arraybuffer = new ArrayBuffer(buffer.length);
242+
const view = new Uint8Array(arraybuffer);
243+
for (let i=0, len=buffer.length; i<len; ++i) {
244244
view[i] = buffer[i];
245245
}
246246
this.dispatchEvent(createMessageEvent(arraybuffer));

lib/WebSocketClient.js

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,25 +14,25 @@
1414
* limitations under the License.
1515
***********************************************************************/
1616

17-
var utils = require('./utils');
18-
var extend = utils.extend;
19-
var util = require('util');
20-
var EventEmitter = require('events').EventEmitter;
21-
var http = require('http');
22-
var https = require('https');
23-
var url = require('url');
24-
var crypto = require('crypto');
25-
var WebSocketConnection = require('./WebSocketConnection');
26-
var bufferAllocUnsafe = utils.bufferAllocUnsafe;
27-
28-
var protocolSeparators = [
17+
const utils = require('./utils');
18+
const extend = utils.extend;
19+
const util = require('util');
20+
const EventEmitter = require('events').EventEmitter;
21+
const http = require('http');
22+
const https = require('https');
23+
const url = require('url');
24+
const crypto = require('crypto');
25+
const WebSocketConnection = require('./WebSocketConnection');
26+
const bufferAllocUnsafe = utils.bufferAllocUnsafe;
27+
28+
const protocolSeparators = [
2929
'(', ')', '<', '>', '@',
3030
',', ';', ':', '\\', '\"',
3131
'/', '[', ']', '?', '=',
3232
'{', '}', ' ', String.fromCharCode(9)
3333
];
3434

35-
var excludedTlsOptions = ['hostname','port','method','path','headers'];
35+
const excludedTlsOptions = ['hostname','port','method','path','headers'];
3636

3737
function WebSocketClient(config) {
3838
// Superclass Constructor
@@ -90,7 +90,7 @@ function WebSocketClient(config) {
9090
};
9191

9292
if (config) {
93-
var tlsOptions;
93+
let tlsOptions;
9494
if (config.tlsOptions) {
9595
tlsOptions = config.tlsOptions;
9696
delete config.tlsOptions;

0 commit comments

Comments
 (0)