Unverified Commit ad39fe86 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Move off of deprecated url.parse (#87257)

parent dfd3c260
import { execSync } from 'node:child_process' import { execSync } from 'node:child_process'
import { lookup } from 'node:dns/promises' import { lookup } from 'node:dns/promises'
import url from 'node:url' import { URL } from 'node:url'
function getProxy(): string | undefined { function getProxy(): string | undefined {
if (process.env.https_proxy) { if (process.env.https_proxy) {
...@@ -27,7 +27,14 @@ export async function getOnline(): Promise<boolean> { ...@@ -27,7 +27,14 @@ export async function getOnline(): Promise<boolean> {
return false return false
} }
const { hostname } = url.parse(proxy) let url: URL
try {
url = new URL(proxy)
} catch {
// Invalid proxy URL
return false
}
const { hostname } = url
if (!hostname) { if (!hostname) {
// Invalid proxy URL // Invalid proxy URL
return false return false
......
import type { Token } from 'next/dist/compiled/path-to-regexp' import type { Token } from 'next/dist/compiled/path-to-regexp'
import { parse, tokensToRegexp } from 'next/dist/compiled/path-to-regexp' import { parse, tokensToRegexp } from 'next/dist/compiled/path-to-regexp'
import { parse as parseURL } from 'url'
import isError from './is-error' import isError from './is-error'
import { normalizeTokensForRegexp } from './route-pattern-normalizer' import { normalizeTokensForRegexp } from './route-pattern-normalizer'
...@@ -67,8 +66,8 @@ export function tryToParsePath( ...@@ -67,8 +66,8 @@ export function tryToParsePath(
const result: ParseResult = { route, parsedPath: route } const result: ParseResult = { route, parsedPath: route }
try { try {
if (options?.handleUrl) { if (options?.handleUrl) {
const parsed = parseURL(route, true) const parsed = new URL(route, 'http://n')
result.parsedPath = `${parsed.pathname!}${parsed.hash || ''}` result.parsedPath = `${parsed.pathname}${parsed.hash || ''}`
} }
result.tokens = parse(result.parsedPath) result.tokens = parse(result.parsedPath)
......
...@@ -18,7 +18,6 @@ import type { ...@@ -18,7 +18,6 @@ import type {
ServerOnInstrumentationRequestError, ServerOnInstrumentationRequestError,
} from './app-render/types' } from './app-render/types'
import type { ServerComponentsHmrCache } from './response-cache' import type { ServerComponentsHmrCache } from './response-cache'
import type { UrlWithParsedQuery } from 'url'
import { import {
NormalizeError, NormalizeError,
DecodeError, DecodeError,
...@@ -46,7 +45,7 @@ import type { PathnameNormalizer } from './normalizers/request/pathname-normaliz ...@@ -46,7 +45,7 @@ import type { PathnameNormalizer } from './normalizers/request/pathname-normaliz
import type { InstrumentationModule } from './instrumentation/types' import type { InstrumentationModule } from './instrumentation/types'
import * as path from 'path' import * as path from 'path'
import { format as formatUrl, parse as parseUrl } from 'url' import { format as formatUrl } from 'url'
import { formatHostname } from './lib/format-hostname' import { formatHostname } from './lib/format-hostname'
import { import {
APP_PATHS_MANIFEST, APP_PATHS_MANIFEST,
...@@ -75,7 +74,10 @@ import { ...@@ -75,7 +74,10 @@ import {
import { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix' import { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { getHostname } from '../shared/lib/get-hostname' import { getHostname } from '../shared/lib/get-hostname'
import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url' import {
parseUrl,
parseUrl as parseUrlUtil,
} from '../shared/lib/router/utils/parse-url'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info' import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
import { import {
RSC_HEADER, RSC_HEADER,
...@@ -953,7 +955,7 @@ export default abstract class Server< ...@@ -953,7 +955,7 @@ export default abstract class Server<
throw new Error('Invariant: url can not be undefined') throw new Error('Invariant: url can not be undefined')
} }
parsedUrl = parseUrl(req.url!, true) parsedUrl = parseUrl(req.url)
} }
if (!parsedUrl.pathname) { if (!parsedUrl.pathname) {
...@@ -1681,7 +1683,7 @@ export default abstract class Server< ...@@ -1681,7 +1683,7 @@ export default abstract class Server<
protected async run( protected async run(
req: ServerRequest, req: ServerRequest,
res: ServerResponse, res: ServerResponse,
parsedUrl: UrlWithParsedQuery parsedUrl: NextUrlWithParsedQuery
): Promise<void> { ): Promise<void> {
return getTracer().trace(BaseServerSpan.run, async () => return getTracer().trace(BaseServerSpan.run, async () =>
this.runImpl(req, res, parsedUrl) this.runImpl(req, res, parsedUrl)
...@@ -1691,7 +1693,7 @@ export default abstract class Server< ...@@ -1691,7 +1693,7 @@ export default abstract class Server<
private async runImpl( private async runImpl(
req: ServerRequest, req: ServerRequest,
res: ServerResponse, res: ServerResponse,
parsedUrl: UrlWithParsedQuery parsedUrl: NextUrlWithParsedQuery
): Promise<void> { ): Promise<void> {
await this.handleCatchallRenderRequest(req, res, parsedUrl) await this.handleCatchallRenderRequest(req, res, parsedUrl)
} }
...@@ -2963,7 +2965,7 @@ export default abstract class Server< ...@@ -2963,7 +2965,7 @@ export default abstract class Server<
parsedUrl?: Pick<NextUrlWithParsedQuery, 'pathname' | 'query'>, parsedUrl?: Pick<NextUrlWithParsedQuery, 'pathname' | 'query'>,
setHeaders = true setHeaders = true
): Promise<void> { ): Promise<void> {
const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(req.url!, true) const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(req.url)
// Ensure the locales are provided on the request meta. // Ensure the locales are provided on the request meta.
if (this.nextConfig.i18n) { if (this.nextConfig.i18n) {
......
...@@ -368,7 +368,7 @@ export async function initialize(opts: { ...@@ -368,7 +368,7 @@ export async function initialize(opts: {
req.url = removePathPrefix(origUrl, config.assetPrefix) req.url = removePathPrefix(origUrl, config.assetPrefix)
} }
const parsedUrl = url.parse(req.url || '/') const parsedUrl = parseUrlUtil(req.url || '/')
const hotReloaderResult = await development.bundler.hotReloader.run( const hotReloaderResult = await development.bundler.hotReloader.run(
req, req,
...@@ -508,14 +508,9 @@ export async function initialize(opts: { ...@@ -508,14 +508,9 @@ export async function initialize(opts: {
if (!(req.method === 'GET' || req.method === 'HEAD')) { if (!(req.method === 'GET' || req.method === 'HEAD')) {
res.setHeader('Allow', ['GET', 'HEAD']) res.setHeader('Allow', ['GET', 'HEAD'])
res.statusCode = 405 res.statusCode = 405
return await invokeRender( return await invokeRender(parseUrlUtil('/405'), '/405', handleIndex, {
url.parse('/405', true), invokeStatus: 405,
'/405', })
handleIndex,
{
invokeStatus: 405,
}
)
} }
try { try {
...@@ -574,7 +569,7 @@ export async function initialize(opts: { ...@@ -574,7 +569,7 @@ export async function initialize(opts: {
const invokeStatus = err.statusCode const invokeStatus = err.statusCode
res.statusCode = err.statusCode res.statusCode = err.statusCode
return await invokeRender( return await invokeRender(
url.parse(invokePath, true), parseUrlUtil(invokePath),
invokePath, invokePath,
handleIndex, handleIndex,
{ {
...@@ -684,7 +679,7 @@ export async function initialize(opts: { ...@@ -684,7 +679,7 @@ export async function initialize(opts: {
console.error(err) console.error(err)
} }
res.statusCode = Number(invokeStatus) res.statusCode = Number(invokeStatus)
return await invokeRender(url.parse(invokePath, true), invokePath, 0, { return await invokeRender(parseUrlUtil(invokePath), invokePath, 0, {
invokeStatus: res.statusCode, invokeStatus: res.statusCode,
}) })
} catch (err2) { } catch (err2) {
......
...@@ -8,7 +8,6 @@ import type { Header } from '../../../lib/load-custom-routes' ...@@ -8,7 +8,6 @@ import type { Header } from '../../../lib/load-custom-routes'
import type { UnwrapPromise } from '../../../lib/coalesced-function' import type { UnwrapPromise } from '../../../lib/coalesced-function'
import type { NextUrlWithParsedQuery } from '../../request-meta' import type { NextUrlWithParsedQuery } from '../../request-meta'
import url from 'url'
import path from 'node:path' import path from 'node:path'
import setupDebug from 'next/dist/compiled/debug' import setupDebug from 'next/dist/compiled/debug'
import { getCloneableBody } from '../../body-streams' import { getCloneableBody } from '../../body-streams'
...@@ -26,6 +25,7 @@ import { normalizeRepeatedSlashes } from '../../../shared/lib/utils' ...@@ -26,6 +25,7 @@ import { normalizeRepeatedSlashes } from '../../../shared/lib/utils'
import { getRelativeURL } from '../../../shared/lib/router/utils/relativize-url' import { getRelativeURL } from '../../../shared/lib/router/utils/relativize-url'
import { addPathPrefix } from '../../../shared/lib/router/utils/add-path-prefix' import { addPathPrefix } from '../../../shared/lib/router/utils/add-path-prefix'
import { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix' import { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix'
import { parseUrl } from '../../../shared/lib/router/utils/parse-url'
import { detectDomainLocale } from '../../../shared/lib/i18n/detect-domain-locale' import { detectDomainLocale } from '../../../shared/lib/i18n/detect-domain-locale'
import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'
import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix' import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'
...@@ -124,7 +124,7 @@ export function getResolveRoutes( ...@@ -124,7 +124,7 @@ export function getResolveRoutes(
let finished = false let finished = false
let resHeaders: Record<string, string | string[]> = {} let resHeaders: Record<string, string | string[]> = {}
let matchedOutput: FsOutput | null = null let matchedOutput: FsOutput | null = null
let parsedUrl = url.parse(req.url || '', true) as NextUrlWithParsedQuery let parsedUrl = parseUrl(req.url || '') as NextUrlWithParsedQuery
let didRewrite = false let didRewrite = false
const urlParts = (req.url || '').split('?', 1) const urlParts = (req.url || '').split('?', 1)
...@@ -142,7 +142,7 @@ export function getResolveRoutes( ...@@ -142,7 +142,7 @@ export function getResolveRoutes(
// handle trailing slash as that is handled the same as a next.config.js // handle trailing slash as that is handled the same as a next.config.js
// redirect // redirect
if (urlNoQuery?.match(/(\\|\/\/)/)) { if (urlNoQuery?.match(/(\\|\/\/)/)) {
parsedUrl = url.parse(normalizeRepeatedSlashes(req.url!), true) parsedUrl = parseUrl(normalizeRepeatedSlashes(req.url!))
return { return {
parsedUrl, parsedUrl,
resHeaders, resHeaders,
...@@ -662,7 +662,7 @@ export function getResolveRoutes( ...@@ -662,7 +662,7 @@ export function getResolveRoutes(
const destination = getRelativeURL(value, initUrl) const destination = getRelativeURL(value, initUrl)
resHeaders['x-middleware-rewrite'] = destination resHeaders['x-middleware-rewrite'] = destination
parsedUrl = url.parse(destination, true) parsedUrl = parseUrl(destination)
if (parsedUrl.protocol) { if (parsedUrl.protocol) {
return { return {
...@@ -697,7 +697,7 @@ export function getResolveRoutes( ...@@ -697,7 +697,7 @@ export function getResolveRoutes(
// Process as redirect: update parsedUrl and convert to relative URL // Process as redirect: update parsedUrl and convert to relative URL
const rel = getRelativeURL(value, initUrl) const rel = getRelativeURL(value, initUrl)
resHeaders['location'] = rel resHeaders['location'] = rel
parsedUrl = url.parse(rel, true) parsedUrl = parseUrl(rel)
return { return {
parsedUrl, parsedUrl,
...@@ -752,11 +752,9 @@ export function getResolveRoutes( ...@@ -752,11 +752,9 @@ export function getResolveRoutes(
parsedDestination.pathname parsedDestination.pathname
) )
// @ts-expect-error // custom ParsedUrl
const unsafeParsedUrl: NextUrlWithParsedQuery = parsedDestination
return { return {
finished: true, finished: true,
parsedUrl: unsafeParsedUrl, parsedUrl: parsedDestination,
resHeaders: null, resHeaders: null,
statusCode: getRedirectStatus(route), statusCode: getRedirectStatus(route),
} }
...@@ -828,10 +826,8 @@ export function getResolveRoutes( ...@@ -828,10 +826,8 @@ export function getResolveRoutes(
} }
if (parsedDestination.protocol) { if (parsedDestination.protocol) {
// @ts-expect-error // custom ParsedUrl
const unsafeParsedUrl: NextUrlWithParsedQuery = parsedDestination
return { return {
parsedUrl: unsafeParsedUrl, parsedUrl: parsedDestination,
resHeaders: null, resHeaders: null,
finished: true, finished: true,
} }
......
...@@ -10,7 +10,6 @@ import type { NextJsHotReloaderInterface } from '../../dev/hot-reloader-types' ...@@ -10,7 +10,6 @@ import type { NextJsHotReloaderInterface } from '../../dev/hot-reloader-types'
import { createDefineEnv } from '../../../build/swc' import { createDefineEnv } from '../../../build/swc'
import { installBindings } from '../../../build/swc/install-bindings' import { installBindings } from '../../../build/swc/install-bindings'
import fs from 'fs' import fs from 'fs'
import url from 'url'
import path from 'path' import path from 'path'
import qs from 'querystring' import qs from 'querystring'
import Watchpack from 'next/dist/compiled/watchpack' import Watchpack from 'next/dist/compiled/watchpack'
...@@ -81,6 +80,7 @@ import { ...@@ -81,6 +80,7 @@ import {
MIDDLEWARE_FILENAME, MIDDLEWARE_FILENAME,
PROXY_FILENAME, PROXY_FILENAME,
} from '../../../lib/constants' } from '../../../lib/constants'
import { parseUrl } from '../../../lib/url'
import { import {
createRouteTypesManifest, createRouteTypesManifest,
writeRouteTypesManifest, writeRouteTypesManifest,
...@@ -1213,9 +1213,10 @@ async function startWatcher( ...@@ -1213,9 +1213,10 @@ async function startWatcher(
opts.fsChecker.devVirtualFsItems.add(devTurbopackMiddlewareManifestPath) opts.fsChecker.devVirtualFsItems.add(devTurbopackMiddlewareManifestPath)
async function requestHandler(req: IncomingMessage, res: ServerResponse) { async function requestHandler(req: IncomingMessage, res: ServerResponse) {
const parsedUrl = url.parse(req.url || '/') const parsedUrl = parseUrl(req.url || '/')
const pathname = parsedUrl !== undefined ? parsedUrl.pathname : null
if (parsedUrl.pathname?.includes(clientPagesManifestPath)) { if (pathname !== null && pathname.includes(clientPagesManifestPath)) {
res.statusCode = 200 res.statusCode = 200
res.setHeader('Content-Type', JSON_CONTENT_TYPE_HEADER) res.setHeader('Content-Type', JSON_CONTENT_TYPE_HEADER)
res.end( res.end(
...@@ -1229,8 +1230,9 @@ async function startWatcher( ...@@ -1229,8 +1230,9 @@ async function startWatcher(
} }
if ( if (
parsedUrl.pathname?.includes(devMiddlewareManifestPath) || pathname !== null &&
parsedUrl.pathname?.includes(devTurbopackMiddlewareManifestPath) (pathname.includes(devMiddlewareManifestPath) ||
pathname.includes(devTurbopackMiddlewareManifestPath))
) { ) {
res.statusCode = 200 res.statusCode = 200
res.setHeader('Content-Type', JSON_CONTENT_TYPE_HEADER) res.setHeader('Content-Type', JSON_CONTENT_TYPE_HEADER)
......
...@@ -22,7 +22,6 @@ import type { Params } from './request/params' ...@@ -22,7 +22,6 @@ import type { Params } from './request/params'
import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher' import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'
import type { RouteMatch } from './route-matches/route-match' import type { RouteMatch } from './route-matches/route-match'
import type { IncomingMessage, ServerResponse } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
import type { UrlWithParsedQuery } from 'url'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { ParsedUrl } from '../shared/lib/router/utils/parse-url' import type { ParsedUrl } from '../shared/lib/router/utils/parse-url'
import type { CacheControl } from './lib/cache-control' import type { CacheControl } from './lib/cache-control'
...@@ -1636,7 +1635,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -1636,7 +1635,7 @@ export default class NextNodeServer extends BaseServer<
request: NodeNextRequest request: NodeNextRequest
response: NodeNextResponse response: NodeNextResponse
parsedUrl: ParsedUrl parsedUrl: ParsedUrl
parsed: UrlWithParsedQuery parsed: NextUrlWithParsedQuery
onWarning?: (warning: Error) => void onWarning?: (warning: Error) => void
}) { }) {
if (process.env.NEXT_MINIMAL) { if (process.env.NEXT_MINIMAL) {
......
...@@ -3,7 +3,6 @@ import type { ...@@ -3,7 +3,6 @@ import type {
NodeRequestHandler, NodeRequestHandler,
Options as ServerOptions, Options as ServerOptions,
} from './next-server' } from './next-server'
import type { UrlWithParsedQuery } from 'url'
import type { IncomingMessage, ServerResponse } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
import type { Duplex } from 'stream' import type { Duplex } from 'stream'
import type { NextUrlWithParsedQuery, RequestMeta } from './request-meta' import type { NextUrlWithParsedQuery, RequestMeta } from './request-meta'
...@@ -148,7 +147,7 @@ export class NextServer implements NextWrapperServer { ...@@ -148,7 +147,7 @@ export class NextServer implements NextWrapperServer {
return async ( return async (
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
parsedUrl?: UrlWithParsedQuery parsedUrl?: NextUrlWithParsedQuery
) => { ) => {
return getTracer().trace(NextServerSpan.getRequestHandler, async () => { return getTracer().trace(NextServerSpan.getRequestHandler, async () => {
const requestHandler = await this.getServerRequestHandler() const requestHandler = await this.getServerRequestHandler()
...@@ -165,7 +164,7 @@ export class NextServer implements NextWrapperServer { ...@@ -165,7 +164,7 @@ export class NextServer implements NextWrapperServer {
return async ( return async (
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
parsedUrl?: UrlWithParsedQuery parsedUrl?: NextUrlWithParsedQuery
) => { ) => {
return getTracer().trace( return getTracer().trace(
NextServerSpan.getRequestHandlerWithMetadata, NextServerSpan.getRequestHandlerWithMetadata,
...@@ -444,7 +443,7 @@ class NextCustomServer implements NextWrapperServer { ...@@ -444,7 +443,7 @@ class NextCustomServer implements NextWrapperServer {
return async ( return async (
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
parsedUrl?: UrlWithParsedQuery parsedUrl?: NextUrlWithParsedQuery
) => { ) => {
this.setupWebSocketHandler(this.options.httpServer, req) this.setupWebSocketHandler(this.options.httpServer, req)
......
import type { IncomingMessage } from 'http' import type { IncomingMessage } from 'http'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { UrlWithParsedQuery } from 'url'
import type { BaseNextRequest } from './base-http' import type { BaseNextRequest } from './base-http'
import type { CloneableBody } from './body-streams' import type { CloneableBody } from './body-streams'
import type { RouteMatch } from './route-matches/route-match' import type { RouteMatch } from './route-matches/route-match'
...@@ -357,6 +356,26 @@ type NextQueryMetadata = { ...@@ -357,6 +356,26 @@ type NextQueryMetadata = {
export type NextParsedUrlQuery = ParsedUrlQuery & NextQueryMetadata export type NextParsedUrlQuery = ParsedUrlQuery & NextQueryMetadata
export interface NextUrlWithParsedQuery extends UrlWithParsedQuery { /**
* subset of `url.parse` return value
*/
interface LegacyUrl {
auth?: string | null
hash: string | null
hostname: string | null
href: string
pathname: string | null
protocol: string | null
search: string | null
slashes: boolean | null
port: string | null
query: string | null | ParsedUrlQuery
}
interface LegacyUrlWithParsedQuery extends LegacyUrl {
query: ParsedUrlQuery
}
// TODO: Remove in favor of WHATWG URLs
export interface NextUrlWithParsedQuery extends LegacyUrlWithParsedQuery {
query: NextParsedUrlQuery query: NextParsedUrlQuery
} }
...@@ -2,8 +2,8 @@ import type { Rewrite } from '../lib/load-custom-routes' ...@@ -2,8 +2,8 @@ import type { Rewrite } from '../lib/load-custom-routes'
import type { RouteMatchFn } from '../shared/lib/router/utils/route-matcher' import type { RouteMatchFn } from '../shared/lib/router/utils/route-matcher'
import type { NextConfig } from './config' import type { NextConfig } from './config'
import type { BaseNextRequest } from './base-http' import type { BaseNextRequest } from './base-http'
import type { NextUrlWithParsedQuery } from './request-meta'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { UrlWithParsedQuery } from 'url'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { getPathMatch } from '../shared/lib/router/utils/path-match' import { getPathMatch } from '../shared/lib/router/utils/path-match'
...@@ -218,11 +218,13 @@ export function getServerUtils({ ...@@ -218,11 +218,13 @@ export function getServerUtils({
function handleRewrites( function handleRewrites(
req: BaseNextRequest | IncomingMessage, req: BaseNextRequest | IncomingMessage,
parsedUrl: DeepReadonly<UrlWithParsedQuery> parsedUrl: DeepReadonly<NextUrlWithParsedQuery>
) { ) {
// Here we deep clone the parsedUrl to avoid mutating the original. We also // Here we deep clone the parsedUrl to avoid mutating the original. We also
// cast this to a mutable type so we can mutate it within this scope. // cast this to a mutable type so we can mutate it within this scope.
const rewrittenParsedUrl = structuredClone(parsedUrl) as UrlWithParsedQuery const rewrittenParsedUrl = structuredClone(
parsedUrl
) as NextUrlWithParsedQuery
const rewriteParams: Record<string, string> = {} const rewriteParams: Record<string, string> = {}
let fsPathname = rewrittenParsedUrl.pathname let fsPathname = rewrittenParsedUrl.pathname
......
...@@ -4,11 +4,12 @@ describe('relative urls', () => { ...@@ -4,11 +4,12 @@ describe('relative urls', () => {
it('should return valid pathname', () => { it('should return valid pathname', () => {
expect(parseRelativeUrl('/').pathname).toBe('/') expect(parseRelativeUrl('/').pathname).toBe('/')
expect(parseRelativeUrl('/abc').pathname).toBe('/abc') expect(parseRelativeUrl('/abc').pathname).toBe('/abc')
expect(parseRelativeUrl('//**y/\\').pathname).toBe('//**y//')
expect(parseRelativeUrl('//google.com').pathname).toBe('//google.com')
}) })
it('should throw for invalid pathname', () => { it('should throw for invalid pathname', () => {
expect(() => parseRelativeUrl('//**y/\\')).toThrow() expect(() => parseRelativeUrl('http://example.com/abc')).toThrow()
expect(() => parseRelativeUrl('//google.com')).toThrow()
}) })
}) })
......
...@@ -3,12 +3,17 @@ import { getLocationOrigin } from '../../utils' ...@@ -3,12 +3,17 @@ import { getLocationOrigin } from '../../utils'
import { searchParamsToUrlQuery } from './querystring' import { searchParamsToUrlQuery } from './querystring'
export interface ParsedRelativeUrl { export interface ParsedRelativeUrl {
auth: string | null
hash: string hash: string
host: string | null
hostname: string | null
href: string href: string
pathname: string pathname: string
port: string | null
protocol: string | null
query: ParsedUrlQuery query: ParsedUrlQuery
search: string search: string
slashes: undefined slashes: null
} }
/** /**
...@@ -44,23 +49,32 @@ export function parseRelativeUrl( ...@@ -44,23 +49,32 @@ export function parseRelativeUrl(
) )
: globalBase : globalBase
const { pathname, searchParams, search, hash, href, origin } = new URL( const { pathname, searchParams, search, hash, href, origin } = url.startsWith(
url, '/'
resolvedBase
) )
? // 'http://localhost:3000///' would be received as '///' in Node.js' IncomingMessage
// See https://nodejs.org/api/http.html#messageurl
// Not using `origin` to support other protocols
new URL(`${resolvedBase.protocol}//${resolvedBase.host}${url}`)
: new URL(url, resolvedBase)
if (origin !== globalBase.origin) { if (origin !== globalBase.origin) {
throw new Error(`invariant: invalid relative URL, router received ${url}`) throw new Error(`invariant: invalid relative URL, router received ${url}`)
} }
return { return {
auth: null,
host: null,
hostname: null,
pathname, pathname,
port: null,
protocol: null,
query: parseQuery ? searchParamsToUrlQuery(searchParams) : undefined, query: parseQuery ? searchParamsToUrlQuery(searchParams) : undefined,
search, search,
hash, hash,
href: href.slice(origin.length), href: href.slice(origin.length),
// We don't know for relative URLs at this point since we set a custom, internal // We don't know for relative URLs at this point since we set a custom, internal
// base that isn't surfaced to users. // base that isn't surfaced to users.
slashes: undefined, slashes: null,
} }
} }
...@@ -4,16 +4,17 @@ import { searchParamsToUrlQuery } from './querystring' ...@@ -4,16 +4,17 @@ import { searchParamsToUrlQuery } from './querystring'
import { parseRelativeUrl } from './parse-relative-url' import { parseRelativeUrl } from './parse-relative-url'
export interface ParsedUrl { export interface ParsedUrl {
auth: string | null
hash: string hash: string
hostname?: string | null hostname: string | null
href: string href: string
origin?: string | null
pathname: string pathname: string
port?: string | null port: string | null
protocol?: string | null protocol: string | null
query: ParsedUrlQuery query: ParsedUrlQuery
origin?: string | null
search: string search: string
slashes: boolean | undefined slashes: boolean | null
} }
export function parseUrl(url: string): ParsedUrl { export function parseUrl(url: string): ParsedUrl {
...@@ -22,15 +23,25 @@ export function parseUrl(url: string): ParsedUrl { ...@@ -22,15 +23,25 @@ export function parseUrl(url: string): ParsedUrl {
} }
const parsedURL = new URL(url) const parsedURL = new URL(url)
const username = parsedURL.username
const password = parsedURL.password
const auth = username
? password
? `${username}:${password}`
: username
: null
const pathname = parsedURL.pathname
const search = parsedURL.search
return { return {
auth,
hash: parsedURL.hash, hash: parsedURL.hash,
hostname: parsedURL.hostname, hostname: parsedURL.hostname,
href: parsedURL.href, href: parsedURL.href,
pathname: parsedURL.pathname, pathname,
port: parsedURL.port, port: parsedURL.port,
protocol: parsedURL.protocol, protocol: parsedURL.protocol,
query: searchParamsToUrlQuery(parsedURL.searchParams), query: searchParamsToUrlQuery(parsedURL.searchParams),
search: parsedURL.search, search,
origin: parsedURL.origin, origin: parsedURL.origin,
slashes: slashes:
parsedURL.href.slice( parsedURL.href.slice(
......
...@@ -14,14 +14,18 @@ describe('parseDestination', () => { ...@@ -14,14 +14,18 @@ describe('parseDestination', () => {
expect(result).toMatchInlineSnapshot(` expect(result).toMatchInlineSnapshot(`
{ {
"auth": null,
"hash": "", "hash": "",
"hostname": undefined, "host": null,
"hostname": null,
"href": "/hello/:name", "href": "/hello/:name",
"origin": undefined, "origin": undefined,
"pathname": "/hello/:name", "pathname": "/hello/:name",
"port": null,
"protocol": null,
"query": {}, "query": {},
"search": "", "search": "",
"slashes": undefined, "slashes": null,
} }
`) `)
}) })
...@@ -39,6 +43,7 @@ describe('parseDestination', () => { ...@@ -39,6 +43,7 @@ describe('parseDestination', () => {
expect(result).toMatchInlineSnapshot(` expect(result).toMatchInlineSnapshot(`
{ {
"auth": null,
"hash": "#bar", "hash": "#bar",
"hostname": "o:foo.com", "hostname": "o:foo.com",
"href": "https://o:foo.com/hello/:name#bar", "href": "https://o:foo.com/hello/:name#bar",
...@@ -66,6 +71,7 @@ describe('parseDestination', () => { ...@@ -66,6 +71,7 @@ describe('parseDestination', () => {
expect(result).toMatchInlineSnapshot(` expect(result).toMatchInlineSnapshot(`
{ {
"auth": null,
"hash": "", "hash": "",
"hostname": "o:foo.com", "hostname": "o:foo.com",
"href": "https://o:foo.com/hello/:name?foo=:bar", "href": "https://o:foo.com/hello/:name?foo=:bar",
......
...@@ -5,7 +5,7 @@ import type { RouteHas } from '../../../../lib/load-custom-routes' ...@@ -5,7 +5,7 @@ import type { RouteHas } from '../../../../lib/load-custom-routes'
import type { BaseNextRequest } from '../../../../server/base-http' import type { BaseNextRequest } from '../../../../server/base-http'
import { escapeStringRegexp } from '../../escape-regexp' import { escapeStringRegexp } from '../../escape-regexp'
import { parseUrl } from './parse-url' import { parseUrl, type ParsedUrl } from './parse-url'
import { import {
INTERCEPTION_ROUTE_MARKERS, INTERCEPTION_ROUTE_MARKERS,
isInterceptionRouteAppPath, isInterceptionRouteAppPath,
...@@ -163,7 +163,7 @@ export function parseDestination(args: { ...@@ -163,7 +163,7 @@ export function parseDestination(args: {
destination: string destination: string
params: Readonly<Params> params: Readonly<Params>
query: Readonly<NextParsedUrlQuery> query: Readonly<NextParsedUrlQuery>
}) { }): ParsedUrl {
let escaped = args.destination let escaped = args.destination
for (const param of Object.keys({ ...args.params, ...args.query })) { for (const param of Object.keys({ ...args.params, ...args.query })) {
if (!param) continue if (!param) continue
......
...@@ -6,11 +6,9 @@ import { removeTrailingSlash } from './remove-trailing-slash' ...@@ -6,11 +6,9 @@ import { removeTrailingSlash } from './remove-trailing-slash'
import { normalizeLocalePath } from '../../i18n/normalize-locale-path' import { normalizeLocalePath } from '../../i18n/normalize-locale-path'
import { removeBasePath } from '../../../../client/remove-base-path' import { removeBasePath } from '../../../../client/remove-base-path'
import { parseRelativeUrl, type ParsedRelativeUrl } from './parse-relative-url' import { parseRelativeUrl, type ParsedRelativeUrl } from './parse-relative-url'
import type { ParsedUrl } from './parse-url'
interface ParsedAs extends Omit<ParsedRelativeUrl, 'slashes'> { type ParsedAs = ParsedRelativeUrl | ParsedUrl
slashes: boolean | undefined
}
export default function resolveRewrites( export default function resolveRewrites(
asPath: string, asPath: string,
pages: string[], pages: string[],
......
import { createNext, FileRef } from 'e2e-utils' import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils' import { NextInstance } from 'e2e-utils'
import { check } from 'next-test-utils' import { retry } from 'next-test-utils'
import { join } from 'path' import { join } from 'path'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
...@@ -58,7 +58,9 @@ describe('i18n-ignore-redirect-source-locale with basepath', () => { ...@@ -58,7 +58,9 @@ describe('i18n-ignore-redirect-source-locale with basepath', () => {
'get redirected to the new page, from: %s to: sv', 'get redirected to the new page, from: %s to: sv',
async (locale) => { async (locale) => {
const browser = await webdriver(next.url, `basepath/${locale}/to-sv`) const browser = await webdriver(next.url, `basepath/${locale}/to-sv`)
await check(() => browser.elementById('current-locale').text(), 'sv') await retry(async () => {
expect(await browser.elementById('current-locale').text()).toBe('sv')
})
} }
) )
...@@ -66,7 +68,9 @@ describe('i18n-ignore-redirect-source-locale with basepath', () => { ...@@ -66,7 +68,9 @@ describe('i18n-ignore-redirect-source-locale with basepath', () => {
'get redirected to the new page, from: %s to: en', 'get redirected to the new page, from: %s to: en',
async (locale) => { async (locale) => {
const browser = await webdriver(next.url, `basepath/${locale}/to-en`) const browser = await webdriver(next.url, `basepath/${locale}/to-en`)
await check(() => browser.elementById('current-locale').text(), 'en') await retry(async () => {
expect(await browser.elementById('current-locale').text()).toBe('en')
})
} }
) )
...@@ -74,7 +78,9 @@ describe('i18n-ignore-redirect-source-locale with basepath', () => { ...@@ -74,7 +78,9 @@ describe('i18n-ignore-redirect-source-locale with basepath', () => {
'get redirected to the new page, from: %s to: /', 'get redirected to the new page, from: %s to: /',
async (locale) => { async (locale) => {
const browser = await webdriver(next.url, `basepath/${locale}/to-slash`) const browser = await webdriver(next.url, `basepath/${locale}/to-slash`)
await check(() => browser.elementById('current-locale').text(), 'en') await retry(async () => {
expect(await browser.elementById('current-locale').text()).toBe('en')
})
} }
) )
...@@ -82,10 +88,11 @@ describe('i18n-ignore-redirect-source-locale with basepath', () => { ...@@ -82,10 +88,11 @@ describe('i18n-ignore-redirect-source-locale with basepath', () => {
'get redirected to the new page, from and to: %s', 'get redirected to the new page, from and to: %s',
async (locale) => { async (locale) => {
const browser = await webdriver(next.url, `basepath/${locale}/to-same`) const browser = await webdriver(next.url, `basepath/${locale}/to-same`)
await check( await retry(async () => {
() => browser.elementById('current-locale').text(), expect(await browser.elementById('current-locale').text()).toBe(
locale === '' ? 'en' : locale.slice(1) locale === '' ? 'en' : locale.slice(1)
) )
})
} }
) )
}) })
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