Open History to see the last commit
1import type { IncomingMessage, ServerResponse } from 'node:http'
2
3export async function readRawBody(req: IncomingMessage): Promise<Uint8Array> {
4 const chunks: Array<Uint8Array> = []
5 let total = 0
6 for await (const chunk of req) {
7 const bytes =
8 typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk
9 total += bytes.byteLength
10 chunks.push(bytes)
11 }
12 const out = new Uint8Array(total)
13 let offset = 0
14 for (const chunk of chunks) {
15 out.set(chunk, offset)
16 offset += chunk.byteLength
17 }
18 return out
19}
20
21export function toWebRequest(
22 req: IncomingMessage,
23 rawBody: Uint8Array,
24): Request {
25 const host = req.headers.host ?? '127.0.0.1'
26 const url = `http://${host}${req.url ?? '/'}`
27 const headers = new Headers()
28 for (const [key, value] of Object.entries(req.headers)) {
29 if (value === undefined) continue
30 if (Array.isArray(value)) {
31 for (const item of value) headers.append(key, item)
32 } else {
33 headers.set(key, value)
34 }
35 }
36 const method = req.method ?? 'GET'
37 return new Request(url, {
38 method,
39 headers,
40 body:
41 method === 'GET' || method === 'HEAD' ? undefined : (rawBody as BodyInit),
42 })
43}
44
45export async function sendWebResponse(
46 res: ServerResponse,
47 response: Response,
48): Promise<void> {
49 res.statusCode = response.status
50 response.headers.forEach((value, key) => {
51 res.setHeader(key, value)
52 })
53 const buf = new Uint8Array(await response.arrayBuffer())
54 res.end(buf)
55}