`);
},
'/htmx.js': async (req, res) => {
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.end(await fs.readFile('src/htmx.js'));
},
'/ext/hx-stream.js': async (req, res) => {
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.end(await fs.readFile('src/ext/hx-stream.js'));
},
// Simulates an LLM streaming plain text word-by-word
'/ai-response': (req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
let words = `The key insight behind hypermedia-driven applications is that the server sends HTML, not JSON. This means the server controls the presentation layer, and the client simply renders what it receives. This approach dramatically simplifies the client-side code, eliminates an entire class of state synchronization bugs, and lets you build rich interactive applications with remarkably little JavaScript.`.split(' ');
let i = 0;
let interval = setInterval(() => {
if (i < words.length) {
res.write((i > 0 ? ' ' : '') + words[i]);
i++;
} else {
clearInterval(interval);
res.end();
}
}, 50);
req.on('close', () => clearInterval(interval));
},
// Streams complete HTML fragments
'/html-stream': (req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
let items = [
'
Step 1: Connecting to server...
',
'
Step 2: Authenticating...
',
'
Step 3: Fetching data...
',
'
Step 4: Processing results...
',
'
Done! All steps completed.
'
];
let i = 0;
let interval = setInterval(() => {
if (i < items.length) {
res.write(items[i]);
i++;
} else {
clearInterval(interval);
res.end();
}
}, 500);
req.on('close', () => clearInterval(interval));
}
};
http.createServer(async (req, res) => {
let pathname = new URL(req.url, 'http://localhost').pathname;
let handler = routes[pathname];
if (handler) {
try { await handler(req, res); }
catch (e) { if (!res.headersSent) { res.writeHead(500); res.end('Error'); } }
} else {
res.writeHead(404); res.end('Not Found');
}
}).listen(3002, () => console.log('http://localhost:3002'));