2020-06-30 06:06:39 +02:00
|
|
|
import { UrlObject } from 'url'
|
|
|
|
|
2020-07-13 18:08:12 +02:00
|
|
|
/**
|
|
|
|
* Removes the trailing slash of a path if there is one. Preserves the root path `/`.
|
|
|
|
*/
|
2020-06-30 06:06:39 +02:00
|
|
|
export function removePathTrailingSlash(path: string): string {
|
|
|
|
return path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path
|
|
|
|
}
|
|
|
|
|
2020-07-13 18:08:12 +02:00
|
|
|
/**
|
|
|
|
* Normalizes the trailing slash of a path according to the `trailingSlash` option
|
|
|
|
* in `next.config.js`.
|
|
|
|
*/
|
2020-06-30 06:06:39 +02:00
|
|
|
const normalizePathTrailingSlash = process.env.__NEXT_TRAILING_SLASH
|
|
|
|
? (path: string): string => {
|
|
|
|
if (/\.[^/]+\/?$/.test(path)) {
|
|
|
|
return removePathTrailingSlash(path)
|
|
|
|
} else if (path.endsWith('/')) {
|
|
|
|
return path
|
|
|
|
} else {
|
|
|
|
return path + '/'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
: removePathTrailingSlash
|
|
|
|
|
2020-07-13 18:08:12 +02:00
|
|
|
/**
|
|
|
|
* Normalizes the trailing slash of the path of a parsed url. Non-destructive.
|
|
|
|
*/
|
|
|
|
export function normalizeTrailingSlash(url: URL): URL
|
|
|
|
export function normalizeTrailingSlash(url: UrlObject): UrlObject
|
|
|
|
export function normalizeTrailingSlash(url: UrlObject | URL): UrlObject | URL {
|
2020-06-30 06:06:39 +02:00
|
|
|
const normalizedPath =
|
|
|
|
url.pathname && normalizePathTrailingSlash(url.pathname)
|
|
|
|
return url.pathname === normalizedPath
|
|
|
|
? url
|
2020-07-13 18:08:12 +02:00
|
|
|
: url instanceof URL
|
|
|
|
? Object.assign(new URL(url.href), { pathname: normalizedPath })
|
2020-06-30 06:06:39 +02:00
|
|
|
: Object.assign({}, url, { pathname: normalizedPath })
|
|
|
|
}
|