-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
server.cjs
100 lines (86 loc) · 2.41 KB
/
server.cjs
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
const http = require('http');
const fs = require('fs');
const path = require('path');
const { once } = require('events');
const { pathToFileURL, fileURLToPath } = require('url');
const open = require('open');
const port = 8080;
const systemJSURL = pathToFileURL(path.resolve(__dirname, '..') + '/');
const mimes = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.mjs': 'application/javascript',
'.json': 'application/json',
'.wasm': 'application/wasm'
};
const shouldExit = process.env.WATCH_MODE !== 'true'
let failTimeout, browserTimeout;
function setBrowserTimeout () {
if (!shouldExit)
return;
if (browserTimeout)
clearTimeout(browserTimeout);
browserTimeout = setTimeout(() => {
console.log('No browser requests made to server for 10s, closing.');
process.exit(0);
}, 10000);
}
setBrowserTimeout();
http.createServer(async function (req, res) {
setBrowserTimeout();
if (req.url === '/done') {
console.log('Tests completed successfully.');
if (shouldExit) {
process.exit();
}
return;
}
else if (req.url === '/error') {
console.log('\033[31mTest failures found.\033[0m');
if (shouldExit) {
failTimeout = setTimeout(() => process.exit(1), 30000);
}
}
else if (failTimeout) {
clearTimeout(failTimeout);
failTimeout = null;
}
const url = new URL(req.url[0] === '/' ? req.url.slice(1) : req.url, systemJSURL);
const filePath = fileURLToPath(url);
// redirect to test/test.html file by default
if (url.href === systemJSURL.href) {
res.writeHead(301, {
'location': '/test/test.html'
});
res.end();
return;
}
const fileStream = fs.createReadStream(filePath);
try {
await once(fileStream, 'readable');
}
catch (e) {
if (e.code === 'EISDIR' || e.code === 'ENOENT') {
res.writeHead(404, {
'content-type': 'text/html'
});
res.end(`File not found.`);
}
return;
}
let mime;
if (filePath.endsWith('javascript.css'))
mime = 'application/javascript';
else
mime = mimes[path.extname(filePath)] || 'text/plain';
res.writeHead(200, {
'content-type': mime
});
fileStream.pipe(res);
await once(fileStream, 'end');
res.end();
}).listen(port);
console.log(`Test server listening on http://localhost:${port}\n`);
const openOptions = process.env.CI ? { app: ['firefox'] } : {};
open(`http://localhost:${port}/test/test.html`, openOptions);