Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract redirect utils into a separate file #39433

Merged
merged 1 commit into from Aug 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 1 addition & 2 deletions packages/next/build/index.ts
Expand Up @@ -24,13 +24,12 @@ import { fileExists } from '../lib/file-exists'
import { findPagesDir } from '../lib/find-pages-dir'
import loadCustomRoutes, {
CustomRoutes,
getRedirectStatus,
modifyRouteRegex,
normalizeRouteRegex,
Redirect,
Rewrite,
RouteType,
} from '../lib/load-custom-routes'
import { getRedirectStatus, modifyRouteRegex } from '../lib/redirect-status'
import { nonNullable } from '../lib/non-nullable'
import { recursiveDelete } from '../lib/recursive-delete'
import { verifyAndLint } from '../lib/verifyAndLint'
Expand Down
Expand Up @@ -8,7 +8,7 @@ import { renderToHTML } from '../../../../server/render'
import { tryGetPreviewData } from '../../../../server/api-utils/node'
import { denormalizePagePath } from '../../../../shared/lib/page-path/denormalize-page-path'
import { setLazyProp, getCookieParser } from '../../../../server/api-utils'
import { getRedirectStatus } from '../../../../lib/load-custom-routes'
import { getRedirectStatus } from '../../../../lib/redirect-status'
import getRouteNoAssetPath from '../../../../shared/lib/router/utils/get-route-from-asset-path'
import { PERMANENT_REDIRECT_STATUS } from '../../../../shared/lib/constants'
import RenderResult from '../../../../server/render-result'
Expand Down
@@ -1,3 +1,4 @@
import type { Rewrite, CustomRoutes } from '../../../lib/load-custom-routes'
import devalue from 'next/dist/compiled/devalue'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import {
Expand All @@ -13,10 +14,8 @@ import {
import { BuildManifest } from '../../../server/get-page-files'
import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint'
import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin'
import { Rewrite } from '../../../lib/load-custom-routes'
import { getSortedRoutes } from '../../../shared/lib/router/utils'
import { spans } from './profiling-plugin'
import { CustomRoutes } from '../../../lib/load-custom-routes'

type DeepMutable<T> = { -readonly [P in keyof T]: DeepMutable<T[P]> }

Expand Down
30 changes: 1 addition & 29 deletions packages/next/lib/load-custom-routes.ts
Expand Up @@ -3,9 +3,8 @@ import type { Token } from 'next/dist/compiled/path-to-regexp'

import chalk from './chalk'
import { escapeStringRegexp } from '../shared/lib/escape-regexp'
import { PERMANENT_REDIRECT_STATUS } from '../shared/lib/constants'
import { TEMPORARY_REDIRECT_STATUS } from '../shared/lib/constants'
import { tryToParsePath } from './try-to-parse-path'
import { allowedStatusCodes } from './redirect-status'

export type RouteHas =
| {
Expand Down Expand Up @@ -53,41 +52,14 @@ export type Redirect = {
}
)

export const allowedStatusCodes = new Set([301, 302, 303, 307, 308])
const allowedHasTypes = new Set(['header', 'cookie', 'query', 'host'])
const namedGroupsRegex = /\(\?<([a-zA-Z][a-zA-Z0-9]*)>/g

export function getRedirectStatus(route: {
statusCode?: number
permanent?: boolean
}): number {
return (
route.statusCode ||
(route.permanent ? PERMANENT_REDIRECT_STATUS : TEMPORARY_REDIRECT_STATUS)
)
}

export function normalizeRouteRegex(regex: string) {
// clean up un-necessary escaping from regex.source which turns / into \\/
return regex.replace(/\\\//g, '/')
}

// for redirects we restrict matching /_next and for all routes
// we add an optional trailing slash at the end for easier
// configuring between trailingSlash: true/false
export function modifyRouteRegex(regex: string, restrictedPaths?: string[]) {
if (restrictedPaths) {
regex = regex.replace(
/\^/,
`^(?!${restrictedPaths
.map((path) => path.replace(/\//g, '\\/'))
.join('|')})`
)
}
regex = regex.replace(/\$$/, '(?:\\/)?$')
return regex
}

function checkRedirect(route: Redirect): {
invalidParts: string[]
hadInvalidStatus: boolean
Expand Down
30 changes: 30 additions & 0 deletions packages/next/lib/redirect-status.ts
@@ -0,0 +1,30 @@
import { PERMANENT_REDIRECT_STATUS } from '../shared/lib/constants'
import { TEMPORARY_REDIRECT_STATUS } from '../shared/lib/constants'

export const allowedStatusCodes = new Set([301, 302, 303, 307, 308])

export function getRedirectStatus(route: {
statusCode?: number
permanent?: boolean
}): number {
return (
route.statusCode ||
(route.permanent ? PERMANENT_REDIRECT_STATUS : TEMPORARY_REDIRECT_STATUS)
)
}

// for redirects we restrict matching /_next and for all routes
// we add an optional trailing slash at the end for easier
// configuring between trailingSlash: true/false
export function modifyRouteRegex(regex: string, restrictedPaths?: string[]) {
if (restrictedPaths) {
regex = regex.replace(
/\^/,
`^(?!${restrictedPaths
.map((path) => path.replace(/\//g, '\\/'))
.join('|')})`
)
}
regex = regex.replace(/\$$/, '(?:\\/)?$')
return regex
}
4 changes: 2 additions & 2 deletions packages/next/server/base-server.ts
@@ -1,4 +1,4 @@
import { __ApiPreviewProps } from './api-utils'
import type { __ApiPreviewProps } from './api-utils'
import type { CustomRoutes } from '../lib/load-custom-routes'
import type { DomainLocale } from './config'
import type { DynamicRoutes, PageChecker, Route } from './router'
Expand Down Expand Up @@ -27,7 +27,7 @@ import type { PayloadOptions } from './send-payload'
import { join, resolve } from '../shared/lib/isomorphic/path'
import { parse as parseQs } from 'querystring'
import { format as formatUrl, parse as parseUrl } from 'url'
import { getRedirectStatus } from '../lib/load-custom-routes'
import { getRedirectStatus } from '../lib/redirect-status'
import {
NEXT_BUILTIN_DOCUMENT,
NEXT_CLIENT_SSR_ENTRY_SUFFIX,
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/config-shared.ts
@@ -1,6 +1,6 @@
import os from 'os'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import { Header, Redirect, Rewrite } from '../lib/load-custom-routes'
import type { Header, Redirect, Rewrite } from '../lib/load-custom-routes'
import {
ImageConfig,
ImageConfigComplete,
Expand Down
6 changes: 3 additions & 3 deletions packages/next/server/dev/hot-reloader.ts
@@ -1,10 +1,12 @@
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import type { NextConfigComplete } from '../config-shared'
import type { CustomRoutes } from '../../lib/load-custom-routes'
import { getOverlayMiddleware } from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware'
import { IncomingMessage, ServerResponse } from 'http'
import { WebpackHotMiddleware } from './hot-middleware'
import { join, relative, isAbsolute } from 'path'
import { UrlObject } from 'url'
import { webpack, StringXor } from 'next/dist/compiled/webpack/webpack'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import {
createEntrypoints,
createPagesMapping,
Expand Down Expand Up @@ -40,8 +42,6 @@ import {
withoutRSCExtensions,
isMiddlewareFilename,
} from '../../build/utils'
import { NextConfigComplete } from '../config-shared'
import { CustomRoutes } from '../../lib/load-custom-routes'
import { DecodeError } from '../../shared/lib/utils'
import { Span, trace } from '../../trace'
import { getProperError } from '../../lib/is-error'
Expand Down
5 changes: 1 addition & 4 deletions packages/next/server/render.tsx
Expand Up @@ -64,10 +64,7 @@ import { HtmlContext } from '../shared/lib/html-context'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import { getRequestMeta, NextParsedUrlQuery } from './request-meta'
import {
allowedStatusCodes,
getRedirectStatus,
} from '../lib/load-custom-routes'
import { allowedStatusCodes, getRedirectStatus } from '../lib/redirect-status'
import RenderResult from './render-result'
import isError from '../lib/is-error'
import {
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/server-route-utils.ts
Expand Up @@ -9,7 +9,7 @@ import type { Route } from './router'
import type { BaseNextRequest } from './base-http'
import type { ParsedUrlQuery } from 'querystring'

import { getRedirectStatus, modifyRouteRegex } from '../lib/load-custom-routes'
import { getRedirectStatus, modifyRouteRegex } from '../lib/redirect-status'
import { getPathMatch } from '../shared/lib/router/utils/path-match'
import {
compileNonPath,
Expand Down
@@ -1,7 +1,7 @@
import type { ParsedUrlQuery } from 'querystring'
import type { Rewrite } from '../../../../lib/load-custom-routes'
import { getPathMatch } from './path-match'
import { matchHas, prepareDestination } from './prepare-destination'
import { Rewrite } from '../../../../lib/load-custom-routes'
import { removeTrailingSlash } from './remove-trailing-slash'
import { normalizeLocalePath } from '../../i18n/normalize-locale-path'
import { removeBasePath } from '../../../../client/remove-base-path'
Expand Down