-
Notifications
You must be signed in to change notification settings - Fork 12
/
wasm-server.js
109 lines (93 loc) · 2.35 KB
/
wasm-server.js
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
102
103
104
105
106
107
108
109
const http = require('http');
const fs = require('fs');
const path = require('path');
function renderFileLink(p, name) {
return `<li><a href="${path.join(p, name)}">${name}</a></li>`;
}
function isDirectory(p) {
try {
return fs.statSync(p).isDirectory();
} catch (e) {
return false;
}
}
const port = parseInt(process.argv[2], 10) || 3042;
const host = process.argv[3] || '127.0.0.1';
const proxy = http.createServer((req, res) => {
let p = path.join('.', req.url);
console.log(p);
if (p.startsWith('prism-assets')) {
p = path.join(__dirname, 'build', path.basename(p));
}
if (p.startsWith('prism-ruby/bindings')) {
p = path.join(__dirname, 'bindings', path.basename(p));
}
if (p.startsWith('prism-ruby')) {
p = path.join(__dirname, 'src', 'rb', path.basename(p));
}
if (isDirectory(p)) {
const files = fs.readdirSync(p);
res.write(`
<!DOCTYPE html>
<html lang=en-us>
<head>
<meta charset=utf-8>
<meta content="text/html; charset=utf-8" http-equiv=Content-Type>
<title>Prism Server</title>
<style>
html, body {
font-family: sans-serif;
}
</style>
</head>
<body>
<h1>Prism Dev Server</h1>
<h2>${path.join(process.cwd(), p)}</h2>
<ul>
${files.map(f => renderFileLink(req.url, f)).join("\n")}
</ul>
</body>
</html>
`);
res.end();
return;
}
try {
if (p.endsWith('.wasm')) {
res.setHeader("Content-Type", "application/wasm")
}
if (p.endsWith('.js')) {
res.setHeader("Content-Type", "text/javascript")
}
if (p.endsWith('.rb') && req.headers.accept.includes("text/html")) {
res.write(`
<!DOCTYPE html>
<html lang=en-us>
<head>
<meta charset=utf-8>
<meta content="text/html; charset=utf-8" http-equiv=Content-Type>
</head>
<body>
<div id="root"></div>
</body>
<script type="text/javascript" src="/prism-assets/prism.js"></script>
<script type="text/javascript" async src="/prism-assets/bundle.js"></script>
<script type="text/javascript">
Prism.run(document.getElementById("root"), "/${p}");
</script>
</html>
`);
res.end();
return;
}
if (p.endsWith('rb')) {
res.setHeader('Content-Type', "application/ruby");
}
res.write(fs.readFileSync(p));
} catch (e) {
res.write(e.toString());
}
res.end();
});
console.log(`Listening on ${host}:${port}`);
proxy.listen(port, host);