Unverified Commit 10b82baf authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Rename header conversion functions (#50389)

To prevent confusion with`IncomingHttpHeaders`, this renames the functions used to convert back and forth between `OutgoingHttpHeaders` and `Headers`:

- Rename `fromNodeHeaders` to `fromNodeOutgoingHttpHeaders`
- Rename `toNodeHeaders` to `toNodeOutgoingHttpHeaders`
parent 466d199d
...@@ -43,7 +43,7 @@ import { NEXT_DYNAMIC_NO_SSR_CODE } from '../shared/lib/lazy-dynamic/no-ssr-erro ...@@ -43,7 +43,7 @@ import { NEXT_DYNAMIC_NO_SSR_CODE } from '../shared/lib/lazy-dynamic/no-ssr-erro
import { createRequestResponseMocks } from '../server/lib/mock-request' import { createRequestResponseMocks } from '../server/lib/mock-request'
import { NodeNextRequest } from '../server/base-http/node' import { NodeNextRequest } from '../server/base-http/node'
import { isAppRouteRoute } from '../lib/is-app-route-route' import { isAppRouteRoute } from '../lib/is-app-route-route'
import { toNodeHeaders } from '../server/web/utils' import { toNodeOutgoingHttpHeaders } from '../server/web/utils'
import { RouteModuleLoader } from '../server/future/helpers/module-loader/route-module-loader' import { RouteModuleLoader } from '../server/future/helpers/module-loader/route-module-loader'
import { NextRequestAdapter } from '../server/web/spec-extension/adapters/next-request' import { NextRequestAdapter } from '../server/web/spec-extension/adapters/next-request'
import * as ciEnvironment from '../telemetry/ci-info' import * as ciEnvironment from '../telemetry/ci-info'
...@@ -445,7 +445,7 @@ export default async function exportPage({ ...@@ -445,7 +445,7 @@ export default async function exportPage({
context.staticGenerationContext.store?.revalidate || false context.staticGenerationContext.store?.revalidate || false
results.fromBuildExportRevalidate = revalidate results.fromBuildExportRevalidate = revalidate
const headers = toNodeHeaders(response.headers) const headers = toNodeOutgoingHttpHeaders(response.headers)
const cacheTags = (context.staticGenerationContext as any) const cacheTags = (context.staticGenerationContext as any)
.fetchTags .fetchTags
......
import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http' import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http'
import { toNodeHeaders } from '../web/utils' import { toNodeOutgoingHttpHeaders } from '../web/utils'
import { BaseNextRequest, BaseNextResponse } from './index' import { BaseNextRequest, BaseNextResponse } from './index'
...@@ -81,7 +81,7 @@ export class WebNextResponse extends BaseNextResponse<WritableStream> { ...@@ -81,7 +81,7 @@ export class WebNextResponse extends BaseNextResponse<WritableStream> {
} }
getHeaders(): OutgoingHttpHeaders { getHeaders(): OutgoingHttpHeaders {
return toNodeHeaders(this.headers) return toNodeOutgoingHttpHeaders(this.headers)
} }
hasHeader(name: string): boolean { hasHeader(name: string): boolean {
......
...@@ -100,7 +100,10 @@ import { I18NProvider } from './future/helpers/i18n-provider' ...@@ -100,7 +100,10 @@ import { I18NProvider } from './future/helpers/i18n-provider'
import { sendResponse } from './send-response' import { sendResponse } from './send-response'
import { RouteKind } from './future/route-kind' import { RouteKind } from './future/route-kind'
import { handleInternalServerErrorResponse } from './future/route-modules/helpers/response-handlers' import { handleInternalServerErrorResponse } from './future/route-modules/helpers/response-handlers'
import { fromNodeHeaders, toNodeHeaders } from './web/utils' import {
fromNodeOutgoingHttpHeaders,
toNodeOutgoingHttpHeaders,
} from './web/utils'
import { NEXT_QUERY_PARAM_PREFIX } from '../lib/constants' import { NEXT_QUERY_PARAM_PREFIX } from '../lib/constants'
export type FindComponentsResult = { export type FindComponentsResult = {
...@@ -1626,7 +1629,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1626,7 +1629,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const blob = await response.blob() const blob = await response.blob()
// Copy the headers from the response. // Copy the headers from the response.
const headers = toNodeHeaders(response.headers) const headers = toNodeOutgoingHttpHeaders(response.headers)
if (cacheTags) { if (cacheTags) {
headers['x-next-cache-tags'] = cacheTags headers['x-next-cache-tags'] = cacheTags
...@@ -2024,7 +2027,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2024,7 +2027,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
req, req,
res, res,
new Response(cachedData.body, { new Response(cachedData.body, {
headers: fromNodeHeaders(headers), headers: fromNodeOutgoingHttpHeaders(headers),
status: cachedData.status || 200, status: cachedData.status || 200,
}) })
) )
......
...@@ -9,7 +9,7 @@ import type { Socket } from 'net' ...@@ -9,7 +9,7 @@ import type { Socket } from 'net'
import type { TLSSocket } from 'tls' import type { TLSSocket } from 'tls'
import Stream from 'stream' import Stream from 'stream'
import { toNodeHeaders } from '../web/utils' import { toNodeOutgoingHttpHeaders } from '../web/utils'
interface MockedRequestOptions { interface MockedRequestOptions {
url: string url: string
...@@ -240,7 +240,7 @@ export class MockedResponse extends Stream.Writable implements ServerResponse { ...@@ -240,7 +240,7 @@ export class MockedResponse extends Stream.Writable implements ServerResponse {
} }
public getHeaders(): OutgoingHttpHeaders { public getHeaders(): OutgoingHttpHeaders {
return toNodeHeaders(this.headers) return toNodeOutgoingHttpHeaders(this.headers)
} }
public getHeaderNames(): string[] { public getHeaderNames(): string[] {
......
...@@ -78,7 +78,7 @@ import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' ...@@ -78,7 +78,7 @@ import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { loadComponents } from './load-components' import { loadComponents } from './load-components'
import isError, { getProperError } from '../lib/is-error' import isError, { getProperError } from '../lib/is-error'
import { FontManifest } from './font-utils' import { FontManifest } from './font-utils'
import { splitCookiesString, toNodeHeaders } from './web/utils' import { splitCookiesString, toNodeOutgoingHttpHeaders } from './web/utils'
import { relativizeURL } from '../shared/lib/router/utils/relativize-url' import { relativizeURL } from '../shared/lib/router/utils/relativize-url'
import { prepareDestination } from '../shared/lib/router/utils/prepare-destination' import { prepareDestination } from '../shared/lib/router/utils/prepare-destination'
import { getMiddlewareRouteMatcher } from '../shared/lib/router/utils/middleware-route-matcher' import { getMiddlewareRouteMatcher } from '../shared/lib/router/utils/middleware-route-matcher'
...@@ -2496,7 +2496,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -2496,7 +2496,7 @@ export default class NextNodeServer extends BaseServer {
if (isMiddlewareInvoke && 'response' in result) { if (isMiddlewareInvoke && 'response' in result) {
for (const [key, value] of Object.entries( for (const [key, value] of Object.entries(
toNodeHeaders(result.response.headers) toNodeOutgoingHttpHeaders(result.response.headers)
)) { )) {
if (key !== 'content-encoding' && value !== undefined) { if (key !== 'content-encoding' && value !== undefined) {
res.setHeader(key, value as string | string[]) res.setHeader(key, value as string | string[])
...@@ -2590,7 +2590,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -2590,7 +2590,7 @@ export default class NextNodeServer extends BaseServer {
result.response.headers.delete('x-middleware-next') result.response.headers.delete('x-middleware-next')
for (const [key, value] of Object.entries( for (const [key, value] of Object.entries(
toNodeHeaders(result.response.headers) toNodeOutgoingHttpHeaders(result.response.headers)
)) { )) {
if ( if (
[ [
......
import type { NextMiddleware, RequestData, FetchEventResult } from './types' import type { NextMiddleware, RequestData, FetchEventResult } from './types'
import type { RequestInit } from './spec-extension/request' import type { RequestInit } from './spec-extension/request'
import { PageSignatureError } from './error' import { PageSignatureError } from './error'
import { fromNodeHeaders } from './utils' import { fromNodeOutgoingHttpHeaders } from './utils'
import { NextFetchEvent } from './spec-extension/fetch-event' import { NextFetchEvent } from './spec-extension/fetch-event'
import { NextRequest } from './spec-extension/request' import { NextRequest } from './spec-extension/request'
import { NextResponse } from './spec-extension/response' import { NextResponse } from './spec-extension/response'
...@@ -127,7 +127,7 @@ export async function adapter( ...@@ -127,7 +127,7 @@ export async function adapter(
requestUrl.pathname = '/' requestUrl.pathname = '/'
} }
const requestHeaders = fromNodeHeaders(params.request.headers) const requestHeaders = fromNodeOutgoingHttpHeaders(params.request.headers)
const flightHeaders = new Map() const flightHeaders = new Map()
// Parameters should only be stripped for middleware // Parameters should only be stripped for middleware
if (!isEdgeRendering) { if (!isEdgeRendering) {
......
...@@ -3,7 +3,7 @@ import type { NodeNextRequest } from '../../../base-http/node' ...@@ -3,7 +3,7 @@ import type { NodeNextRequest } from '../../../base-http/node'
import type { WebNextRequest } from '../../../base-http/web' import type { WebNextRequest } from '../../../base-http/web'
import { getRequestMeta } from '../../../request-meta' import { getRequestMeta } from '../../../request-meta'
import { fromNodeHeaders } from '../../utils' import { fromNodeOutgoingHttpHeaders } from '../../utils'
import { NextRequest } from '../request' import { NextRequest } from '../request'
export class NextRequestAdapter { export class NextRequestAdapter {
...@@ -38,7 +38,7 @@ export class NextRequestAdapter { ...@@ -38,7 +38,7 @@ export class NextRequestAdapter {
return new NextRequest(url, { return new NextRequest(url, {
body, body,
method: request.method, method: request.method,
headers: fromNodeHeaders(request.headers), headers: fromNodeOutgoingHttpHeaders(request.headers),
// @ts-expect-error - see https://github.com/whatwg/fetch/pull/1457 // @ts-expect-error - see https://github.com/whatwg/fetch/pull/1457
duplex: 'half', duplex: 'half',
// geo // geo
...@@ -57,7 +57,7 @@ export class NextRequestAdapter { ...@@ -57,7 +57,7 @@ export class NextRequestAdapter {
return new NextRequest(request.url, { return new NextRequest(request.url, {
body, body,
method: request.method, method: request.method,
headers: fromNodeHeaders(request.headers), headers: fromNodeOutgoingHttpHeaders(request.headers),
// @ts-expect-error - see https://github.com/whatwg/fetch/pull/1457 // @ts-expect-error - see https://github.com/whatwg/fetch/pull/1457
duplex: 'half', duplex: 'half',
// geo // geo
......
import type { I18NConfig } from '../../config-shared' import type { I18NConfig } from '../../config-shared'
import type { RequestData } from '../types' import type { RequestData } from '../types'
import { NextURL } from '../next-url' import { NextURL } from '../next-url'
import { toNodeHeaders, validateURL } from '../utils' import { toNodeOutgoingHttpHeaders, validateURL } from '../utils'
import { RemovedUAError, RemovedPageError } from '../error' import { RemovedUAError, RemovedPageError } from '../error'
import { RequestCookies } from './cookies' import { RequestCookies } from './cookies'
...@@ -22,7 +22,7 @@ export class NextRequest extends Request { ...@@ -22,7 +22,7 @@ export class NextRequest extends Request {
validateURL(url) validateURL(url)
super(url, init) super(url, init)
const nextUrl = new NextURL(url, { const nextUrl = new NextURL(url, {
headers: toNodeHeaders(this.headers), headers: toNodeOutgoingHttpHeaders(this.headers),
nextConfig: init.nextConfig, nextConfig: init.nextConfig,
}) })
this[INTERNALS] = { this[INTERNALS] = {
......
import type { I18NConfig } from '../../config-shared' import type { I18NConfig } from '../../config-shared'
import { NextURL } from '../next-url' import { NextURL } from '../next-url'
import { toNodeHeaders, validateURL } from '../utils' import { toNodeOutgoingHttpHeaders, validateURL } from '../utils'
import { ResponseCookies } from './cookies' import { ResponseCookies } from './cookies'
...@@ -40,7 +40,7 @@ export class NextResponse<Body = unknown> extends Response { ...@@ -40,7 +40,7 @@ export class NextResponse<Body = unknown> extends Response {
cookies: new ResponseCookies(this.headers), cookies: new ResponseCookies(this.headers),
url: init.url url: init.url
? new NextURL(init.url, { ? new NextURL(init.url, {
headers: toNodeHeaders(this.headers), headers: toNodeOutgoingHttpHeaders(this.headers),
nextConfig: init.nextConfig, nextConfig: init.nextConfig,
}) })
: undefined, : undefined,
......
import { toNodeHeaders } from './utils' import { toNodeOutgoingHttpHeaders } from './utils'
// We use `Headers` here which is provided by the polyfill. // We use `Headers` here which is provided by the polyfill.
import '../node-polyfill-fetch' import '../node-polyfill-fetch'
...@@ -10,7 +10,7 @@ describe('toNodeHeaders', () => { ...@@ -10,7 +10,7 @@ describe('toNodeHeaders', () => {
headers.append('set-cookie', 'foo=bar') headers.append('set-cookie', 'foo=bar')
headers.append('set-cookie', 'bar=foo') headers.append('set-cookie', 'bar=foo')
expect(toNodeHeaders(headers)).toEqual({ expect(toNodeOutgoingHttpHeaders(headers)).toEqual({
'set-cookie': ['foo=bar', 'bar=foo'], 'set-cookie': ['foo=bar', 'bar=foo'],
}) })
}) })
...@@ -20,7 +20,7 @@ describe('toNodeHeaders', () => { ...@@ -20,7 +20,7 @@ describe('toNodeHeaders', () => {
headers.append('set-cookie', 'foo=bar') headers.append('set-cookie', 'foo=bar')
expect(toNodeHeaders(headers)).toEqual({ expect(toNodeOutgoingHttpHeaders(headers)).toEqual({
'set-cookie': 'foo=bar', 'set-cookie': 'foo=bar',
}) })
}) })
...@@ -30,13 +30,13 @@ describe('toNodeHeaders', () => { ...@@ -30,13 +30,13 @@ describe('toNodeHeaders', () => {
headers.append('set-cookie', 'foo=bar, bar=foo') headers.append('set-cookie', 'foo=bar, bar=foo')
expect(toNodeHeaders(headers)).toEqual({ expect(toNodeOutgoingHttpHeaders(headers)).toEqual({
'set-cookie': ['foo=bar', 'bar=foo'], 'set-cookie': ['foo=bar', 'bar=foo'],
}) })
headers.append('set-cookie', 'baz=qux') headers.append('set-cookie', 'baz=qux')
expect(toNodeHeaders(headers)).toEqual({ expect(toNodeOutgoingHttpHeaders(headers)).toEqual({
'set-cookie': ['foo=bar', 'bar=foo', 'baz=qux'], 'set-cookie': ['foo=bar', 'bar=foo', 'baz=qux'],
}) })
}) })
...@@ -47,12 +47,8 @@ describe('toNodeHeaders', () => { ...@@ -47,12 +47,8 @@ describe('toNodeHeaders', () => {
headers.append('set-cookie', 'foo=bar') headers.append('set-cookie', 'foo=bar')
headers.append('Set-Cookie', 'bar=foo') headers.append('Set-Cookie', 'bar=foo')
expect(toNodeHeaders(headers)).toEqual({ expect(toNodeOutgoingHttpHeaders(headers)).toEqual({
'set-cookie': ['foo=bar', 'bar=foo'], 'set-cookie': ['foo=bar', 'bar=foo'],
}) })
}) })
it('should return an empty object when no headers are provided', () => {
expect(toNodeHeaders()).toEqual({})
})
}) })
import type { OutgoingHttpHeaders } from 'http' import type { OutgoingHttpHeaders } from 'http'
export function fromNodeHeaders(object: OutgoingHttpHeaders): Headers { /**
* Converts a Node.js IncomingHttpHeaders object to a Headers object. Any
* headers with multiple values will be joined with a comma and space. Any
* headers that have an undefined value will be ignored and others will be
* coerced to strings.
*
* @param nodeHeaders the headers object to convert
* @returns the converted headers object
*/
export function fromNodeOutgoingHttpHeaders(
nodeHeaders: OutgoingHttpHeaders
): Headers {
const headers = new Headers() const headers = new Headers()
for (let [key, value] of Object.entries(object)) { for (let [key, value] of Object.entries(nodeHeaders)) {
const values = Array.isArray(value) ? value : [value] const values = Array.isArray(value) ? value : [value]
for (let v of values) { for (let v of values) {
if (typeof v === 'undefined') continue if (typeof v === 'undefined') continue
...@@ -92,8 +103,17 @@ export function splitCookiesString(cookiesString: string) { ...@@ -92,8 +103,17 @@ export function splitCookiesString(cookiesString: string) {
return cookiesStrings return cookiesStrings
} }
export function toNodeHeaders(headers?: Headers): OutgoingHttpHeaders { /**
const result: OutgoingHttpHeaders = {} * Converts a Headers object to a Node.js OutgoingHttpHeaders object. This is
* required to support the set-cookie header, which may have multiple values.
*
* @param headers the headers object to convert
* @returns the converted headers object
*/
export function toNodeOutgoingHttpHeaders(
headers: Headers
): OutgoingHttpHeaders {
const nodeHeaders: OutgoingHttpHeaders = {}
const cookies: string[] = [] const cookies: string[] = []
if (headers) { if (headers) {
for (const [key, value] of headers.entries()) { for (const [key, value] of headers.entries()) {
...@@ -102,13 +122,13 @@ export function toNodeHeaders(headers?: Headers): OutgoingHttpHeaders { ...@@ -102,13 +122,13 @@ export function toNodeHeaders(headers?: Headers): OutgoingHttpHeaders {
// set-cookie headers. We need to merge them into one header array // set-cookie headers. We need to merge them into one header array
// to represent all the cookies. // to represent all the cookies.
cookies.push(...splitCookiesString(value)) cookies.push(...splitCookiesString(value))
result[key] = cookies.length === 1 ? cookies[0] : cookies nodeHeaders[key] = cookies.length === 1 ? cookies[0] : cookies
} else { } else {
result[key] = value nodeHeaders[key] = value
} }
} }
} }
return result return nodeHeaders
} }
/** /**
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment