-
Notifications
You must be signed in to change notification settings - Fork 11
/
Headers.ts
195 lines (166 loc) · 5.33 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
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
import { splitCookiesString } from 'set-cookie-parser'
import { HeadersList, HeadersObject } from './glossary'
import { normalizeHeaderName } from './utils/normalizeHeaderName'
import { normalizeHeaderValue } from './utils/normalizeHeaderValue'
import { isValidHeaderName } from './utils/isValidHeaderName'
import { isValidHeaderValue } from './utils/isValidHeaderValue'
export const NORMALIZED_HEADERS: unique symbol = Symbol('normalizedHeaders')
export const RAW_HEADER_NAMES: unique symbol = Symbol('rawHeaderNames')
const HEADER_VALUE_DELIMITER = ', ' as const
export class Headers {
// Normalized header {"name":"a, b"} storage.
private [NORMALIZED_HEADERS]: Record<string, string> = {}
// Keeps the mapping between the raw header name
// and the normalized header name to ease the lookup.
private [RAW_HEADER_NAMES]: Map<string, string> = new Map()
constructor(init?: HeadersInit | HeadersObject | HeadersList) {
/**
* @note Cannot necessarily check if the `init` is an instance of the
* `Headers` because that class may not be defined in Node or jsdom.
*/
if (
['Headers', 'HeadersPolyfill'].includes(init?.constructor.name) ||
init instanceof Headers ||
(typeof globalThis.Headers !== 'undefined' && init instanceof globalThis.Headers)
) {
const initialHeaders = init as Headers
initialHeaders.forEach((value, name) => {
this.append(name, value)
}, this)
} else if (Array.isArray(init)) {
init.forEach(([name, value]) => {
this.append(
name,
Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value
)
})
} else if (init) {
Object.getOwnPropertyNames(init).forEach((name) => {
const value = init[name]
this.append(
name,
Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value
)
})
}
}
[Symbol.iterator]() {
return this.entries()
}
*keys(): IterableIterator<string> {
for (const [name] of this.entries()) {
yield name
}
}
*values(): IterableIterator<string> {
for (const [, value] of this.entries()) {
yield value
}
}
*entries(): IterableIterator<[string, string]> {
// https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
let sortedKeys = Object.keys(this[NORMALIZED_HEADERS]).sort((a, b) =>
a.localeCompare(b)
)
for (const name of sortedKeys) {
if (name === 'set-cookie') {
for (const value of this.getSetCookie()) {
yield [name, value]
}
} else {
yield [name, this.get(name)]
}
}
}
/**
* Returns a boolean stating whether a `Headers` object contains a certain header.
*/
has(name: string): boolean {
if (!isValidHeaderName(name)) {
throw new TypeError(`Invalid header name "${name}"`)
}
return this[NORMALIZED_HEADERS].hasOwnProperty(normalizeHeaderName(name))
}
/**
* Returns a `ByteString` sequence of all the values of a header with a given name.
*/
get(name: string): string | null {
if (!isValidHeaderName(name)) {
throw TypeError(`Invalid header name "${name}"`)
}
return this[NORMALIZED_HEADERS][normalizeHeaderName(name)] ?? null
}
/**
* Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist.
*/
set(name: string, value: string): void {
if (!isValidHeaderName(name) || !isValidHeaderValue(value)) {
return
}
const normalizedName = normalizeHeaderName(name)
const normalizedValue = normalizeHeaderValue(value)
this[NORMALIZED_HEADERS][normalizedName] =
normalizeHeaderValue(normalizedValue)
this[RAW_HEADER_NAMES].set(normalizedName, name)
}
/**
* Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist.
*/
append(name: string, value: string): void {
if (!isValidHeaderName(name) || !isValidHeaderValue(value)) {
return
}
const normalizedName = normalizeHeaderName(name)
const normalizedValue = normalizeHeaderValue(value)
let resolvedValue = this.has(normalizedName)
? `${this.get(normalizedName)}, ${normalizedValue}`
: normalizedValue
this.set(name, resolvedValue)
}
/**
* Deletes a header from the `Headers` object.
*/
delete(name: string): void {
if (!isValidHeaderName(name)) {
return
}
if (!this.has(name)) {
return
}
const normalizedName = normalizeHeaderName(name)
delete this[NORMALIZED_HEADERS][normalizedName]
this[RAW_HEADER_NAMES].delete(normalizedName)
}
/**
* Traverses the `Headers` object,
* calling the given callback for each header.
*/
forEach<ThisArg = this>(
callback: (
this: ThisArg,
value: string,
name: string,
parent: this
) => void,
thisArg?: ThisArg
) {
for (const [name, value] of this.entries()) {
callback.call(thisArg, value, name, this)
}
}
/**
* Returns an array containing the values
* of all Set-Cookie headers associated
* with a response
*/
getSetCookie(): string[] {
const setCookieHeader = this.get('set-cookie')
if (setCookieHeader === null) {
return []
}
if (setCookieHeader === '') {
return ['']
}
return splitCookiesString(setCookieHeader)
}
}