-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
244 lines (201 loc) · 5.27 KB
/
index.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
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'development'
}
var http = require('node:http')
var https = require('node:https')
var fs = require('node:fs')
var path = require('node:path')
var util = require('node:util')
var stream = require('node:stream')
var ws = require('ws')
var mime = require('mime-types')
var smor = require('smor')
var kross = require('kross')
var bparse = require('bparse')
var extras = require('extras')
var wcookie = require('wcookie')
var rekvest = require('rekvest')
var router = require('reqroute')
var lang = require('reqlang')
var root = process.cwd()
function getContentType(pathname, method = 'GET') {
var defaultType = method == 'GET' ? 'html' : 'json'
let [base, ext] = extras.basext(pathname)
if (!ext) ext = defaultType
var fileName = [base, ext].join('.')
var type = mime.lookup(fileName) || 'text/plain'
return mime.contentType(type)
}
// Make asset list
function getAssets(dir) {
if (typeof dir != 'string') return
var assetPath = path.join(root, dir)
var assetList = extras.tree(assetPath).map((x) => x.replace(assetPath, ''))
return new Set(assetList)
}
function isReadableStream(obj) {
return (
obj instanceof stream.Stream &&
typeof (obj._read === 'function') &&
typeof (obj._readableState === 'object')
)
}
function favicon(res) {
res.statusCode = 404
res.end('')
}
function cors(res) {
res.statusCode = 204
res.end('')
}
function setFile(req) {
req.file = req.pathname.slice(1)
if (req.pathname.endsWith('/')) {
req.file += 'index'
}
}
async function log(req) {
var options = { showHidden: true, depth: null, colors: true }
var lines = [
`${req.method}#${req.pathname.slice(1)}`,
util.inspect(req.params || {}, options)
]
console.log(`${lines.join('\n')}\n`)
}
module.exports = function (opt, fn) {
if (typeof opt == 'function') {
opt = {}
fn = opt
}
// Set mode
var mode = process.env.NODE_ENV
// Store assets as a set
var assets = getAssets(opt.dir)
var server = http.createServer(function (req, res) {
// Add request properties
rekvest(req)
// Block favicon requests
if (req.pathname == '/favicon.ico') {
return favicon(res)
}
// Cors
kross(req, res, opt.cors)
if (req.method == 'OPTIONS') {
return cors(res)
}
// Return asset if it exists
if (assets && assets.has(req.pathname)) {
return smor(req, res, { dir: opt.dir })
}
handleRequest(req, res, opt, fn)
})
// Set up web socket for development
if (mode == 'development') {
new ws.Server({ server })
}
server.listen(opt.port || 9090, () => {
var port = server.address().port
console.log(`Listening on port ${port} in ${mode} mode.\n`)
})
return server
}
async function handleRequest(req, res, opt, fn) {
// Routes
if (opt.routes) {
router(req, opt.routes)
}
// Set up cookies
wcookie(req)
// Set up lang
lang(req, opt.lang)
// Set file
setFile(req)
// Set store
req.store = {}
req.redirect = function (location = '/', status = 302) {
res.statusCode = status
res.setHeader('location', location)
req.redirecting = true
}
// Set content type
var defaultContentType = getContentType(req.pathname, req.method)
res.setHeader('content-type', defaultContentType)
// Pipe local or remote file to response
res.stream = function (file, contentType) {
if (!contentType) {
contentType = getContentType(file, req.method)
}
res.setHeader('content-type', contentType)
if (/^https?:\/\//.test(file)) {
var client = file.startsWith('https') ? https : http
return new Promise(function (resolve) {
client.get(file, function (response) {
resolve(response)
})
})
}
return fs.createReadStream(file)
}
// Download streamed file
res.download = function (file) {
var filename = file.split('/').reverse()[0]
res.setHeader('content-disposition', `attachment; filename="${filename}"`)
return res.stream(file)
}
let result
// Run middleware
if (opt.middleware) {
for (var m in opt.middleware) {
var mw = opt.middleware[m]
if (typeof mw == 'function') {
result = await mw(req, res)
if (typeof result != 'undefined') {
break
}
}
}
}
// Run main function
if (typeof result == 'undefined') {
if (req.method == 'POST') {
await bparse(req)
extras.transform(req.params)
}
log(req)
result = await fn(req, res)
}
// Write cookies
if (req.cookieJar && req.cookieJar.length) {
res.setHeader('set-cookie', req.cookieJar.headers)
}
if (req.redirecting) {
return res.end('')
}
handleResult(req, res, result)
}
function handleResult(req, res, result) {
if (req.method == 'HEAD') {
result = ''
}
if (isReadableStream(result)) {
return result.pipe(res)
}
// Undefined and null returns empty string and 404
if (result == null) {
res.statusCode = 404
result = req.method == 'POST' ? '{}' : ''
}
// Stringify objects
if (typeof result == 'object') {
try {
result = JSON.stringify(result)
} catch (e) {
result = '{}'
}
}
// Make sure it's a string
result = String(result)
// Set content length
res.setHeader('content-length', Buffer.byteLength(result))
res.end(result)
}