2022-04-30 13:19:27 +02:00
|
|
|
import { normalizePathSep } from './normalize-path-sep'
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Removes the file extension for a page and the trailing `index` if it exists
|
|
|
|
* making sure to not return an empty string. The page head is not touched
|
|
|
|
* and returned as it is passed. Examples:
|
|
|
|
* - `/foo/bar/baz/index.js` -> `/foo/bar/baz`
|
|
|
|
* - `/foo/bar/baz.js` -> `/foo/bar/baz`
|
|
|
|
*
|
|
|
|
* @param pagePath A page to a page file (absolute or relative)
|
2022-05-19 17:46:21 +02:00
|
|
|
* @param options.extensions Extensions allowed for the page.
|
|
|
|
* @param options.keepIndex When true the trailing `index` is _not_ removed.
|
2022-04-30 13:19:27 +02:00
|
|
|
*/
|
2022-05-03 12:37:23 +02:00
|
|
|
export function removePagePathTail(
|
|
|
|
pagePath: string,
|
2022-05-19 17:46:21 +02:00
|
|
|
options: {
|
|
|
|
extensions: string[]
|
|
|
|
keepIndex?: boolean
|
|
|
|
}
|
2022-05-03 12:37:23 +02:00
|
|
|
) {
|
|
|
|
pagePath = normalizePathSep(pagePath).replace(
|
2022-05-19 17:46:21 +02:00
|
|
|
new RegExp(`\\.+(?:${options.extensions.join('|')})$`),
|
2022-05-03 12:37:23 +02:00
|
|
|
''
|
2022-04-30 13:19:27 +02:00
|
|
|
)
|
2022-05-03 12:37:23 +02:00
|
|
|
|
2022-05-19 17:46:21 +02:00
|
|
|
if (options.keepIndex !== true) {
|
2022-05-03 12:37:23 +02:00
|
|
|
pagePath = pagePath.replace(/\/index$/, '') || '/'
|
|
|
|
}
|
|
|
|
|
|
|
|
return pagePath
|
2022-04-30 13:19:27 +02:00
|
|
|
}
|