2023-07-17 19:17:59 -05:00
|
|
|
import type { OutgoingHttpHeaders } from 'node:http';
|
2023-06-06 10:09:16 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Takes in a nullable WebAPI Headers object and produces a NodeJS OutgoingHttpHeaders object suitable for usage
|
|
|
|
* with ServerResponse.writeHead(..) or ServerResponse.setHeader(..)
|
2023-06-06 10:11:47 -05:00
|
|
|
*
|
2023-06-06 10:09:16 -05:00
|
|
|
* @param webHeaders WebAPI Headers object
|
|
|
|
* @returns NodeJS OutgoingHttpHeaders object with multiple set-cookie handled as an array of values
|
|
|
|
*/
|
2023-06-06 10:11:47 -05:00
|
|
|
export const createOutgoingHttpHeaders = (
|
|
|
|
webHeaders: Headers | undefined | null
|
|
|
|
): OutgoingHttpHeaders | undefined => {
|
|
|
|
if (!webHeaders) {
|
|
|
|
return undefined;
|
|
|
|
}
|
2023-06-06 10:09:16 -05:00
|
|
|
|
2023-06-06 10:11:47 -05:00
|
|
|
// re-type to access Header.getSetCookie()
|
|
|
|
const headers = webHeaders as HeadersWithGetSetCookie;
|
2023-06-06 10:09:16 -05:00
|
|
|
|
2023-06-06 10:11:47 -05:00
|
|
|
// at this point, a multi-value'd set-cookie header is invalid (it was concatenated as a single CSV, which is not valid for set-cookie)
|
|
|
|
const nodeHeaders: OutgoingHttpHeaders = Object.fromEntries(headers.entries());
|
2023-06-06 10:09:16 -05:00
|
|
|
|
2023-06-06 10:11:47 -05:00
|
|
|
if (Object.keys(nodeHeaders).length === 0) {
|
|
|
|
return undefined;
|
|
|
|
}
|
2023-06-06 10:09:16 -05:00
|
|
|
|
2023-06-06 10:11:47 -05:00
|
|
|
// if there is > 1 set-cookie header, we have to fix it to be an array of values
|
|
|
|
if (headers.has('set-cookie')) {
|
|
|
|
const cookieHeaders = headers.getSetCookie();
|
|
|
|
if (cookieHeaders.length > 1) {
|
|
|
|
// the Headers.entries() API already normalized all header names to lower case so we can safely index this as 'set-cookie'
|
|
|
|
nodeHeaders['set-cookie'] = cookieHeaders;
|
|
|
|
}
|
|
|
|
}
|
2023-06-06 10:09:16 -05:00
|
|
|
|
2023-06-06 10:11:47 -05:00
|
|
|
return nodeHeaders;
|
2023-06-06 10:09:16 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
interface HeadersWithGetSetCookie extends Headers {
|
2023-06-06 10:11:47 -05:00
|
|
|
// the @astrojs/webapi polyfill makes this available (as of undici@5.19.0), but tsc doesn't pick it up on the built-in Headers type from DOM lib
|
|
|
|
getSetCookie(): string[];
|
2023-06-06 10:09:16 -05:00
|
|
|
}
|