rsnext/packages/next/server/lib/find-page-file.ts
Shu Ding 1c1a4de0e2
Refactor base server to remove native dependencies (#33499)
Part of #31506, this PR removes `loadEnvConfig` and `chalk` from the base server while keeping the same behavior for the node server.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
2022-01-20 21:25:44 +00:00

65 lines
2 KiB
TypeScript

import { join, sep as pathSeparator, normalize } from 'path'
import chalk from '../../lib/chalk'
import { warn } from '../../build/output/log'
import { promises } from 'fs'
import { denormalizePagePath } from '../normalize-page-path'
import { fileExists } from '../../lib/file-exists'
async function isTrueCasePagePath(pagePath: string, pagesDir: string) {
const pageSegments = normalize(pagePath).split(pathSeparator).filter(Boolean)
const segmentExistsPromises = pageSegments.map(async (segment, i) => {
const segmentParentDir = join(pagesDir, ...pageSegments.slice(0, i))
const parentDirEntries = await promises.readdir(segmentParentDir)
return parentDirEntries.includes(segment)
})
return (await Promise.all(segmentExistsPromises)).every(Boolean)
}
export async function findPageFile(
rootDir: string,
normalizedPagePath: string,
pageExtensions: string[]
): Promise<string | null> {
const foundPagePaths: string[] = []
const page = denormalizePagePath(normalizedPagePath)
for (const extension of pageExtensions) {
if (!normalizedPagePath.endsWith('/index')) {
const relativePagePath = `${page}.${extension}`
const pagePath = join(rootDir, relativePagePath)
if (await fileExists(pagePath)) {
foundPagePaths.push(relativePagePath)
}
}
const relativePagePathWithIndex = join(page, `index.${extension}`)
const pagePathWithIndex = join(rootDir, relativePagePathWithIndex)
if (await fileExists(pagePathWithIndex)) {
foundPagePaths.push(relativePagePathWithIndex)
}
}
if (foundPagePaths.length < 1) {
return null
}
if (!(await isTrueCasePagePath(foundPagePaths[0], rootDir))) {
return null
}
if (foundPagePaths.length > 1) {
warn(
`Duplicate page detected. ${chalk.cyan(
join('pages', foundPagePaths[0])
)} and ${chalk.cyan(
join('pages', foundPagePaths[1])
)} both resolve to ${chalk.cyan(normalizedPagePath)}.`
)
}
return foundPagePaths[0]
}