2018-03-30 13:08:09 +00:00
|
|
|
import {join, posix} from 'path'
|
|
|
|
import {PAGES_MANIFEST} from '../lib/constants'
|
2018-02-05 17:46:36 +00:00
|
|
|
|
2018-02-13 13:27:52 +00:00
|
|
|
export function pageNotFoundError (page) {
|
|
|
|
const err = new Error(`Cannot find module for page: ${page}`)
|
|
|
|
err.code = 'ENOENT'
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
export function normalizePagePath (page) {
|
|
|
|
// If the page is `/` we need to append `/index`, otherwise the returned directory root will be bundles instead of pages
|
|
|
|
if (page === '/') {
|
|
|
|
page = '/index'
|
|
|
|
}
|
|
|
|
|
|
|
|
// Resolve on anything that doesn't start with `/`
|
|
|
|
if (page[0] !== '/') {
|
|
|
|
page = `/${page}`
|
|
|
|
}
|
|
|
|
|
|
|
|
// Throw when using ../ etc in the pathname
|
2018-03-30 13:08:09 +00:00
|
|
|
const resolvedPage = posix.normalize(page)
|
2018-02-13 13:27:52 +00:00
|
|
|
if (page !== resolvedPage) {
|
|
|
|
throw new Error('Requested and resolved page mismatch')
|
|
|
|
}
|
|
|
|
|
|
|
|
return page
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getPagePath (page, {dir, dist}) {
|
2018-03-30 13:08:09 +00:00
|
|
|
const serverBuildPath = join(dir, dist, 'dist')
|
|
|
|
const pagesManifest = require(join(serverBuildPath, PAGES_MANIFEST))
|
2018-02-13 13:27:52 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
page = normalizePagePath(page)
|
|
|
|
} catch (err) {
|
|
|
|
console.error(err)
|
|
|
|
throw pageNotFoundError(page)
|
|
|
|
}
|
|
|
|
|
2018-03-30 13:08:09 +00:00
|
|
|
if (!pagesManifest[page]) {
|
2018-02-13 13:27:52 +00:00
|
|
|
throw pageNotFoundError(page)
|
|
|
|
}
|
|
|
|
|
2018-03-30 13:08:09 +00:00
|
|
|
return join(serverBuildPath, pagesManifest[page])
|
2018-02-13 13:27:52 +00:00
|
|
|
}
|
|
|
|
|
2018-03-09 16:14:30 +00:00
|
|
|
export default async function requirePage (page, {dir, dist}) {
|
2018-03-30 13:08:09 +00:00
|
|
|
const pagePath = getPagePath(page, {dir, dist})
|
2018-03-09 16:14:30 +00:00
|
|
|
return require(pagePath)
|
2018-02-05 17:46:36 +00:00
|
|
|
}
|