Unverified Commit 7dd77fea authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update build-complete for adapter API (#82452)

This adds some additional API surface for `build-complete` adapter hook.
Wiring up prerenders and additional configs.
parent 46709a2a
...@@ -774,5 +774,6 @@ ...@@ -774,5 +774,6 @@
"773": "Missing workStore in createPrerenderParamsForClientSegment", "773": "Missing workStore in createPrerenderParamsForClientSegment",
"774": "Route %s used %s outside of a Server Component. This is not allowed.", "774": "Route %s used %s outside of a Server Component. This is not allowed.",
"775": "Node.js instrumentation extensions should not be loaded in the Edge runtime.", "775": "Node.js instrumentation extensions should not be loaded in the Edge runtime.",
"776": "`unstable_isUnrecognizedActionError` can only be used on the client." "776": "`unstable_isUnrecognizedActionError` can only be used on the client.",
"777": "Invariant: failed to find source route %s for prerender %s"
} }
...@@ -372,39 +372,6 @@ type ManifestBuiltRoute = { ...@@ -372,39 +372,6 @@ type ManifestBuiltRoute = {
regex: string regex: string
} }
export enum RouteType {
/**
* `PAGES` represents all the React pages that are under `pages/`.
*/
PAGES = 'PAGES',
/**
* `PAGES_API` represents all the API routes under `pages/api/`.
*/
PAGES_API = 'PAGES_API',
/**
* `APP_PAGE` represents all the React pages that are under `app/` with the
* filename of `page.{j,t}s{,x}`.
*/
APP_PAGE = 'APP_PAGE',
/**
* `APP_ROUTE` represents all the API routes and metadata routes that are under `app/` with the
* filename of `route.{j,t}s{,x}`.
*/
APP_ROUTE = 'APP_ROUTE',
/**
* `IMAGE` represents all the images that are generated by `next/image`.
*/
// IMAGE = 'IMAGE',
/**
* `STATIC_FILE` represents a static file (ie /_next/static)
*/
STATIC_FILE = 'STATIC_FILE',
MIDDLEWARE = 'MIDDLEWARE',
}
export type ManifestRewriteRoute = ManifestBuiltRoute & Rewrite export type ManifestRewriteRoute = ManifestBuiltRoute & Rewrite
export type ManifestRedirectRoute = ManifestBuiltRoute & Redirect export type ManifestRedirectRoute = ManifestBuiltRoute & Redirect
export type ManifestHeaderRoute = ManifestBuiltRoute & Header export type ManifestHeaderRoute = ManifestBuiltRoute & Header
......
import os from 'os' import os from 'os'
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type { Header, Redirect, Rewrite } from '../lib/load-custom-routes' import type {
Header,
Redirect,
Rewrite,
RouteHas,
} from '../lib/load-custom-routes'
import { imageConfigDefault } from '../shared/lib/image-config' import { imageConfigDefault } from '../shared/lib/image-config'
import type { import type {
ImageConfig, ImageConfig,
...@@ -17,10 +22,13 @@ import type { ...@@ -17,10 +22,13 @@ import type {
ManifestRewriteRoute, ManifestRewriteRoute,
ManifestHeaderRoute, ManifestHeaderRoute,
ManifestRedirectRoute, ManifestRedirectRoute,
RouteType,
ManifestRoute, ManifestRoute,
} from '../build' } from '../build'
import { isStableBuild } from '../shared/lib/canary-only' import { isStableBuild } from '../shared/lib/canary-only'
import type { RenderingMode } from '../build/rendering-mode'
import type { Revalidate } from './lib/cache-control'
import type { AdapterOutputType } from '../shared/lib/constants'
import type { MiddlewareMatcher } from '../build/analysis/get-page-static-info'
export type NextConfigComplete = Required<NextConfig> & { export type NextConfigComplete = Required<NextConfig> & {
images: Required<ImageConfigComplete> images: Required<ImageConfigComplete>
...@@ -35,19 +43,112 @@ export type NextConfigComplete = Required<NextConfig> & { ...@@ -35,19 +43,112 @@ export type NextConfigComplete = Required<NextConfig> & {
} }
export type AdapterOutputs = Array<{ export type AdapterOutputs = Array<{
/**
* id is a unique identifier for the output
*/
id: string id: string
fallbackID?: string /**
runtime?: 'nodejs' | 'edge' * pathname is the URL path that the output is meant to
* be routable to at e.g. /blog/[slug] or /_next/static/chunks/chunk.js
*/
pathname: string pathname: string
allowQuery?: string[] /**
* runtime for the route, this doesn't apply for prerender or static
*/
runtime?: 'nodejs' | 'edge'
/**
* config related to the route
*/
config?: { config?: {
/**
* maxDuration is a segment config to signal the max
* execution duration a route should be allowed before
* it's timed out
*/
maxDuration?: number maxDuration?: number
expiration?: number /**
revalidate?: number * preferredRegion is a segment config to signal deployment
* region preferences to the provider being used
*/
preferredRegion?: string | string[]
/**
* allowQuery is the allowed query values to be passed
* to an ISR function and what should be considered for the cacheKey
* e.g. for /blog/[slug], "slug" is the only allowQuery
*/
allowQuery?: string[]
/**
* allowHeader is the allowed headers to be passed to an
* ISR function to prevent accidentally poisoning the cache
* from leaking additional information that can impact the render
*/
allowHeader?: string[]
/**
* bypass for is a list of has conditions the cache
* should be bypassed and invoked directly e.g. action header
*/
bypassFor?: RouteHas[]
/**
* renderingMode signals PPR or not for a prerender
*/
renderingMode?: RenderingMode
/**
* matchers are the configured matchers for middleware
*/
matchers?: MiddlewareMatcher[]
}
/**
* For prerenders the parent output is the originating
* page that the prerender is created from
*/
parentOutputId?: string
/**
* fallback is initial cache data generated during build for a prerender
*/
fallback?: {
/**
* path to the fallback file can be HTML/JSON/RSC
*/
filePath: string
/**
* initialStatus is the status code that should be applied
* when serving the fallback
*/
initialStatus?: number
/**
* initialHeaders are the headers that should be sent when
* serving the fallback
*/
initialHeaders?: Record<string, string | string[]>
/**
* initial expiration is how long until the fallback entry
* is considered expired and no longer valid to serve
*/
initialExpiration?: number
/**
* initial revalidate is how long until the fallback is
* considered stale and should be revalidated
*/
initialRevalidate?: Revalidate
} }
/**
* assets are all necessary traced assets that could be
* loaded by the output to handle a request e.g. traced
* node_modules or necessary manifests for Next.js
*/
assets?: Record<string, string> assets?: Record<string, string>
filePath: string /**
type: RouteType * filePath is present for all cases except a Prerender
* which may or may not have a fallback (initial cache entry).
* The parent output will have a filePath for a prerender though
*/
filePath?: string
/**
* type of output
*/
type: AdapterOutputType
}> }>
export interface NextAdapter { export interface NextAdapter {
......
...@@ -12,6 +12,45 @@ export const COMPILER_NAMES = { ...@@ -12,6 +12,45 @@ export const COMPILER_NAMES = {
export type CompilerNameValues = ValueOf<typeof COMPILER_NAMES> export type CompilerNameValues = ValueOf<typeof COMPILER_NAMES>
export enum AdapterOutputType {
/**
* `PAGES` represents all the React pages that are under `pages/`.
*/
PAGES = 'PAGES',
/**
* `PAGES_API` represents all the API routes under `pages/api/`.
*/
PAGES_API = 'PAGES_API',
/**
* `APP_PAGE` represents all the React pages that are under `app/` with the
* filename of `page.{j,t}s{,x}`.
*/
APP_PAGE = 'APP_PAGE',
/**
* `APP_ROUTE` represents all the API routes and metadata routes that are under `app/` with the
* filename of `route.{j,t}s{,x}`.
*/
APP_ROUTE = 'APP_ROUTE',
/**
* `PRERENDER` represents an ISR enabled route that might
* have a seeded cache entry or fallback generated during build
*/
PRERENDER = 'PRERENDER',
/**
* `STATIC_FILE` represents a static file (ie /_next/static)
*/
STATIC_FILE = 'STATIC_FILE',
/**
* `MIDDLEWARE` represents the middleware output if present
*/
MIDDLEWARE = 'MIDDLEWARE',
}
export const COMPILER_INDEXES: { export const COMPILER_INDEXES: {
[compilerKey in CompilerNameValues]: number [compilerKey in CompilerNameValues]: number
} = { } = {
......
import fs from 'fs'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
import { AdapterOutputType } from 'next/constants'
describe('adapter-config', () => { describe('adapter-config', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -6,14 +9,89 @@ describe('adapter-config', () => { ...@@ -6,14 +9,89 @@ describe('adapter-config', () => {
}) })
it('should apply modifyConfig from adapter', async () => { it('should apply modifyConfig from adapter', async () => {
// we apply basePath /docs so ensure that applied // we apply basePath of "/docs" to ensure modify was called
const res = await next.fetch('/') const res = await next.fetch('/')
expect(res.status).toBe(404) expect(res.status).toBe(404)
const res2 = await next.fetch('/docs') const res2 = await next.fetch('/docs/node-pages')
expect(res2.status).toBe(200) expect(res2.status).toBe(200)
expect(await res2.text()).toContain('hello world') expect(await res2.text()).toContain('hello world')
expect(next.cliOutput).toContain('called modify config in adapter') expect(next.cliOutput).toContain('called modify config in adapter')
}) })
it('should call onBuildComplete with correct context', async () => {
expect(next.cliOutput).toContain('onBuildComplete called')
const buildContext: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
const outputMap = new Map<string, (typeof buildContext.outputs)[0]>()
const prerenderOutputs: typeof buildContext.outputs = []
const staticOutputs: typeof buildContext.outputs = []
const nodeOutputs: typeof buildContext.outputs = []
const edgeOutputs: typeof buildContext.outputs = []
for (const output of buildContext.outputs) {
if (outputMap.has(output.id)) {
throw new Error(
`multiple outputs with same ID ${JSON.stringify(
{
first: outputMap.get(output.id),
second: output,
},
null,
2
)}`
)
}
switch (output.type) {
case AdapterOutputType.PRERENDER: {
prerenderOutputs.push(output)
break
}
case AdapterOutputType.STATIC_FILE: {
staticOutputs.push(output)
break
}
case AdapterOutputType.APP_PAGE:
case AdapterOutputType.APP_ROUTE:
case AdapterOutputType.PAGES:
case AdapterOutputType.PAGES_API: {
if (output.runtime === 'nodejs') {
nodeOutputs.push(output)
} else if (output.runtime === 'edge') {
edgeOutputs.push(output)
} else {
throw new Error(
`unrecognized runtime on ${JSON.stringify(output, null, 2)}`
)
}
break
}
default: {
throw new Error(`unrecognized output type ${output.type}`)
}
}
}
expect(nodeOutputs.length).toBeGreaterThan(0)
expect(edgeOutputs.length).toBeGreaterThan(0)
expect(staticOutputs.length).toBeGreaterThan(0)
expect(prerenderOutputs.length).toBeGreaterThan(0)
for (const output of staticOutputs) {
expect(output.id).toBeTruthy()
expect(output.pathname).toStartWith('/_next/static')
expect(fs.existsSync(output.filePath)).toBe(true)
}
expect(buildContext.routes).toEqual({
dynamicRoutes: expect.toBeArray(),
rewrites: expect.toBeObject(),
redirects: expect.toBeArray(),
headers: expect.toBeArray(),
})
})
}) })
export const runtime = 'edge'
export default function Page() {
return (
<>
<p>/edge-app</p>
<p>now: {Date.now()}</p>
</>
)
}
import { NextRequest, NextResponse } from 'next/server'
export const runtime = 'edge'
export function GET(req: NextRequest) {
console.log(req.url.toString())
return NextResponse.json({
now: Date.now(),
})
}
export const dynamic = 'force-static'
export function generateStaticParams() {
return [{ slug: 'first' }]
}
export default async function Page({ params }) {
const { slug } = await params
return (
<>
<p>/isr-app/[slug]</p>
<p>now: {Date.now()}</p>
<p>slug: {slug}</p>
</>
)
}
export default function Page() {
return (
<>
<p>/isr-app</p>
<p>now: {Date.now()}</p>
</>
)
}
import { NextRequest, NextResponse } from 'next/server'
export const dynamic = 'force-static'
export function generateStaticParams() {
return [{ slug: 'first' }]
}
export async function GET(req: NextRequest, { params }) {
console.log(req.url.toString(), await params)
return NextResponse.json({
now: Date.now(),
})
}
import { NextRequest, NextResponse } from 'next/server'
export const dynamic = 'force-static'
export async function GET(req: NextRequest, { params }) {
console.log(req.url.toString(), await params)
return NextResponse.json({
now: Date.now(),
})
}
export default function Layout({ children }) {
return (
<html lang="en">
<head />
<body>{children}</body>
</html>
)
}
export const dynamic = 'force-dynamic'
export default function Page() {
return (
<>
<p>/node-app</p>
<p>now: {Date.now()}</p>
</>
)
}
import { NextRequest, NextResponse } from 'next/server'
export function GET(req: NextRequest) {
console.log(req.url.toString())
return NextResponse.json({
now: Date.now(),
})
}
import fs from 'fs'
// @ts-check // @ts-check
/** @type {import('next').NextAdapter } */ /** @type {import('next').NextAdapter } */
const myAdapter = { const myAdapter = {
...@@ -7,6 +9,14 @@ const myAdapter = { ...@@ -7,6 +9,14 @@ const myAdapter = {
config.basePath = '/docs' config.basePath = '/docs'
return config return config
}, },
onBuildComplete: async (ctx) => {
console.log('onBuildComplete called')
await fs.promises.writeFile(
'build-complete.json',
JSON.stringify(ctx, null, 2)
)
},
} }
export default myAdapter export default myAdapter
import { NextRequest, NextResponse } from 'next/server'
export const config = {
runtime: 'edge',
}
export default function handler(req: NextRequest) {
return NextResponse.json({ now: Date.now() })
}
import { NextApiRequest, NextApiResponse } from 'next/dist/types'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
console.log(req.url)
res.json({ now: Date.now() })
}
export const config = {
runtime: 'experimental-edge',
}
export default function Page() {
return (
<>
<p>/edge-pages</p>
<p>now: {Date.now()}</p>
</>
)
}
export default function Page() {
return <p>hello world</p>
}
export function getStaticPaths() {
return {
paths: [
{
params: { slug: 'first' },
},
{
params: { slug: 'second' },
},
{
params: { slug: 'not-found' },
},
],
fallback: false,
}
}
export function getStaticProps({ params }) {
if (params.slug === 'not-found') {
return {
notFound: true,
}
}
return {
props: {
params,
now: Date.now(),
},
revalidate: params.slug === 'first' ? 60 : undefined,
}
}
export default function Page(props) {
return (
<>
<p>/isr-pages-fallback-false</p>
<p>now: {Date.now()}</p>
<p>{JSON.stringify(props)}</p>
</>
)
}
export function getStaticPaths() {
return {
paths: [
{
params: { slug: 'first' },
},
{
params: { slug: 'second' },
},
],
fallback: true,
}
}
export function getStaticProps({ params }) {
if (params.slug === 'not-found') {
return {
notFound: true,
}
}
return {
props: {
params,
now: Date.now(),
},
revalidate: params.slug === 'first' ? 60 : undefined,
}
}
export default function Page(props) {
return (
<>
<p>/isr-pages-fallback-true</p>
<p>now: {Date.now()}</p>
<p>{JSON.stringify(props)}</p>
</>
)
}
export function getStaticPaths() {
return {
paths: [
{
params: { slug: 'first' },
},
{
params: { slug: 'second' },
},
{
params: { slug: 'not-found' },
},
],
fallback: 'blocking',
}
}
export function getStaticProps({ params }) {
return {
props: {
params,
now: Date.now(),
},
revalidate: params.slug === 'first' ? 60 : undefined,
}
}
export default function Page() {
return (
<>
<p>/isr-pages/[slug]</p>
<p>now: {Date.now()}</p>
</>
)
}
export function getStaticProps() {
return {
props: {
now: Date.now(),
},
}
}
export default function Page() {
return (
<>
<p>/edge-pages</p>
<p>now: {Date.now()}</p>
</>
)
}
export function getServerSideProps() {
return {
props: {
now: Date.now(),
},
}
}
export default function Page(props) {
return (
<>
<p>/node-pages</p>
<p>hello world</p>
<p>now: {Date.now()}</p>
<p>{JSON.stringify(props)}</p>
</>
)
}
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