-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
195 lines (166 loc) · 5.36 KB
/
index.js
File metadata and controls
195 lines (166 loc) · 5.36 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//@ts-check
const https = require('node:https')
const http = require('node:http')
const fs = require('node:fs')
const path = require('node:path')
const fsPromises = fs.promises
const location = process.argv[1]
const isDev = (process.argv[2] === '--dev')
if(process.argv[2] !== undefined && !isDev) {
console.error('process.argv[2] is defined and it is not "--dev"')
process.exit(1)
}
let myPath
if(fs.lstatSync(location).isDirectory()) {
myPath = location
} else {
myPath = path.dirname(location)
}
myPath += path.sep
/**
* @param {http.IncomingMessage} request
* @returns {Promise<string>}
*/
const getPayloadString = function(request) {
return new Promise((resolve) => {
let body = ''
request.on('data', (chunk) => {
body += chunk
}).on('end', () => {
resolve(body)
})
})
}
/**
* @param {Parameters<import("./index.d.ts")>[0]} options
*/
module.exports = function ({
publicDir,
port,
hostname,
routes,
httpsOptions,
}) {
publicDir = path.resolve(myPath, publicDir)
hostname ??= 'localhost'
routes ??= {}
httpsOptions ??= {key: '', cert: ''}
let /** @type {https} */ protocol
const options = {}
if(httpsOptions.key && httpsOptions.cert) {
options.key = fs.readFileSync(path.resolve(myPath, httpsOptions.key))
options.cert = fs.readFileSync(path.resolve(myPath, httpsOptions.cert))
protocol = https
} else {
// @ts-expect-error
protocol = http
}
const cache = {}
if (!isDev) {
const cacheFilesRecursively = function(dir, baseUrl = '') {
const entries = fs.readdirSync(dir, { withFileTypes: true })
for (const entry of entries) {
const entryPath = path.join(dir, entry.name)
const entryUrl = path.posix.join(baseUrl, entry.name)
if (entry.isDirectory()) {
cacheFilesRecursively(entryPath, entryUrl)
} else if (entry.isFile()) {
cache[`/${entryUrl}`] = fs.readFileSync(entryPath)
}
}
}
try {
cacheFilesRecursively(publicDir)
} catch(_) {}
}
const server = protocol.createServer(options, async (req, res) => {
if (req.url === undefined) throw new Error("req.url is undefined")
req.url = req.url.split('?')[0]
if(req.url in routes) {
const route = routes[req.url]
if (typeof route === 'string') {
res.writeHead(302, {
location: route
})
res.end()
return
}
let result
try {
const payloadString = await getPayloadString(req)
let requestPayload
if (payloadString !== "") {
requestPayload = JSON.parse(payloadString)
}
result = await route(requestPayload)
} catch(_) {
res.writeHead(500)
res.end("Internal server error")
return
}
if (typeof result === 'string') {
res.end(result)
return
}
res.writeHead(500)
res.end("Internal server error")
return
}
if(req.url.endsWith('.js') || req.url.endsWith('.mjs')) {
res.setHeader('content-type', 'text/javascript')
}
if(req.url.endsWith('.wasm')) {
res.setHeader('content-type', 'application/wasm')
}
if (!isDev) {
if (cache[req.url]) {
res.end(cache[req.url])
return
}
if (req.url.includes('.')) {
res.writeHead(404)
res.end("404 Not Found")
return
}
const urlWithoutIndex = path.posix.join(req.url, 'index.html')
if (cache[urlWithoutIndex]) {
res.end(cache[urlWithoutIndex])
return
}
res.writeHead(404)
res.end("404 Not Found")
return
}
fsPromises.readFile(path.resolve(publicDir, req.url.substring(1)))
.then((buffer) => {
res.end(buffer)
})
.catch((_) => {
if (req.url === undefined) throw new Error("req.url is undefined")
if (req.url.includes('.')) {
res.writeHead(404)
res.end("404 Not Found")
return
}
fsPromises.readFile(path.resolve(publicDir, req.url.substring(1), 'index.html'))
.then((buffer) => {
res.end(buffer)
})
.catch((_) => {
res.writeHead(404)
res.end("404 Not Found")
return
})
})
})
server.listen(port, hostname, () => {
const address = server.address()
if (address === null) {
throw new Error("server.address() is null")
}
if (typeof address === 'string') {
throw new Error("server.address() is a string, which is not expected")
}
console.log(`Listening on ${hostname}:${address.port}`)
})
}