The Open Framework for Building Agents
fix(eve): preserve Next.js middleware with generated services (#783)
Andrew Barbad81057003e7e
diff --git a/.changeset/isolate-next-eve-service-output.md b/.changeset/isolate-next-eve-service-output.mdnew file mode 100644index 000000000..3c99b210f--- /dev/null+++ b/.changeset/isolate-next-eve-service-output.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Keep generated eve service builds isolated from a colocated Next.js Build Output and preserve host middleware mappings when Vercel collects the generated service.diff --git a/packages/eve/src/cli/run.test.ts b/packages/eve/src/cli/run.test.tsindex f8cfb136f..fb69fea92 100644--- a/packages/eve/src/cli/run.test.ts+++ b/packages/eve/src/cli/run.test.ts@@ -1,3 +1,5 @@+import { resolve } from "node:path";+import { describe, expect, it, vi } from "vitest";import { resolveDevUiMode, resolveTuiDisplayOptions, runCli } from "#cli/run.js";@@ -402,6 +404,44 @@ describe("eve dev local server ownership", () => {});});+describe("eve build output ownership", () => {+ it("resolves the internal service output directory from the build working directory", async () => {+ const buildHost = vi.fn(async () => "/service/.vercel/output");+ const configuredDirectory = ".eve/vercel-services/eve/.vercel/output";+ const configuredHostDirectory = ".vercel/output";+ vi.stubEnv("EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY", configuredDirectory);+ vi.stubEnv("EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY", configuredHostDirectory);++ try {+ await runCli(["build"], { error: () => {}, log: () => {} }, { buildHost });+ } finally {+ vi.unstubAllEnvs();+ }++ expect(buildHost).toHaveBeenCalledWith(process.cwd(), {+ skipVercelSandboxPrewarm: false,+ vercelServiceOutput: {+ hostOutputDirectory: resolve(process.cwd(), configuredHostDirectory),+ serviceOutputDirectory: resolve(process.cwd(), configuredDirectory),+ },+ });+ });++ it("rejects an incomplete internal Vercel service output contract", async () => {+ vi.stubEnv("EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY", ".eve/vercel-services/eve/.vercel/output");++ try {+ await expect(+ runCli(["build"], { error: () => {}, log: () => {} }, { buildHost: vi.fn() }),+ ).rejects.toThrow(+ "EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY and EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY must be set together.",+ );+ } finally {+ vi.unstubAllEnvs();+ }+ });+});+describe("resolveDevUiMode", () => {it("defaults to the terminal UI in an interactive terminal", () => {expect(resolveDevUiMode({ options: {}, interactive: true })).toBe("tui");diff --git a/packages/eve/src/cli/run.ts b/packages/eve/src/cli/run.tsindex 420e5653d..e3a7e19fe 100644--- a/packages/eve/src/cli/run.ts+++ b/packages/eve/src/cli/run.ts@@ -4,6 +4,7 @@ import { resolveApplicationRoot } from "#internal/application/paths.js";import { resolveInstalledPackageInfo } from "#internal/application/package.js";import { isCodingAgentLaunch } from "#cli/agent-detection.js";import { eveCliBanner } from "#cli/banner.js";+import { resolveInternalVercelServiceOutput } from "#cli/vercel-service-output.js";import { registerProjectCommands } from "#cli/commands/register-project-commands.js";import { resolveDevUiMode, resolveTuiDisplayOptions } from "#cli/dev/ui-options.js";import {@@ -380,6 +381,7 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Commconst buildHost = runtime.buildHost ?? (await loadBuildHost());const outputDir = await buildHost(appRoot, {skipVercelSandboxPrewarm: options.skipSandboxPrewarm === true,+ vercelServiceOutput: resolveInternalVercelServiceOutput(appRoot),});logger.log(renderCliTaggedLine(theme, {diff --git a/packages/eve/src/cli/vercel-service-output.ts b/packages/eve/src/cli/vercel-service-output.tsnew file mode 100644index 000000000..6e8076fb1--- /dev/null+++ b/packages/eve/src/cli/vercel-service-output.ts@@ -0,0 +1,46 @@+import { resolve } from "node:path";++import {+ EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV,+ EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV,+} from "#internal/application/paths.js";+import type { ApplicationBuildOptions } from "#internal/nitro/host/types.js";++type VercelServiceOutput = NonNullable<ApplicationBuildOptions["vercelServiceOutput"]>;++function resolveInternalBuildDirectory(+ appRoot: string,+ environmentVariableName: string,+): string | undefined {+ const configuredDirectory = process.env[environmentVariableName];++ if (configuredDirectory === undefined || configuredDirectory.trim().length === 0) {+ return undefined;+ }++ return resolve(appRoot, configuredDirectory);+}++export function resolveInternalVercelServiceOutput(+ appRoot: string,+): VercelServiceOutput | undefined {+ const hostOutputDirectory = resolveInternalBuildDirectory(+ appRoot,+ EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV,+ );+ const serviceOutputDirectory = resolveInternalBuildDirectory(+ appRoot,+ EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV,+ );++ if (hostOutputDirectory === undefined && serviceOutputDirectory === undefined) {+ return undefined;+ }+ if (hostOutputDirectory === undefined || serviceOutputDirectory === undefined) {+ throw new Error(+ `${EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV} and ${EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV} must be set together.`,+ );+ }++ return { hostOutputDirectory, serviceOutputDirectory };+}diff --git a/packages/eve/src/internal/application/build-workspace.ts b/packages/eve/src/internal/application/build-workspace.tsindex 62e8efa90..4283356cf 100644--- a/packages/eve/src/internal/application/build-workspace.ts+++ b/packages/eve/src/internal/application/build-workspace.ts@@ -42,6 +42,7 @@ export interface ApplicationBuildWorkspace {*/export async function createApplicationBuildWorkspace(appRoot: string,+ outputDirectory?: string,): Promise<ApplicationBuildWorkspace> {const resolvedAppRoot = resolve(appRoot);const buildId = `${Date.now().toString(36)}-${randomUUID()}`;@@ -62,7 +63,7 @@ export async function createApplicationBuildWorkspace(},publication: {output: {- finalDir: resolveOutputDirectory(resolvedAppRoot),+ finalDir: outputDirectory ?? resolveOutputDirectory(resolvedAppRoot),stagedDir: join(rootDir, "output"),},summary: {diff --git a/packages/eve/src/internal/application/paths.ts b/packages/eve/src/internal/application/paths.tsindex b898e3e4b..faf94058c 100644--- a/packages/eve/src/internal/application/paths.ts+++ b/packages/eve/src/internal/application/paths.ts@@ -10,6 +10,10 @@ import {resolvePackageSourceDirectoryPath,} from "#internal/application/package.js";+export const EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV = "EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY";+export const EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV =+ "EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY";+export interface ApplicationInfo {appRoot: string;outputDir: string;diff --git a/packages/eve/src/internal/nitro/host/build-application.ts b/packages/eve/src/internal/nitro/host/build-application.tsindex 38cd7a711..bfc9312cf 100644--- a/packages/eve/src/internal/nitro/host/build-application.ts+++ b/packages/eve/src/internal/nitro/host/build-application.ts@@ -24,6 +24,7 @@ import { normalizeEveVercelFunctionOutput } from "#internal/workflow-bundle/vercimport { createProductionApplicationNitro } from "#internal/nitro/host/create-application-nitro.js";import { emitVercelAgentSummary } from "#internal/nitro/host/build-vercel-agent-summary.js";import { tryReadExtensionBuildConfig } from "#internal/nitro/host/build-extension.js";+import { copyHostMiddlewareFunctions } from "#internal/nitro/host/copy-host-middleware.js";import { prepareProductionApplicationHost } from "#internal/nitro/host/prepare-application-host.js";import { runVercelBuildPrewarm } from "#internal/nitro/host/vercel-build-prewarm.js";import type {@@ -322,7 +323,10 @@ export async function buildApplication(}const project = await resolveDiscoveryProject(rootDir);- const workspace = await createApplicationBuildWorkspace(project.appRoot);+ const workspace = await createApplicationBuildWorkspace(+ project.appRoot,+ options.vercelServiceOutput?.serviceOutputDirectory,+ );// A recoverable publication failure leaves the lock journal pointing at// staged artifacts inside this workspace; the next build's recovery@@ -417,6 +421,12 @@ async function buildApplicationInWorkspace(servicePrefix,});}+ if (options.vercelServiceOutput !== undefined) {+ await copyHostMiddlewareFunctions({+ hostOutputDirectory: options.vercelServiceOutput.hostOutputDirectory,+ serviceOutputDirectory: workspace.publication.output.stagedDir,+ });+ }await emitVercelAgentSummary({manifest: preparedHost.compileResult.manifest,outputPath: workspace.publication.summary.stagedPath,diff --git a/packages/eve/src/internal/nitro/host/copy-host-middleware.ts b/packages/eve/src/internal/nitro/host/copy-host-middleware.tsnew file mode 100644index 000000000..33ed7120d--- /dev/null+++ b/packages/eve/src/internal/nitro/host/copy-host-middleware.ts@@ -0,0 +1,98 @@+import { access, cp, mkdir, readFile } from "node:fs/promises";+import { dirname, join, posix, resolve, sep } from "node:path";++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}++const NEXT_MIDDLEWARE_PATH = "/_middleware";++function resolveMiddlewareFunctionDirectory(+ outputDirectory: string,+ middlewarePath: string,+): string {+ const normalizedPath = posix.normalize(middlewarePath.replace(/^\/+/, ""));++ if (+ normalizedPath.length === 0 ||+ normalizedPath === "." ||+ normalizedPath === ".." ||+ normalizedPath.startsWith("../") ||+ normalizedPath.includes("\\") ||+ normalizedPath.includes("\0")+ ) {+ throw new Error(`Invalid Vercel middlewarePath: ${JSON.stringify(middlewarePath)}.`);+ }++ const functionsDirectory = resolve(outputDirectory, "functions");+ const functionDirectory = resolve(functionsDirectory, `${normalizedPath}.func`);++ if (!functionDirectory.startsWith(`${functionsDirectory}${sep}`)) {+ throw new Error(`Vercel middlewarePath escapes the functions directory: ${middlewarePath}.`);+ }++ return functionDirectory;+}++/**+ * Copies host middleware functions into a generated service Build Output.+ *+ * Vercel validates generated-service routes against each service builder's+ * function map. The host remains the runtime owner of these functions; this+ * copy makes that same opaque Build Output function available while Vercel+ * collects the generated service.+ */+export async function copyHostMiddlewareFunctions(input: {+ readonly hostOutputDirectory: string;+ readonly serviceOutputDirectory: string;+}): Promise<void> {+ const config: unknown = JSON.parse(+ await readFile(join(input.hostOutputDirectory, "config.json"), "utf8"),+ );++ if (!isRecord(config)) {+ return;+ }++ const middlewarePaths = new Set<string>();++ if (Array.isArray(config.routes)) {+ for (const route of config.routes) {+ if (isRecord(route) && typeof route.middlewarePath === "string") {+ middlewarePaths.add(route.middlewarePath);+ }+ }+ }++ // Local `vercel build` emits the Next middleware function before it adds the+ // corresponding route to config.json. Remote builds have both by this point.+ const nextMiddlewareDirectory = resolveMiddlewareFunctionDirectory(+ input.hostOutputDirectory,+ NEXT_MIDDLEWARE_PATH,+ );+ try {+ await access(nextMiddlewareDirectory);+ middlewarePaths.add(NEXT_MIDDLEWARE_PATH);+ } catch (error) {+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {+ throw error;+ }+ }++ for (const middlewarePath of middlewarePaths) {+ const sourceDirectory = resolveMiddlewareFunctionDirectory(+ input.hostOutputDirectory,+ middlewarePath,+ );+ const destinationDirectory = resolveMiddlewareFunctionDirectory(+ input.serviceOutputDirectory,+ middlewarePath,+ );++ await mkdir(dirname(destinationDirectory), { recursive: true });+ await cp(sourceDirectory, destinationDirectory, {+ force: true,+ recursive: true,+ });+ }+}diff --git a/packages/eve/src/internal/nitro/host/types.ts b/packages/eve/src/internal/nitro/host/types.tsindex 46e0a0df5..fcbc97a3a 100644--- a/packages/eve/src/internal/nitro/host/types.ts+++ b/packages/eve/src/internal/nitro/host/types.ts@@ -12,6 +12,10 @@ export type NitroBuildSurface = "all" | "app" | "flow";/** Options for one production application build. */export interface ApplicationBuildOptions {readonly skipVercelSandboxPrewarm: boolean;+ readonly vercelServiceOutput?: {+ readonly hostOutputDirectory: string;+ readonly serviceOutputDirectory: string;+ };}/** Outcome of starting a Nitro development server the current process owns. */diff --git a/packages/eve/src/internal/testing/run-pnpm-command.ts b/packages/eve/src/internal/testing/run-pnpm-command.tsindex 59ba28ca7..b7dbf9334 100644--- a/packages/eve/src/internal/testing/run-pnpm-command.ts+++ b/packages/eve/src/internal/testing/run-pnpm-command.ts@@ -8,6 +8,7 @@ const runFile = promisify(execFile);interface PnpmCommandInput {readonly args: readonly string[];readonly cwd: string;+ readonly env?: NodeJS.ProcessEnv;}/**@@ -41,6 +42,7 @@ export async function runPnpmCommand(input: PnpmCommandInput): Promise<PnpmCommatry {const result = await runFile(invocation.command, [...invocation.args], {cwd: input.cwd,+ env: input.env,maxBuffer: 10 * 1024 * 1024,shell: invocation.shell,});diff --git a/packages/eve/src/internal/testing/scenario-apps/next-eve-proxy.ts b/packages/eve/src/internal/testing/scenario-apps/next-eve-proxy.tsnew file mode 100644index 000000000..233ca843f--- /dev/null+++ b/packages/eve/src/internal/testing/scenario-apps/next-eve-proxy.ts@@ -0,0 +1,73 @@+import { createRequire } from "node:module";++import type { ScenarioAppDescriptor } from "#internal/testing/scenario-app.js";++const require = createRequire(import.meta.url);++export interface NextEveProxyDescriptorOptions {+ readonly installDependencies?: boolean;+ readonly vercelVersion?: string;+}++/**+ * A Next.js host with routing middleware and a generated eve service.+ */+export function createNextEveProxyDescriptor(+ options: NextEveProxyDescriptorOptions = {},+): ScenarioAppDescriptor {+ const dependencies: Record<string, string> = {+ next: resolveInstalledPackageVersion("next"),+ react: resolveInstalledPackageVersion("react"),+ "react-dom": resolveInstalledPackageVersion("react-dom"),+ };+ if (options.vercelVersion !== undefined) {+ dependencies.vercel = options.vercelVersion;+ }++ return {+ dependencies,+ files: {+ "agent/agent.mjs": `import { defineAgent } from "eve";++export default defineAgent({ model: "openai/gpt-5.4" });+`,+ "agent/instructions.md": "You are a test agent.\n",+ "next.config.mjs": `import { withEve } from "eve/next";++export default withEve({});+`,+ "pnpm-workspace.yaml": "minimumReleaseAge: 0\n",+ "src/app/layout.js": `export default function RootLayout({ children }) {+ return <html><body>{children}</body></html>;+}+`,+ "src/app/page.js": `export default function Page() {+ return <main>eve middleware deployment</main>;+}+`,+ "src/proxy.js": `import { NextResponse } from "next/server";++export function proxy() {+ return NextResponse.next();+}+`,+ },+ installDependencies: options.installDependencies,+ name: "next-eve-proxy",+ };+}++function resolveInstalledPackageVersion(packageName: string): string {+ const manifest: unknown = require(`${packageName}/package.json`);++ if (+ typeof manifest !== "object" ||+ manifest === null ||+ !("version" in manifest) ||+ typeof manifest.version !== "string"+ ) {+ throw new Error(`Expected ${packageName}/package.json to contain a string version.`);+ }++ return manifest.version;+}diff --git a/packages/eve/src/public/next/index.integration.test.ts b/packages/eve/src/public/next/index.integration.test.tsindex f62cbdc75..4dde0753c 100644--- a/packages/eve/src/public/next/index.integration.test.ts+++ b/packages/eve/src/public/next/index.integration.test.ts@@ -1,4 +1,4 @@-import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, readFile, stat, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";@@ -73,7 +73,8 @@ describe("withEve Vercel config", () => {],services: {eve: {- buildCommand: "node 'node_modules/eve/bin/eve.js' build",+ buildCommand:+ "cd '../../..' && export EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY='.eve/vercel-services/eve/.vercel/output' && export EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY='.vercel/output' && node 'node_modules/eve/bin/eve.js' build",framework: "eve",routes: [{@@ -87,7 +88,7 @@ describe("withEve Vercel config", () => {],},],- root: ".",+ root: ".eve/vercel-services/eve",},},version: 3,@@ -95,6 +96,30 @@ describe("withEve Vercel config", () => {expect(rewrites).toBeUndefined();});+ it("isolates a colocated generated eve service from the Next.js Build Output", async () => {+ const appRoot = await createTempAppRoot();+ process.chdir(appRoot);+ vi.stubEnv("NODE_ENV", "production");+ vi.stubEnv("VERCEL", "1");+ vi.stubEnv("VERCEL_URL", "preview.example.com");++ await resolveConfig(withEve<TestConfig>({}));++ const serviceRoot = join(appRoot, ".eve", "vercel-services", "eve");+ const outputConfig = await readJsonFile(join(appRoot, ".vercel", "output", "config.json"));++ expect((await stat(serviceRoot)).isDirectory()).toBe(true);+ expect(outputConfig).toMatchObject({+ services: {+ eve: {+ buildCommand:+ "cd '../../..' && export EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY='.eve/vercel-services/eve/.vercel/output' && export EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY='.vercel/output' && node 'node_modules/eve/bin/eve.js' build",+ root: ".eve/vercel-services/eve",+ },+ },+ });+ });+it("writes Build Output config to the closest existing .vercel directory", async () => {const projectRoot = await createTempAppRoot();const appRoot = join(projectRoot, "apps", "web");@@ -122,7 +147,8 @@ describe("withEve Vercel config", () => {],services: {eve: {- buildCommand: "node 'node_modules/eve/bin/eve.js' build",+ buildCommand:+ "cd '../../..' && export EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY='.eve/vercel-services/eve/.vercel/output' && export EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY='../../.vercel/output' && node 'node_modules/eve/bin/eve.js' build",framework: "eve",routes: [{@@ -136,7 +162,7 @@ describe("withEve Vercel config", () => {],},],- root: ".",+ root: ".eve/vercel-services/eve",},},version: 3,@@ -276,7 +302,8 @@ describe("withEve Vercel config", () => {expect(outputConfig).toMatchObject({services: {eve: {- buildCommand: "pnpm build:eve",+ buildCommand:+ "cd '../../..' && export EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY='.eve/vercel-services/eve/.vercel/output' && export EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY='.vercel/output' && pnpm build:eve",},},});@@ -326,7 +353,8 @@ describe("withEve Vercel config", () => {],services: {"eve-billing": {- buildCommand: "pnpm build:billing-agent",+ buildCommand:+ "cd '../../../agents/billing' && export EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY='../../.eve/vercel-services/eve-billing/.vercel/output' && export EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY='../../.vercel/output' && pnpm build:billing-agent",framework: "eve",routes: [{@@ -340,11 +368,12 @@ describe("withEve Vercel config", () => {],},],- root: "agents/billing",+ root: ".eve/vercel-services/eve-billing",routePrefix: "/eve/agents/billing",},"eve-support": {- buildCommand: "node '../../node_modules/eve/bin/eve.js' build",+ buildCommand:+ "cd '../../../agents/support' && export EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY='../../.eve/vercel-services/eve-support/.vercel/output' && export EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY='../../.vercel/output' && node '../../node_modules/eve/bin/eve.js' build",framework: "eve",routes: [{@@ -358,7 +387,7 @@ describe("withEve Vercel config", () => {],},],- root: "agents/support",+ root: ".eve/vercel-services/eve-support",routePrefix: "/eve/agents/support",},},@@ -442,7 +471,8 @@ describe("withEve Vercel config", () => {],services: {"eve-billing": {- buildCommand: "node '../../node_modules/eve/bin/eve.js' build",+ buildCommand:+ "cd '../../../agents/billing' && export EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY='../../.eve/vercel-services/eve-billing/.vercel/output' && export EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY='../../.vercel/output' && node '../../node_modules/eve/bin/eve.js' build",framework: "eve",routes: [{@@ -456,7 +486,7 @@ describe("withEve Vercel config", () => {],},],- root: "agents/billing",+ root: ".eve/vercel-services/eve-billing",routePrefix: "/eve/agents/billing",},"eve-support": {diff --git a/packages/eve/src/public/next/vercel-output-config.ts b/packages/eve/src/public/next/vercel-output-config.tsindex 6284d0b24..37d592cf7 100644--- a/packages/eve/src/public/next/vercel-output-config.ts+++ b/packages/eve/src/public/next/vercel-output-config.ts@@ -1,6 +1,10 @@import { mkdir, readFile, writeFile } from "node:fs/promises";import { dirname, join, relative } from "node:path";+import {+ EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV,+ EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV,+} from "#internal/application/paths.js";import {findClosestLinkedVercelDirectory,findClosestVercelOutputDirectory,@@ -12,6 +16,7 @@ const VERCEL_BUILD_OUTPUT_VERSION = 3;const EVE_SERVICE_NAME = "eve";const EVE_SERVICE_ROUTE_SRC = "^/eve/v1/(.*)$";const EVE_SERVICE_ROUTE_PATH = "/eve/v1/$1";+const EVE_VERCEL_SERVICES_DIRECTORY = ".eve/vercel-services";interface VercelServiceMount {readonly path?: string;@@ -140,6 +145,36 @@ function resolveRelativeEntrypoint(fromRoot: string, toRoot: string): string {return relativePath.replaceAll("\\", "/");}+function quoteShellArgument(value: string): string {+ return `'${value.replaceAll("'", "'\\''")}'`;+}++function createGeneratedServiceBuild(input: {+ readonly agent: EnsureVercelOutputConfigAgentInput;+ readonly hostOutputDirectory: string;+ readonly nextRoot: string;+ readonly serviceName: string;+}): {+ readonly buildCommand: string;+ readonly root: string;+ readonly rootDirectory: string;+} {+ const rootDirectory = join(input.nextRoot, EVE_VERCEL_SERVICES_DIRECTORY, input.serviceName);+ const outputDirectory = join(rootDirectory, ".vercel", "output");+ const workingDirectory = resolveRelativeEntrypoint(rootDirectory, input.agent.appRoot);+ const configuredOutputDirectory = resolveRelativeEntrypoint(input.agent.appRoot, outputDirectory);+ const configuredHostOutputDirectory = resolveRelativeEntrypoint(+ input.agent.appRoot,+ input.hostOutputDirectory,+ );++ return {+ buildCommand: `cd ${quoteShellArgument(workingDirectory)} && export ${EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(configuredOutputDirectory)} && export ${EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(configuredHostOutputDirectory)} && ${input.agent.buildCommand}`,+ root: resolveRelativeEntrypoint(input.nextRoot, rootDirectory),+ rootDirectory,+ };+}+async function resolveVercelOutputConfigLocation(nextRoot: string): Promise<{readonly canWriteGeneratedOutput: boolean;readonly outputConfigPath: string;@@ -465,11 +500,18 @@ export async function ensureEveVercelOutputConfig(input: {const routeSrc = createEveServiceRouteSrc(agent.publicRoutePrefix);if (configuredEveServiceEntry === undefined) {+ const generatedServiceBuild = createGeneratedServiceBuild({+ agent,+ hostOutputDirectory: dirname(outputConfigPath),+ nextRoot: input.nextRoot,+ serviceName,+ });+ await mkdir(generatedServiceBuild.rootDirectory, { recursive: true });const serviceConfig: MutableGeneratedVercelServiceConfig = {- buildCommand: agent.buildCommand,+ buildCommand: generatedServiceBuild.buildCommand,framework: "eve",routes: insertEveServiceRequestPathRoute(undefined, routeSrc),- root: resolveRelativeEntrypoint(input.nextRoot, agent.appRoot),+ root: generatedServiceBuild.root,};if (agent.publicRoutePrefix.length > 0) {diff --git a/packages/eve/test/helpers/vercel-deployment-fixture.ts b/packages/eve/test/helpers/vercel-deployment-fixture.tsindex 707c112e6..448d5bc42 100644--- a/packages/eve/test/helpers/vercel-deployment-fixture.ts+++ b/packages/eve/test/helpers/vercel-deployment-fixture.ts@@ -34,6 +34,8 @@ export interface CreateTarballVercelDeploymentFixtureInput {readonly runtimeEnv?: Readonly<Record<string, string>>;readonly scope?: string;readonly token: string;+ /** Wait for the deployed eve health route after the Vercel build succeeds. */+ readonly waitForHealth?: boolean;}/**@@ -73,9 +75,11 @@ export async function createTarballVercelDeploymentFixture(token: input.token,});- await waitForDeploymentReady({- deploymentUrl,- });+ if (input.waitForHealth !== false) {+ await waitForDeploymentReady({+ deploymentUrl,+ });+ }return {appRoot,@@ -168,7 +172,7 @@ async function deployFixtureToVercel(input: {readonly scope?: string;readonly token: string;}): Promise<string> {- const args = ["dlx", VERCEL_CLI_PACKAGE, "deploy", "--json", "--yes", "--token", input.token];+ const args = ["dlx", VERCEL_CLI_PACKAGE, "deploy", "--json", "--yes"];if (input.scope !== undefined && input.scope.trim().length > 0) {args.push("--scope", input.scope.trim());@@ -186,6 +190,10 @@ async function deployFixtureToVercel(input: {const result = await runPnpmCommand({args,cwd: input.appRoot,+ env: {+ ...process.env,+ VERCEL_TOKEN: input.token,+ },});const deploymentUrl =extractDeploymentUrlFromJsonOutput(result.stdout) ??@@ -205,6 +213,15 @@ async function deployFixtureToVercel(input: {}function extractDeploymentUrlFromJsonOutput(stdout: string): string | undefined {+ try {+ const parsed: unknown = JSON.parse(stdout);+ const deploymentUrl = readDeploymentUrl(parsed);++ if (deploymentUrl !== undefined) {+ return deploymentUrl;+ }+ } catch {}+for (const line of stdout.split(/\r?\n/u).reverse()) {const trimmedLine = line.trim();@@ -213,21 +230,42 @@ function extractDeploymentUrlFromJsonOutput(stdout: string): string | undefined}try {- const parsed = JSON.parse(trimmedLine) as {- url?: unknown;- };+ const parsed: unknown = JSON.parse(trimmedLine);+ const deploymentUrl = readDeploymentUrl(parsed);- if (typeof parsed.url !== "string" || parsed.url.trim().length === 0) {- continue;+ if (deploymentUrl !== undefined) {+ return deploymentUrl;}-- return normalizeDeploymentUrl(parsed.url);} catch {}}return undefined;}+function readDeploymentUrl(value: unknown): string | undefined {+ if (!isRecord(value)) {+ return undefined;+ }++ if (typeof value.url === "string" && value.url.trim().length > 0) {+ return normalizeDeploymentUrl(value.url);+ }++ if (+ isRecord(value.deployment) &&+ typeof value.deployment.url === "string" &&+ value.deployment.url.trim().length > 0+ ) {+ return normalizeDeploymentUrl(value.deployment.url);+ }++ return undefined;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}+function extractDeploymentUrlFromText(output: string): string | undefined {const urlMatches = output.match(/https:\/\/[a-zA-Z0-9.-]+\.vercel\.app/gu);diff --git a/packages/eve/test/scenarios/framework-next-build.scenario.test.ts b/packages/eve/test/scenarios/framework-next-build.scenario.test.tsindex 1088fd05d..b1c0cbcdb 100644--- a/packages/eve/test/scenarios/framework-next-build.scenario.test.ts+++ b/packages/eve/test/scenarios/framework-next-build.scenario.test.ts@@ -1,10 +1,62 @@+import { access, readFile } from "node:fs/promises";+import { join } from "node:path";import { fileURLToPath } from "node:url";-import { describe, it } from "vitest";+import { describe, expect, it } from "vitest";+import type { ScenarioAppDescriptor } from "../../src/internal/testing/scenario-app.js";+import { createNextEveProxyDescriptor } from "../../src/internal/testing/scenario-apps/next-eve-proxy.js";+import { useScenarioApp } from "../../src/internal/testing/scenario-app.js";import { runPnpmCommand } from "../../src/internal/testing/run-pnpm-command.js";const REPO_ROOT = fileURLToPath(new URL("../../../..", import.meta.url));+const VERCEL_GENERATED_SERVICES_VERSION = "55.0.0";+const VERCEL_PNPM_10_PROJECT_CREATED_AT = Date.UTC(2026, 6, 13);+const scenarioApp = useScenarioApp();++const NEXT_EVE_PROXY_DESCRIPTOR = createNextEveProxyDescriptor({+ installDependencies: true,+ vercelVersion: VERCEL_GENERATED_SERVICES_VERSION,+});+const NEXT_EVE_MIDDLEWARE_DESCRIPTOR = {+ ...NEXT_EVE_PROXY_DESCRIPTOR,+ files: {+ ...NEXT_EVE_PROXY_DESCRIPTOR.files,+ ".vercel/project.json": `${JSON.stringify(+ {+ orgId: "team_eve_scenario",+ projectId: "prj_eve_scenario",+ projectName: "next-eve-middleware",+ settings: {+ buildCommand: "pnpm exec next build",+ createdAt: VERCEL_PNPM_10_PROJECT_CREATED_AT,+ framework: "nextjs",+ nodeVersion: "24.x",+ outputDirectory: null,+ rootDirectory: null,+ },+ },+ null,+ 2,+ )}\n`,+ },+ name: "next-eve-middleware",+} satisfies ScenarioAppDescriptor;++async function readVercelOutputRoutes(outputRoot: string): Promise<readonly unknown[]> {+ const config: unknown = JSON.parse(await readFile(join(outputRoot, "config.json"), "utf8"));++ if (+ typeof config !== "object" ||+ config === null ||+ !("routes" in config) ||+ !Array.isArray(config.routes)+ ) {+ throw new Error("Expected Vercel Build Output config.json to contain a routes array.");+ }++ return config.routes;+}describe("framework-next build", () => {it("builds the Next.js framework fixture after regenerating eve dist", async () => {@@ -13,4 +65,37 @@ describe("framework-next build", () => {cwd: REPO_ROOT,});}, 180_000);++ it("preserves Next middleware when Vercel assembles the generated eve service", async () => {+ const app = await scenarioApp(NEXT_EVE_MIDDLEWARE_DESCRIPTOR);++ await runPnpmCommand({+ args: ["exec", "vercel", "build", "--yes"],+ cwd: app.appRoot,+ });++ const outputRoot = join(app.appRoot, ".vercel", "output");+ const routes = await readVercelOutputRoutes(outputRoot);++ expect(routes).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ middlewarePath: "/_middleware" }),+ expect.objectContaining({+ destination: { service: "eve", type: "service" },+ src: "^/eve/v1/(.*)$",+ }),+ ]),+ );+ await expect(+ access(join(outputRoot, "functions", "_middleware.func", ".vc-config.json")),+ ).resolves.toBeUndefined();+ await expect(+ access(join(outputRoot, "services", "eve", "functions", "__server.func", ".vc-config.json")),+ ).resolves.toBeUndefined();+ await expect(+ access(+ join(outputRoot, "services", "eve", "functions", "_middleware.func", ".vc-config.json"),+ ),+ ).resolves.toBeUndefined();+ }, 240_000);});diff --git a/packages/eve/test/vercel/next-eve-proxy.vercel.test.ts b/packages/eve/test/vercel/next-eve-proxy.vercel.test.tsnew file mode 100644index 000000000..42c9d1e48--- /dev/null+++ b/packages/eve/test/vercel/next-eve-proxy.vercel.test.ts@@ -0,0 +1,70 @@+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { createNextEveProxyDescriptor } from "../../src/internal/testing/scenario-apps/next-eve-proxy.js";+import {+ createTarballVercelDeploymentFixture,+ type TarballVercelDeploymentFixture,+} from "../helpers/vercel-deployment-fixture.js";++const REQUIRED_VERCEL_ENV_NAMES = ["VERCEL_TOKEN", "VERCEL_ORG_ID", "VERCEL_PROJECT_ID"] as const;+const missingEnvironmentVariables = REQUIRED_VERCEL_ENV_NAMES.filter(+ (name) => !hasEnvironmentVariable(name),+);++if (missingEnvironmentVariables.length > 0) {+ throw new Error(+ [+ "Missing required environment variables for Next.js proxy Vercel deployment tests.",+ `Set: ${missingEnvironmentVariables.join(", ")}`,+ ].join("\n"),+ );+}++describe.sequential("Next.js proxy with generated eve service", () => {+ let deploymentFixture: TarballVercelDeploymentFixture | undefined;++ beforeAll(async () => {+ deploymentFixture = await createTarballVercelDeploymentFixture({+ descriptor: createNextEveProxyDescriptor(),+ orgId: readRequiredEnvironmentVariable("VERCEL_ORG_ID"),+ prefix: "eve-vercel-next-proxy-",+ projectId: readRequiredEnvironmentVariable("VERCEL_PROJECT_ID"),+ scope: readOptionalEnvironmentVariable("VERCEL_SCOPE"),+ token: readRequiredEnvironmentVariable("VERCEL_TOKEN"),+ waitForHealth: false,+ });+ }, 20 * 60_000);++ afterAll(async () => {+ await deploymentFixture?.cleanup();+ deploymentFixture = undefined;+ });++ it("deploys from source without rejecting the host middleware mapping", () => {+ if (deploymentFixture === undefined) {+ throw new Error("Expected Vercel deployment fixture to be initialized.");+ }++ expect(deploymentFixture.deploymentUrl).toMatch(/^https:\/\//u);+ });+});++function hasEnvironmentVariable(name: string): boolean {+ return readOptionalEnvironmentVariable(name) !== undefined;+}++function readOptionalEnvironmentVariable(name: string): string | undefined {+ const value = process.env[name]?.trim();++ return value === undefined || value.length === 0 ? undefined : value;+}++function readRequiredEnvironmentVariable(name: string): string {+ const value = readOptionalEnvironmentVariable(name);++ if (value === undefined) {+ throw new Error(`Missing required environment variable: ${name}`);+ }++ return value;+}