-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
send.ts
78 lines (67 loc) · 1.62 KB
/
send.ts
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
import type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from 'http'
import getEtag from 'etag'
import type { SourceMap } from 'rollup'
const isDebug = process.env.DEBUG
const alias: Record<string, string | undefined> = {
js: 'application/javascript',
css: 'text/css',
html: 'text/html',
json: 'application/json'
}
export interface SendOptions {
etag?: string
cacheControl?: string
headers?: OutgoingHttpHeaders
map?: SourceMap | null
}
export function send(
req: IncomingMessage,
res: ServerResponse,
content: string | Buffer,
type: string,
options: SendOptions
): void {
const {
etag = getEtag(content, { weak: true }),
cacheControl = 'no-cache',
headers,
map
} = options
if (res.writableEnded) {
return
}
if (req.headers['if-none-match'] === etag) {
res.statusCode = 304
res.end()
return
}
res.setHeader('Content-Type', alias[type] || type)
res.setHeader('Cache-Control', cacheControl)
res.setHeader('Etag', etag)
if (headers) {
for (const name in headers) {
res.setHeader(name, headers[name]!)
}
}
// inject source map reference
if (map && map.mappings) {
if (isDebug) {
content += `\n/*${JSON.stringify(map, null, 2).replace(
/\*\//g,
'*\\/'
)}*/\n`
}
content += genSourceMapString(map)
}
res.statusCode = 200
res.end(content)
return
}
function genSourceMapString(map: SourceMap | string | undefined) {
if (typeof map !== 'string') {
map = JSON.stringify(map)
}
return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(
map
).toString('base64')}`
}