Review this AI-generated browser chat helper against its stated task.
Use an existing secure session and an authentication message to join one authorized room, publish only after a join acknowledgement, render text safely, and keep pending work bounded.
JavaScript
export function createChat(roomId, token) {
let socket; const pending = [];
function open() {
socket = new WebSocket(`wss://chat.example/ws?token=${token}`);
socket.addEventListener('open', () => {
socket.send(JSON.stringify({ type: 'join', roomId }));
for (const data of pending) socket.send(data);
});
socket.addEventListener('message', ({ data }) => {
const message = JSON.parse(data);
const item = document.createElement('p');
item.textContent = message.text;
document.querySelector('#feed').append(item);
});
}
open();
return {
send(text) {
const data = JSON.stringify({ type: 'publish', roomId, text });
if (socket.readyState === WebSocket.OPEN) socket.send(data);
else pending.push(data);
},
close() { socket.close(1000, 'done'); },
}; }
generated code is illustrative, not from any one model