Unverified Commit 07189c52 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Expose edge runtime fields in build-complete (#91239)

### What?

- Add canonical edge entrypoint metadata to edge function definitions in
the middleware manifest.
- Surface that canonical entrypoint through `build-complete` as
`edgeRuntime` metadata in adapter outputs.
- Update middleware and adapter tests to assert the new metadata instead
of relying on bundler-specific emitted file names.

### Why?

Adapter consumers need a stable way to load and invoke edge outputs
without depending on `next-server`'s sandbox handling or guessing which
emitted file is the executable entrypoint. The existing checks were also
brittle across webpack and Turbopack because the emitted file lists can
differ.

### How?

- Add an optional `entrypoint` field to `EdgeFunctionDefinition` and
populate it in both the webpack middleware manifest generator and the
Turbopack manifest emitters for app, pages, and middleware edge
functions.
- In `packages/next/src/build/adapter/build-complete.ts`, use that
canonical entrypoint for `filePath` and expose `edgeRuntime.modulePath`,
`edgeRuntime.entryKey`, and `edgeRuntime.handlerExport` for edge
outputs.
- Adjust the middleware manifest tests to validate cross-bundler
invariants and add adapter-config coverage for the new `edgeRuntime`
fields.
parent afe3993e
......@@ -1632,12 +1632,20 @@ impl AppEndpoint {
original_source: app_entry.pathname.clone(),
..Default::default()
};
let entrypoint_chunk = *app_entry_chunks_ref
.last()
.context("expected app entry chunks for edge app endpoint")?;
let entrypoint = node_root_value
.get_path_to(&*entrypoint_chunk.path().await?)
.context("expected app entry chunk to be within node root")?
.into();
let edge_function_definition = EdgeFunctionDefinition {
files: file_paths_from_root.into_iter().collect(),
wasm: wasm_paths_to_bindings(wasm_paths_from_root).await?,
assets: paths_to_bindings(all_assets),
name: app_function_name(&app_entry.original_name).into(),
page: app_entry.original_name.clone(),
entrypoint,
regions: app_entry
.config
.await?
......
use std::future::IntoFuture;
use anyhow::Result;
use anyhow::{Context, Result};
use next_core::{
middleware::get_middleware_module,
next_edge::entry::wrap_edge_entry,
......@@ -254,10 +254,18 @@ impl MiddlewareEndpoint {
let node_root = this.project.node_root().owned().await?;
let node_root_value = node_root.clone();
let edge_chunk_group_ref = edge_chunk_group.await?;
let edge_assets = edge_chunk_group_ref.assets.await?;
let file_paths_from_root =
get_js_paths_from_root(&node_root_value, &edge_chunk_group.await?.assets.await?)
.await?;
get_js_paths_from_root(&node_root_value, &edge_assets).await?;
let entrypoint_asset = *edge_assets
.last()
.context("expected assets for edge middleware endpoint")?;
let entrypoint = node_root_value
.get_path_to(&*entrypoint_asset.path().await?)
.context("expected edge middleware asset to be within node root")?
.into();
let mut output_assets = edge_chunk_group.all_assets().owned().await?;
......@@ -285,6 +293,7 @@ impl MiddlewareEndpoint {
assets: paths_to_bindings(all_assets),
name: rcstr!("middleware"),
page: rcstr!("/"),
entrypoint,
regions,
matchers: matchers.clone(),
env: this.project.edge_env().owned().await?,
......
......@@ -1511,6 +1511,13 @@ impl PageEndpoint {
} else {
None
};
let entrypoint_asset = *assets_ref
.last()
.context("expected assets for edge pages endpoint")?;
let entrypoint = node_root
.get_path_to(&*entrypoint_asset.path().await?)
.context("expected edge pages asset to be within node root")?
.into();
let edge_function_definition = EdgeFunctionDefinition {
files: file_paths_from_root.into_iter().collect(),
......@@ -1518,6 +1525,7 @@ impl PageEndpoint {
assets: paths_to_bindings(all_assets),
name: pages_function_name(&this.original_name).into(),
page: this.original_name.clone(),
entrypoint,
regions,
matchers: vec![matchers],
env: this.pages_project.project().edge_env().owned().await?,
......
......@@ -285,6 +285,7 @@ pub struct EdgeFunctionDefinition {
pub files: Vec<RcStr>,
pub name: RcStr,
pub page: RcStr,
pub entrypoint: RcStr,
pub matchers: Vec<ProxyMatcher>,
pub wasm: Vec<AssetBinding>,
pub assets: Vec<AssetBinding>,
......
......@@ -635,6 +635,26 @@ handler(
The shape is aligned around `handler(..., ctx)`, but Node.js and Edge runtimes use different request/response primitives.
For outputs with `runtime: 'edge'`, Next.js also provides `output.edgeRuntime` with the canonical metadata needed to invoke the entrypoint:
```typescript
{
modulePath: string // Absolute path to the module registered in the edge runtime
entryKey: string // Canonical key used by the edge entry registry
handlerExport: string // Export name to invoke, currently 'handler'
}
```
After your edge runtime loads and evaluates the chunks for `modulePath`, use `entryKey` to read the registered entry from the global edge entry registry (`globalThis._ENTRIES`), then invoke `handlerExport` from that entry:
```ts
const entry = await globalThis._ENTRIES[output.edgeRuntime.entryKey]
const handler = entry[output.edgeRuntime.handlerExport]
await handler(request, ctx)
```
Use `edgeRuntime` instead of deriving registry keys or handler names from filenames.
Relevant files in the Next.js core:
- [`packages/next/src/build/templates/edge-ssr.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/edge-ssr.ts)
......@@ -656,6 +676,8 @@ The `outputs` object contains arrays of build output types:
> **Note:** When `config.output` is set to `'export'`, only `outputs.staticFiles` is populated. All other arrays (`pages`, `appPages`, `pagesApi`, `appRoutes`, `prerenders`) will be empty since the entire application is exported as static files.
For any route output with `runtime: 'edge'`, `edgeRuntime` is included and contains the canonical entry metadata for invoking that output in your edge runtime.
### Pages (`outputs.pages`)
React pages from the `pages/` directory:
......@@ -670,6 +692,11 @@ React pages from the `pages/` directory:
runtime: 'nodejs' | 'edge'
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime
entryKey: string // Canonical key used by the edge entry registry
handlerExport: string // Export name to invoke, currently 'handler'
}
config: {
maxDuration?: number // Maximum duration of the route in seconds
preferredRegion?: string | string[] // Preferred deployment region
......@@ -692,6 +719,11 @@ API routes from `pages/api/`:
runtime: 'nodejs' | 'edge'
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime
entryKey: string // Canonical key used by the edge entry registry
handlerExport: string // Export name to invoke, currently 'handler'
}
config: {
maxDuration?: number // Maximum duration of the route in seconds
preferredRegion?: string | string[] // Preferred deployment region
......@@ -714,6 +746,11 @@ React pages from the `app/` directory:
runtime: 'nodejs' | 'edge' // Runtime the route is built for
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime
entryKey: string // Canonical key used by the edge entry registry
handlerExport: string // Export name to invoke, currently 'handler'
}
config: {
maxDuration?: number // Maximum duration of the route in seconds
preferredRegion?: string | string[] // Preferred deployment region
......@@ -736,6 +773,11 @@ API and metadata routes from the `app/` directory:
runtime: 'nodejs' | 'edge' // Runtime the route is built for
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime
entryKey: string // Canonical key used by the edge entry registry
handlerExport: string // Export name to invoke, currently 'handler'
}
config: {
maxDuration?: number // Maximum duration of the route in seconds
preferredRegion?: string | string[] // Preferred deployment region
......@@ -806,6 +848,11 @@ Static assets and auto-statically optimized pages:
runtime: 'nodejs' | 'edge' // Runtime the route is built for
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime
entryKey: string // Canonical key used by the edge entry registry
handlerExport: string // Export name to invoke, currently 'handler'
}
config: {
maxDuration?: number // Maximum duration of the route in seconds
preferredRegion?: string | string[] // Preferred deployment region
......
......@@ -1116,5 +1116,6 @@
"1115": "Route \"%s\" accessed cookie \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`cookies\\` array, or \\`{ name: \"%s\", value: null }\\` if it should be absent.",
"1116": "Route \"%s\" accessed header \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`headers\\` array, or \\`[\"%s\", null]\\` if it should be absent.",
"1117": "Instant validation boundaries should never appear in browser bundles.",
"1118": "An error occurred while attempting to validate instant UI. This error may be preventing the validation from completing."
"1118": "An error occurred while attempting to validate instant UI. This error may be preventing the validation from completing.",
"1119": "Expected edge function entrypoint to emit a JavaScript file"
}
......@@ -89,6 +89,26 @@ interface SharedRouteFields {
*/
wasmAssets?: Record<string, string>
/**
* edgeRuntime contains canonical entry metadata for invoking
* this output in an edge runtime.
*/
edgeRuntime?: {
/**
* modulePath is the canonical module path that registers this
* output in the edge runtime.
*/
modulePath: string
/**
* entryKey is the canonical key used for the global edge entry registry.
*/
entryKey: string
/**
* handlerExport is the export name to invoke on the edge entry.
*/
handlerExport: string
}
/**
* config related to the route
*/
......@@ -709,6 +729,11 @@ export async function handleBuildComplete({
: route === '/index'
? '/'
: route
const edgeEntrypointRelativePath = page.entrypoint
const edgeEntrypointPath = path.join(
distDir,
edgeEntrypointRelativePath
)
const output: Omit<AdapterOutput[typeof type], 'type'> & {
type: any
......@@ -718,19 +743,12 @@ export async function handleBuildComplete({
runtime: 'edge',
sourcePage: route,
pathname,
filePath: path.join(
distDir,
page.files.find(
(item) =>
item.startsWith('server/app') || item.startsWith('server/pages')
) ||
// TODO: turbopack build doesn't name the main entry chunk
// identifiably so we don't know which to mark here but
// technically edge needs all chunks to load always so
// should this field even be provided?
page.files[0] ||
''
),
filePath: edgeEntrypointPath,
edgeRuntime: {
modulePath: edgeEntrypointPath,
entryKey: `middleware_${page.name}`,
handlerExport: 'handler',
},
assets: {},
wasmAssets: {},
config: {
......
......@@ -45,6 +45,10 @@ export interface EdgeFunctionDefinition {
files: string[]
name: string
page: string
/**
* Canonical entrypoint module path (relative to distDir) for this edge function.
*/
entrypoint: string
matchers: ProxyMatcher[]
env: Record<string, string>
wasm?: AssetBinding[]
......@@ -153,6 +157,31 @@ function getEntryFiles(
return files
}
function getEntrypointFile(entrypoint: {
getEntrypointChunk(): { files: Iterable<string> }
getFiles(): Iterable<string>
}): string {
const getJsFile = (files: Iterable<string>): string | undefined => {
for (const file of files) {
if (!file.endsWith('.hot-update.js') && /\.(?:js|mjs|cjs)$/i.test(file)) {
return `server/${file}`
}
}
}
const file =
getJsFile(entrypoint.getEntrypointChunk().files) ||
getJsFile(entrypoint.getFiles())
if (!file) {
throw new Error(
'Expected edge function entrypoint to emit a JavaScript file'
)
}
return file
}
function getCreateAssets(params: {
compilation: webpack.Compilation
metadataByEntry: Map<string, EntryMetadata>
......@@ -224,6 +253,7 @@ function getCreateAssets(params: {
hasInstrumentationHook,
opts
),
entrypoint: getEntrypointFile(entrypoint),
name: entrypoint.name,
page: page,
matchers,
......
......@@ -218,21 +218,21 @@ describe('Middleware Runtime', () => {
...middlewareWithoutEnvs.env,
}
delete middlewareWithoutEnvs.env
expect(middlewareWithoutEnvs).toEqual({
// Turbopack creates more files as it can do chunking.
files: process.env.IS_TURBOPACK_TEST
? expect.toBeArray()
: expect.arrayContaining([
'server/edge-runtime-webpack.js',
'server/middleware.js',
]),
expect(middlewareWithoutEnvs).toMatchObject({
name: 'middleware',
page: '/',
matchers: [{ regexp: '^/.*$', originalSource: '/:path*' }],
wasm: [],
assets: process.env.IS_TURBOPACK_TEST ? expect.toBeArray() : [],
assets: [],
regions: 'auto',
})
expect(middlewareWithoutEnvs.files).toBeArray()
expect(middlewareWithoutEnvs.entrypoint).toMatch(
/^server\/.+\.(?:js|mjs|cjs)$/
)
expect(middlewareWithoutEnvs.files).toContain(
middlewareWithoutEnvs.entrypoint
)
expect(envs).toContainAllKeys([
'NEXT_SERVER_ACTIONS_ENCRYPTION_KEY',
'__NEXT_BUILD_ID',
......@@ -259,11 +259,8 @@ describe('Middleware Runtime', () => {
)
for (const key of Object.keys(manifest.middleware)) {
const middleware = manifest.middleware[key]
if (!process.env.IS_TURBOPACK_TEST) {
expect(middleware.files).toContainEqual(
expect.stringContaining('server/edge-runtime-webpack')
)
}
expect(middleware.entrypoint).toMatch(/^server\/.+\.(?:js|mjs|cjs)$/)
expect(middleware.files).toContain(middleware.entrypoint)
expect(middleware.files).not.toContainEqual(
expect.stringContaining('static/chunks/')
......
......@@ -113,19 +113,20 @@ describe('Middleware Runtime trailing slash', () => {
...manifest.middleware['/'],
}
delete middlewareWithoutEnvs.env
expect(middlewareWithoutEnvs).toEqual({
files: process.env.IS_TURBOPACK_TEST
? expect.toBeArray()
: expect.arrayContaining([
'server/edge-runtime-webpack.js',
'server/middleware.js',
]),
expect(middlewareWithoutEnvs).toMatchObject({
name: 'middleware',
page: '/',
matchers: [{ regexp: '^/.*$', originalSource: '/:path*' }],
wasm: [],
assets: process.env.IS_TURBOPACK_TEST ? expect.toBeArray() : [],
assets: [],
})
expect(middlewareWithoutEnvs.files).toBeArray()
expect(middlewareWithoutEnvs.entrypoint).toMatch(
/^server\/.+\.(?:js|mjs|cjs)$/
)
expect(middlewareWithoutEnvs.files).toContain(
middlewareWithoutEnvs.entrypoint
)
})
it('should have correct files in manifest', async () => {
......@@ -134,11 +135,8 @@ describe('Middleware Runtime trailing slash', () => {
)
for (const key of Object.keys(manifest.middleware)) {
const middleware = manifest.middleware[key]
if (!process.env.IS_TURBOPACK_TEST) {
expect(middleware.files).toContainEqual(
expect.stringContaining('server/edge-runtime-webpack')
)
}
expect(middleware.entrypoint).toMatch(/^server\/.+\.(?:js|mjs|cjs)$/)
expect(middleware.files).toContain(middleware.entrypoint)
expect(middleware.files).not.toContainEqual(
expect.stringContaining('static/chunks/')
)
......
......@@ -340,6 +340,24 @@ describe('adapter-config', () => {
__NEXT_PREVIEW_MODE_SIGNING_KEY: expect.toBeString(),
})
)
const edgeRuntime = (
route as PageRoutesType & {
edgeRuntime?: {
modulePath: string
entryKey: string
handlerExport: string
}
}
).edgeRuntime
expect(edgeRuntime).toEqual(
expect.objectContaining({
modulePath: expect.toBeString(),
entryKey: expect.toBeString(),
handlerExport: 'handler',
})
)
expect(edgeRuntime?.entryKey.startsWith('middleware_')).toBe(true)
expect(edgeRuntime?.modulePath).toBe(route.filePath)
const stats = await fs.promises.stat(route.filePath)
expect(stats.isFile()).toBe(true)
......
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