-
Notifications
You must be signed in to change notification settings - Fork 0
/
dev.livereload.mjs
62 lines (50 loc) · 1.57 KB
/
dev.livereload.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import { randomUUID } from 'node:crypto';
let clients = new Set();
const CORS_OPTIONS = {
origin: function (origin, callback) {
callback(null, true);
},
credentials: true,
};
export function runLiveReloadServer(liveReloadPort) {
let app = express();
app.use(cors(CORS_OPTIONS));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/status', (request, response) => response.json({ clients: clients.length }));
function eventsHandler(request, response, next) {
let headers = {
'Content-Type': 'text/event-stream',
Connection: 'keep-alive',
'Cache-Control': 'no-cache',
};
response.writeHead(200, headers);
response.flushHeaders();
response.write(`id: ${randomUUID()}\n`);
response.write('event: init \n');
response.write(`data: Started at ${Date.now()} \n\n`);
clients.add(response);
request.on('close', () => {
console.log(`Connection closed`);
clients.delete(response);
});
}
app.get('/', eventsHandler);
app.listen(liveReloadPort, () => {
console.log(`[Running live reload server]`);
console.log(
`Live Reload Events service listening at http://localhost:${liveReloadPort}`,
);
});
}
export function postLiveReloadEvent(update) {
let data = JSON.stringify(update ?? 'no data');
clients.forEach((client) => {
client.write(`id: ${randomUUID()}\n`);
client.write('event: update\n');
client.write(`data: ${data} \n\n`);
});
}