forked from oakserver/oak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
headers.ts
78 lines (72 loc) · 2.28 KB
/
headers.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
// Copyright 2018-2021 the oak authors. All rights reserved. MIT license.
import type { BufReader } from "./buf_reader.ts";
import { httpErrors } from "./httpError.ts";
const COLON = ":".charCodeAt(0);
const HTAB = "\t".charCodeAt(0);
const SPACE = " ".charCodeAt(0);
const decoder = new TextDecoder();
/** With a provided attribute pattern, return a RegExp which will match and
* capture in the first group the value of the attribute from a header value. */
export function toParamRegExp(
attributePattern: string,
flags?: string,
): RegExp {
// deno-fmt-ignore
return new RegExp(
`(?:^|;)\\s*${attributePattern}\\s*=\\s*` +
`(` +
`[^";\\s][^;\\s]*` +
`|` +
`"(?:[^"\\\\]|\\\\"?)+"?` +
`)`,
flags
);
}
/** Asynchronously read the headers out of body request and resolve with them as
* a `Headers` object. */
export async function readHeaders(
body: BufReader,
): Promise<Record<string, string>> {
const headers: Record<string, string> = {};
let readResult = await body.readLine();
while (readResult) {
const { bytes } = readResult;
if (!bytes.length) {
return headers;
}
let i = bytes.indexOf(COLON);
if (i === -1) {
throw new httpErrors.BadRequest(
`Malformed header: ${decoder.decode(bytes)}`,
);
}
const key = decoder.decode(bytes.subarray(0, i)).trim().toLowerCase();
if (key === "") {
throw new httpErrors.BadRequest("Invalid header key.");
}
i++;
while (i < bytes.byteLength && (bytes[i] === SPACE || bytes[i] === HTAB)) {
i++;
}
const value = decoder.decode(bytes.subarray(i)).trim();
headers[key] = value;
readResult = await body.readLine();
}
throw new httpErrors.BadRequest("Unexpected end of body reached.");
}
/** Unquotes attribute values that might be pass as part of a header. */
export function unquote(value: string): string {
if (value.startsWith(`"`)) {
const parts = value.slice(1).split(`\\"`);
for (let i = 0; i < parts.length; ++i) {
const quoteIndex = parts[i].indexOf(`"`);
if (quoteIndex !== -1) {
parts[i] = parts[i].slice(0, quoteIndex);
parts.length = i + 1; // Truncates and stops the loop
}
parts[i] = parts[i].replace(/\\(.)/g, "$1");
}
value = parts.join(`"`);
}
return value;
}