rsnext/packages/next/build/babel/plugins/next-page-config.ts
JJ Kasper 85e720a092 Add experimental SPR support (#8832)
* initial commit for SPRv2

* Add initial SPR cache handling

* update SPR handling

* Implement SPR handling in render

* Update tests, handle caching with serverless next
start, add TODOs, and update manifest generating

* Handle no prerender-manifest from not being used

* Fix url.parse error

* Apply suggestions from code review

Co-Authored-By: Joe Haddad <joe.haddad@zeit.co>

* Replace set with constants in next-page-config

* simplify sprStatus.used

* Add error if getStaticProps is used with getInitialProps

* Remove stale TODO

* Update revalidate values in SPR cache for non-seeded routes

* Apply suggestions from code review

* Remove concurrency type

* Rename variable for clarity

* Add copying prerender files during export

* Add comment for clarity

* Fix exporting

* Update comment

* Add additional note

* Rename variable

* Update to not re-export SPR pages from build

* Hard navigate when fetching data fails

* Remove default extension

* Add brackets

* Add checking output files to prerender tests

* Adjust export move logic

* Clarify behavior of export aggregation

* Update variable names for clarity

* Update tests

* Add comment

* s/an oxymoron/contradictory/

* rename

* Extract error case

* Add tests for exporting SPR pages and update
/_next/data endpoint to end with .json

* Relocate variable

* Adjust route building

* Rename to unstable

* Rename unstable_getStaticParams

* Fix linting

* Only add this when a data request

* Update prerender data tests

* s/isServerless/isLikeServerless/

* Don't rely on query for `next start` in serverless mode

* Rename var

* Update renderedDuringBuild check

* Add test for dynamic param with bracket

* Fix serverless next start handling

* remove todo

* Adjust comment

* Update calculateRevalidate

* Remove cache logic from render.tsx

* Remove extra imports

* Move SPR cache logic to next-server

* Remove old isDynamic prop

* Add calling App getInitialProps for SPR pages

* Update revalidate logic

* Add isStale to SprCacheValue

* Update headers for SPR

* add awaiting pendingRevalidation

* Dont return null for revalidation render

* Adjust logic

* Be sure to remove coalesced render

* Fix data for serverless

* Create a method coalescing utility

* Remove TODO

* Extract send payload helper

* Wrap in-line

* Move around some code

* Add tests for de-duping and revalidating

* Update prerender manifest test
2019-09-24 10:50:04 +02:00

150 lines
4.6 KiB
TypeScript

import { PluginObj } from '@babel/core'
import { NodePath } from '@babel/traverse'
import * as BabelTypes from '@babel/types'
import { PageConfig } from '../../../types'
export const dropBundleIdentifier = '__NEXT_DROP_CLIENT_FILE__'
export const sprStatus = { used: false }
const configKeys = new Set(['amp'])
const pageComponentVar = '__NEXT_COMP'
// this value can't be optimized by terser so the shorter the better
const prerenderId = '__NEXT_SPR'
const EXPORT_NAME_GET_STATIC_PROPS = 'unstable_getStaticProps'
const EXPORT_NAME_GET_STATIC_PARAMS = 'unstable_getStaticParams'
// replace program path with just a variable with the drop identifier
function replaceBundle(path: any, t: typeof BabelTypes) {
path.parentPath.replaceWith(
t.program(
[
t.variableDeclaration('const', [
t.variableDeclarator(
t.identifier('config'),
t.assignmentExpression(
'=',
t.identifier(dropBundleIdentifier),
t.stringLiteral(`${dropBundleIdentifier} ${Date.now()}`)
)
),
]),
],
[]
)
)
}
interface ConfigState {
isPrerender?: boolean
bundleDropped?: boolean
}
// config to parsing pageConfig for client bundles
export default function nextPageConfig({
types: t,
}: {
types: typeof BabelTypes
}): PluginObj {
return {
visitor: {
Program: {
enter(path, state: ConfigState) {
path.traverse(
{
ExportNamedDeclaration(
path: NodePath<BabelTypes.ExportNamedDeclaration>,
state: any
) {
if (state.bundleDropped || !path.node.declaration) {
return
}
const { declarations, id } = path.node.declaration as any
const config: PageConfig = {}
// drop SSR Exports for client bundles
if (
id &&
(id.name === EXPORT_NAME_GET_STATIC_PROPS ||
id.name === EXPORT_NAME_GET_STATIC_PARAMS)
) {
if (id.name === EXPORT_NAME_GET_STATIC_PROPS) {
state.isPrerender = true
sprStatus.used = true
}
path.remove()
return
}
if (!declarations) {
return
}
for (const declaration of declarations) {
if (declaration.id.name !== 'config') {
continue
}
if (declaration.init.type !== 'ObjectExpression') {
const pageName =
(state.filename || '').split(state.cwd || '').pop() ||
'unknown'
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`
)
}
for (const prop of declaration.init.properties) {
const { name } = prop.key
if (configKeys.has(name)) {
// @ts-ignore
config[name] = prop.value.value
}
}
}
if (config.amp === true) {
replaceBundle(path, t)
state.bundleDropped = true
return
}
// remove export const config from bundle
path.remove()
},
},
state
)
},
},
ExportDefaultDeclaration(path, state: ConfigState) {
if (!state.isPrerender) {
return
}
const prev = t.cloneDeep(path.node.declaration)
// workaround to allow assigning a ClassDeclaration to a variable
// babel throws error without
if (prev.type.endsWith('Declaration')) {
prev.type = prev.type.replace(/Declaration$/, 'Expression') as any
}
path.insertBefore([
t.variableDeclaration('const', [
t.variableDeclarator(t.identifier(pageComponentVar), prev as any),
]),
t.assignmentExpression(
'=',
t.memberExpression(
t.identifier(pageComponentVar),
t.identifier(prerenderId)
),
t.booleanLiteral(true)
),
])
path.node.declaration = t.identifier(pageComponentVar)
},
},
}
}