Unverified Commit 29010ffd authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update cases for build complete with adapters (#84361)

This handles `i18n` cases, ensures `pathname` field is prefixed with
`basePath` when configured, and fixes interop with `output: 'export'`
configured.
parent 9c9e793b
......@@ -35,6 +35,8 @@ import {
JSON_CONTENT_TYPE_HEADER,
NEXT_RESUME_HEADER,
} from '../../lib/constants'
import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path'
import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix'
interface SharedRouteFields {
/**
......@@ -62,6 +64,12 @@ interface SharedRouteFields {
*/
assets: Record<string, string>
/**
* wasmAssets are bundled wasm files with mapping of name
* to filePath on disk
*/
wasmAssets?: Record<string, string>
/**
* config related to the route
*/
......@@ -77,6 +85,12 @@ interface SharedRouteFields {
* region preferences to the provider being used
*/
preferredRegion?: string | string[]
/**
* env is the environment variables to expose, this is only
* populated for edge runtime currently
*/
env?: Record<string, string>
}
}
......@@ -297,9 +311,30 @@ export interface NextAdapter {
}) => Promise<void> | void
}
function normalizePathnames(
config: NextConfigComplete,
outputs: AdapterOutputs
) {
// normalize pathname field with basePath
if (config.basePath) {
for (const output of [
...outputs.pages,
...outputs.pagesApi,
...outputs.appPages,
...outputs.appRoutes,
...outputs.prerenders,
...outputs.staticFiles,
...(outputs.middleware ? [outputs.middleware] : []),
]) {
output.pathname = addPathPrefix(output.pathname, config.basePath)
}
}
}
export async function handleBuildComplete({
dir,
config,
configOutDir,
distDir,
pageKeys,
tracingRoot,
......@@ -318,6 +353,7 @@ export async function handleBuildComplete({
}: {
dir: string
distDir: string
configOutDir: string
adapterPath: string
tracingRoot: string
nextVersion: string
......@@ -341,16 +377,34 @@ export async function handleBuildComplete({
if (typeof adapterMod.onBuildComplete === 'function') {
Log.info(`Running onBuildComplete from ${adapterMod.name}`)
try {
const outputs: AdapterOutputs = {
pages: [],
pagesApi: [],
appPages: [],
appRoutes: [],
prerenders: [],
staticFiles: [],
}
const outputs: AdapterOutputs = {
pages: [],
pagesApi: [],
appPages: [],
appRoutes: [],
prerenders: [],
staticFiles: [],
}
if (config.output === 'export') {
// collect export assets and provide as static files
const exportFiles = await recursiveReadDir(configOutDir)
for (const file of exportFiles) {
let pathname = (
file.endsWith('.html') ? file.replace(/\.html$/, '') : file
).replace(/\\/g, '/')
pathname = pathname.startsWith('/') ? pathname : `/${pathname}`
outputs.staticFiles.push({
id: file,
pathname,
filePath: path.join(configOutDir, file),
type: AdapterOutputType.STATIC_FILE,
} satisfies AdapterOutput['STATIC_FILE'])
}
} else {
const staticFiles = await recursiveReadDir(path.join(distDir, 'static'))
for (const file of staticFiles) {
......@@ -460,12 +514,15 @@ export async function handleBuildComplete({
''
),
assets: {},
config:
type === AdapterOutputType.MIDDLEWARE
wasmAssets: {},
config: {
...(type === AdapterOutputType.MIDDLEWARE
? {
matchers: page.matchers,
}
: {},
: {}),
env: page.env,
},
}
function handleFile(file: string) {
......@@ -482,9 +539,15 @@ export async function handleBuildComplete({
for (const file of page.files) {
handleFile(file)
}
for (const item of [...(page.wasm || []), ...(page.assets || [])]) {
for (const item of [...(page.assets || [])]) {
handleFile(item.filePath)
}
for (const item of page.wasm || []) {
if (!output.wasmAssets) {
output.wasmAssets = {}
}
output.wasmAssets[item.name] = item.filePath
}
if (type === AdapterOutputType.MIDDLEWARE) {
outputs.middleware = output
......@@ -528,12 +591,28 @@ export async function handleBuildComplete({
// if it's an auto static optimized page it's just
// a static file
if (staticPages.has(page)) {
outputs.staticFiles.push({
id: page,
pathname: route,
type: AdapterOutputType.STATIC_FILE,
filePath: pageFile.replace(/\.js$/, '.html'),
} satisfies AdapterOutput['STATIC_FILE'])
if (config.i18n) {
for (const locale of config.i18n.locales || []) {
const localePage =
page === '/' ? `/${locale}` : addPathPrefix(page, `/${locale}`)
outputs.staticFiles.push({
id: localePage,
pathname: localePage,
type: AdapterOutputType.STATIC_FILE,
filePath: path.join(
pagesDistDir,
`${normalizePagePath(localePage)}.html`
),
} satisfies AdapterOutput['STATIC_FILE'])
}
} else {
outputs.staticFiles.push({
id: page,
pathname: route,
type: AdapterOutputType.STATIC_FILE,
filePath: pageFile.replace(/\.js$/, '.html'),
} satisfies AdapterOutput['STATIC_FILE'])
}
continue
}
......@@ -639,7 +718,12 @@ export async function handleBuildComplete({
childRoute: string,
allowMissing?: boolean
) => {
const parentOutput = pageOutputMap[srcRoute] || appOutputMap[srcRoute]
const normalizedSrcRoute = normalizeLocalePath(
srcRoute,
config.i18n?.locales || []
).pathname
const parentOutput =
pageOutputMap[normalizedSrcRoute] || appOutputMap[normalizedSrcRoute]
if (!parentOutput && !allowMissing) {
console.error({
......@@ -966,7 +1050,11 @@ export async function handleBuildComplete({
}
prerenderGroupId += 1
}
}
normalizePathnames(config, outputs)
try {
await adapterMod.onBuildComplete({
routes: {
dynamicRoutes: routesManifest.dynamicRoutes,
......
......@@ -3796,7 +3796,7 @@ export default async function build(
dataRoute: path.posix.join(
'/_next/data',
buildId,
`${file}.json`
`${localePage}.json`
),
prefetchDataRoute: undefined,
allowHeader: ALLOWED_HEADERS,
......@@ -4085,6 +4085,9 @@ export default async function build(
})
}
// This should come after output: export handling but before
// output: standalone, in the future output: standalone might
// not be allowed if an adapter with onBuildComplete is configured
const adapterPath = config.experimental.adapterPath
if (adapterPath) {
await nextBuildSpan
......@@ -4094,6 +4097,7 @@ export default async function build(
dir,
distDir,
config,
configOutDir: path.join(dir, configOutDir),
staticPages,
nextVersion: process.env.__NEXT_VERSION as string,
tracingRoot: outputFileTracingRoot,
......
import fs from 'fs'
import type { NextAdapter } from 'next'
import { nextTestSetup } from 'e2e-utils'
import { version as nextVersion } from 'next/package.json'
process.env.TEST_EXPORT = '1'
describe('adapter-config export', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
it('should call onBuildComplete with correct context', async () => {
const nonExportFiles = [
'app/node-app/page.tsx',
'app/node-route/route.ts',
'app/edge-route/route.ts',
'app/isr-route/route.ts',
'app/isr-route/[slug]/route.ts',
'app/edge-app/page.tsx',
'pages/api/edge-pages.ts',
'pages/api/node-pages.ts',
'pages/edge-pages/index.tsx',
'pages/node-pages/index.tsx',
]
for (const file of nonExportFiles) {
await next.remove(file)
}
await next.build()
expect(next.cliOutput).toContain('onBuildComplete called')
const {
outputs,
routes,
config,
...ctx
}: Parameters<NextAdapter['onBuildComplete']>[0] = await next.readJSON(
'build-complete.json'
)
for (const field of ['distDir', 'projectDir', 'repoRoot']) {
expect(ctx[field]).toBeString()
if (!fs.existsSync(ctx[field])) {
throw new Error(
`Invalid dir value provided for ${field} value ${ctx[field]}`
)
}
}
expect(ctx.nextVersion).toBe(nextVersion)
expect(config?.basePath).toBe('/docs')
const combinedRouteOutputs = [
...outputs.appPages,
...outputs.appRoutes,
...outputs.pages,
...outputs.pagesApi,
]
expect(outputs.middleware).toBeFalsy()
expect(outputs.prerenders).toEqual([])
expect(combinedRouteOutputs).toEqual([])
for (const output of outputs.staticFiles) {
expect(output.id).toBeTruthy()
if (output.filePath.endsWith('.html')) {
expect(output.pathname.endsWith('.html')).toBe(false)
}
expect(output.pathname).toStartWith('/docs/')
const stats = await fs.promises.stat(output.filePath)
expect(stats.isFile()).toBe(true)
}
expect(routes).toEqual({
dynamicRoutes: expect.toBeArray(),
rewrites: expect.toBeObject(),
redirects: expect.toBeArray(),
headers: expect.toBeArray(),
})
})
})
......@@ -95,7 +95,7 @@ describe('adapter-config', () => {
if (output.filePath.endsWith('.html')) {
expect(output.pathname.endsWith('.html')).toBe(false)
} else {
expect(output.pathname).toStartWith('/_next/static')
expect(output.pathname).toStartWith('/docs/_next/static')
}
const stats = await fs.promises.stat(output.filePath)
......@@ -153,6 +153,15 @@ describe('adapter-config', () => {
expect(route.config).toBeObject()
expect(route.pathname).toBeString()
expect(route.runtime).toBe('edge')
expect(route.config.env).toEqual(
expect.objectContaining({
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: expect.toBeString(),
__NEXT_BUILD_ID: expect.toBeString(),
__NEXT_PREVIEW_MODE_ENCRYPTION_KEY: expect.toBeString(),
__NEXT_PREVIEW_MODE_ID: expect.toBeString(),
__NEXT_PREVIEW_MODE_SIGNING_KEY: expect.toBeString(),
})
)
const stats = await fs.promises.stat(route.filePath)
expect(stats.isFile()).toBe(true)
......
......@@ -7,6 +7,7 @@ const nextConfig = {
adapterPath: require.resolve('./my-adapter.mjs'),
ppr: Boolean(process.env.TEST_PPR),
},
output: process.env.TEST_EXPORT ? 'export' : undefined,
}
export default nextConfig
......@@ -27,7 +27,8 @@ export function getStaticProps({ params }) {
params,
now: Date.now(),
},
revalidate: params.slug === 'first' ? 60 : undefined,
revalidate:
!process.env.TEST_EXPORT && params.slug === 'first' ? 60 : undefined,
}
}
......
......@@ -27,7 +27,8 @@ export function getStaticProps({ params }) {
params,
now: Date.now(),
},
revalidate: params.slug === 'first' ? 60 : undefined,
revalidate:
!process.env.TEST_EXPORT && params.slug === 'first' ? 60 : undefined,
}
}
......
......@@ -27,7 +27,8 @@ export function getStaticProps({ params }) {
params,
now: Date.now(),
},
revalidate: params.slug === 'first' ? 60 : undefined,
revalidate:
!process.env.TEST_EXPORT && params.slug === 'first' ? 60 : undefined,
}
}
......
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