Unverified Commit 0b12e2e8 authored by Jan Potoms's avatar Jan Potoms Committed by GitHub

Improve error for invalid page configurations (#10441)

* Remove any type and fix edge cases

Removed the "as any" and use the @babel/types typeguards instead. This revealed some edge cases that would just error.

* Remove ts-ignore
Co-authored-by: 's avatarJoe Haddad <timer150@gmail.com>
parent 44e40d4f
...@@ -2,7 +2,6 @@ import { NodePath, PluginObj } from '@babel/core' ...@@ -2,7 +2,6 @@ import { NodePath, PluginObj } from '@babel/core'
import * as BabelTypes from '@babel/types' import * as BabelTypes from '@babel/types'
import { PageConfig } from 'next/types' import { PageConfig } from 'next/types'
const configKeys = new Set(['amp'])
const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__' const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__'
// replace program path with just a variable with the drop identifier // replace program path with just a variable with the drop identifier
...@@ -26,6 +25,12 @@ function replaceBundle(path: any, t: typeof BabelTypes) { ...@@ -26,6 +25,12 @@ function replaceBundle(path: any, t: typeof BabelTypes) {
) )
} }
function errorMessage(state: any, details: string) {
const pageName =
(state.filename || '').split(state.cwd || '').pop() || 'unknown'
return `Invalid page config export found. ${details} in file ${pageName}. See: https://err.sh/zeit/next.js/invalid-page-config`
}
interface ConfigState { interface ConfigState {
bundleDropped?: boolean bundleDropped?: boolean
} }
...@@ -50,32 +55,51 @@ export default function nextPageConfig({ ...@@ -50,32 +55,51 @@ export default function nextPageConfig({
return return
} }
const { declarations } = path.node.declaration as any if (!BabelTypes.isVariableDeclaration(path.node.declaration)) {
const config: PageConfig = {}
if (!declarations) {
return return
} }
const { declarations } = path.node.declaration
const config: PageConfig = {}
for (const declaration of declarations) { for (const declaration of declarations) {
if (declaration.id.name !== 'config') { if (
!BabelTypes.isIdentifier(declaration.id, { name: 'config' })
) {
continue continue
} }
if (declaration.init.type !== 'ObjectExpression') { if (!BabelTypes.isObjectExpression(declaration.init)) {
const pageName = const got = declaration.init
(state.filename || '').split(state.cwd || '').pop() || ? declaration.init.type
'unknown' : 'undefined'
throw new Error( throw new Error(
`Invalid page config export found. Expected object but got ${declaration.init.type} in file ${pageName}. See: https://err.sh/zeit/next.js/invalid-page-config` errorMessage(state, `Expected object but got ${got}`)
) )
} }
for (const prop of declaration.init.properties) { for (const prop of declaration.init.properties) {
if (BabelTypes.isSpreadElement(prop)) {
throw new Error(
errorMessage(state, `Property spread is not allowed`)
)
}
const { name } = prop.key const { name } = prop.key
if (configKeys.has(name)) { if (BabelTypes.isIdentifier(prop.key, { name: 'amp' })) {
// @ts-ignore if (!BabelTypes.isObjectProperty(prop)) {
config[name] = prop.value.value throw new Error(
errorMessage(state, `Invalid property "${name}"`)
)
}
if (
!BabelTypes.isBooleanLiteral(prop.value) &&
!BabelTypes.isStringLiteral(prop.value)
) {
throw new Error(
errorMessage(state, `Invalid value for "${name}"`)
)
}
config.amp = prop.value.value as PageConfig['amp']
} }
} }
} }
......
import { config as hello } from '../something' import { config as hello } from '../something'
import { config as world } from '../config' import { config as world } from '../config'
// export const config = 'hello world'
export default () => ( export default () => (
<p> <p>
{hello} {world} {hello} {world}
......
// export const config = { amp() {} }
export default () => <p>hello world</p>
const amp = 'hybrid'
// export const config = { amp }
export default () => <p>hello ${amp}</p>
// export let config
export default () => <p>hello world</p>
const props = { amp: true }
// export const config = { ...props }
export default () => <p>{props}</p>
// export const config = 'hello world'
export default () => <p>hello world</p>
...@@ -5,20 +5,79 @@ import { join } from 'path' ...@@ -5,20 +5,79 @@ import { join } from 'path'
import { nextBuild } from 'next-test-utils' import { nextBuild } from 'next-test-utils'
const appDir = join(__dirname, '..') const appDir = join(__dirname, '..')
const indexPage = join(appDir, 'pages/index.js')
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2
async function uncommentExport(page) {
const pagePath = join(appDir, 'pages', page)
const origContent = await fs.readFile(pagePath, 'utf8')
const newContent = origContent.replace('// export', 'export')
await fs.writeFile(pagePath, newContent, 'utf8')
return async () => {
await fs.writeFile(pagePath, origContent, 'utf8')
}
}
describe('Page Config', () => { describe('Page Config', () => {
it('builds without error when export const config is used outside page', async () => { it('builds without error when export const config is used outside page', async () => {
const { stderr } = await nextBuild(appDir, undefined, { stderr: true }) const { stderr } = await nextBuild(appDir, undefined, { stderr: true })
expect(stderr).not.toMatch(/Failed to compile\./) expect(stderr).not.toMatch(/Failed to compile\./)
}) })
it('shows valid error on invalid page config', async () => { it('shows valid error when page config is a string', async () => {
const origContent = await fs.readFile(indexPage, 'utf8') const reset = await uncommentExport('invalid/string-config.js')
const newContent = origContent.replace('// export', 'export')
await fs.writeFile(indexPage, newContent, 'utf8') try {
const { stderr } = await nextBuild(appDir, undefined, { stderr: true })
expect(stderr).toMatch(
/https:\/\/err\.sh\/zeit\/next\.js\/invalid-page-config/
)
} finally {
await reset()
}
})
it('shows valid error when page config has no init', async () => {
const reset = await uncommentExport('invalid/no-init.js')
try {
const { stderr } = await nextBuild(appDir, undefined, { stderr: true })
expect(stderr).toMatch(
/https:\/\/err\.sh\/zeit\/next\.js\/invalid-page-config/
)
} finally {
await reset()
}
})
it('shows error when page config has spread properties', async () => {
const reset = await uncommentExport('invalid/spread-config.js')
try {
const { stderr } = await nextBuild(appDir, undefined, { stderr: true })
expect(stderr).toMatch(
/https:\/\/err\.sh\/zeit\/next\.js\/invalid-page-config/
)
} finally {
await reset()
}
})
it('shows error when page config has invalid properties', async () => {
const reset = await uncommentExport('invalid/invalid-property.js')
try {
const { stderr } = await nextBuild(appDir, undefined, { stderr: true })
expect(stderr).toMatch(
/https:\/\/err\.sh\/zeit\/next\.js\/invalid-page-config/
)
} finally {
await reset()
}
})
it('shows error when page config has invalid property value', async () => {
const reset = await uncommentExport('invalid/invalid-value.js')
try { try {
const { stderr } = await nextBuild(appDir, undefined, { stderr: true }) const { stderr } = await nextBuild(appDir, undefined, { stderr: true })
...@@ -26,7 +85,7 @@ describe('Page Config', () => { ...@@ -26,7 +85,7 @@ describe('Page Config', () => {
/https:\/\/err\.sh\/zeit\/next\.js\/invalid-page-config/ /https:\/\/err\.sh\/zeit\/next\.js\/invalid-page-config/
) )
} finally { } finally {
await fs.writeFile(indexPage, origContent, 'utf8') await reset()
} }
}) })
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment