forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreload.js
More file actions
101 lines (90 loc) · 2.52 KB
/
Copy pathreload.js
File metadata and controls
101 lines (90 loc) · 2.52 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const WebSocket = require('ws');
const {log} = require('./utils');
const PORT = 8890;
const WAIT_FOR_CONNECTION = 2000;
/** @type {import('ws').Server} */
let server = null;
/** @type {Set<WebSocket>} */
const sockets = new Set();
const times = new WeakMap();
/**
* @returns {Promise<import('ws').Server>}
*/
function createServer() {
return new Promise((resolve) => {
const server = new WebSocket.Server({port: PORT});
server.on('listening', () => {
log.ok('Auto-reloader started');
resolve(server);
});
server.on('connection', async (ws) => {
sockets.add(ws);
times.set(ws, Date.now());
ws.on('message', async (data) => {
const message = JSON.parse(data);
if (message.type === 'reloading') {
log.ok('Extension reloading...');
}
});
ws.on('close', () => sockets.delete(ws));
if (connectionAwaiter != null) {
connectionAwaiter();
}
});
});
}
function closeServer() {
server && server.close(() => log.ok('Auto-reloader exit'));
sockets.forEach((ws) => ws.close());
sockets.clear();
server = null;
}
process.on('exit', closeServer);
process.on('SIGINT', closeServer);
/** @type {() => void} */
let connectionAwaiter = null;
function waitForConnection() {
return new Promise((resolve) => {
connectionAwaiter = () => {
connectionAwaiter = null;
clearTimeout(timeoutId);
setTimeout(resolve, WAIT_FOR_CONNECTION);
};
const timeoutId = setTimeout(() => {
log.warn('Auto-reloader did not connect');
connectionAwaiter = null;
resolve();
}, WAIT_FOR_CONNECTION);
});
}
/**
* @param {WebSocket} ws
* @param {any} message
*/
function send(ws, message) {
ws.send(JSON.stringify(message));
}
/**
* @param {Object} options
* @param {string} options.type
*/
async function reload({type}) {
if (!server) {
server = await createServer();
}
if (sockets.size === 0) {
await waitForConnection();
}
const now = Date.now();
Array.from(sockets.values())
.filter((ws) => {
const created = times.get(ws);
return created < now;
})
.forEach((ws) => send(ws, {type}));
}
module.exports = reload;
module.exports.PORT = PORT;
module.exports.CSS = 'reload:css';
module.exports.FULL = 'reload:full';
module.exports.UI = 'reload:ui';