-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
56 lines (49 loc) · 1.49 KB
/
index.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
import type { IncomingMessage, ServerResponse } from "node:http";
interface ClearSiteDataOptions {
directives?: string[];
}
function getHeaderValueFromOptions({
directives = ["*"],
}: Readonly<ClearSiteDataOptions>): string {
const VALID_TYPES = new Set([
"cache",
"cookies",
"storage",
"executionContexts",
"*",
]);
if (!Array.isArray(directives)) {
throw new Error("Clear-Site-Data directives must be an array.");
} else if (directives.length === 0) {
throw new Error("Clear-Site-Data directives cannot be an empty array.");
}
const directivesSet = new Set(directives);
if (directivesSet.size !== directives.length) {
throw new Error("Clear-Site-Data directives cannot contain duplicates.");
} else if (directivesSet.has("*") && directives.length > 1) {
throw new Error(
'Clear-Site-Data cannot contain "*" and other directives. Remove the other directives or "*".',
);
}
return directives
.map((directive) => {
if (!VALID_TYPES.has(directive)) {
throw new Error(
`${directive} is not a valid Clear-Site-Data directive.`,
);
}
return `"${directive}"`;
})
.join(",");
}
export = function clearSiteData(options: Readonly<ClearSiteDataOptions> = {}) {
const headerValue = getHeaderValueFromOptions(options);
return function clearSiteData(
_req: IncomingMessage,
res: ServerResponse,
next: () => void,
) {
res.setHeader("Clear-Site-Data", headerValue);
next();
};
};