The Open Framework for Building Agents
fix(eve): stub server-only and client-only in every bundle (#5260)
Andrew Barba9bd75df1fcba
diff --git a/.changeset/pseudo-packages-everywhere.md b/.changeset/pseudo-packages-everywhere.mdnew file mode 100644index 000000000..fcb1a96f0--- /dev/null+++ b/.changeset/pseudo-packages-everywhere.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`server-only` and `client-only` imports now load as empty modules in every eve bundle, so tools, channels, workflow steps, and shared workspace packages that import them build and boot without `--conditions=react-server` or a direct dependency. Thanks @jakeleventhal for the original implementation in #3752.diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex c1ae041a0..c5c75f41d 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -210,8 +210,13 @@ eve build [--profile <path>] [--skip-sandbox-prewarm]Compiles and bundles in an invocation-owned directory under `.eve/builds/`, prepares sandbox artifacts, then publishes the completed host output and prints its path. Scratch workspaces are removed after success or failure. Pass `--skip-sandbox-prewarm` when you only need compiled output, such as before a separate typecheck. Skipping preparation can produce output that cannot start its configured sandbox, so do not deploy that output.Authored bundles preserve custom Node.js resolution conditions supplied through `--conditions`,-`-C`, or `NODE_OPTIONS`. For example, `NODE_OPTIONS="--conditions=react-server" eve build`-keeps a channel's `server-only` imports on the same export used during compilation.+`-C`, or `NODE_OPTIONS`, so compilation and the bundle resolve each package to the same export.+For example, `NODE_OPTIONS="--conditions=react-server" eve build` selects the `react-server`+export of packages that publish one.++eve loads `server-only` and `client-only` imports as empty modules in every bundle it builds. Code+shared with a Next.js app can keep these imports without a resolution condition, and your app does+not need to depend on either package.| Flag | Type | Default | Description || ------------------------ | ------ | ------- | --------------------------------------------------------------------------------------------- |diff --git a/packages/eve/src/internal/bundler/nitro-rolldown.ts b/packages/eve/src/internal/bundler/nitro-rolldown.tsindex a507ede6c..bc2a4eefd 100644--- a/packages/eve/src/internal/bundler/nitro-rolldown.ts+++ b/packages/eve/src/internal/bundler/nitro-rolldown.ts@@ -1,6 +1,7 @@import { createRequire } from "node:module";import { pathToFileURL } from "node:url";+import { createPseudoPackagePlugin } from "#internal/bundler/pseudo-packages.js";import {type BundlerDefaultLogHandler,onVendoredDependencyLog,@@ -104,16 +105,21 @@ export async function parseWithNitroRolldownAst(* bundle whose consumer expects one in-memory file; use this directly only* for multi-file, written-to-disk output. Warnings raised only by dependency* code are dropped unless the caller supplies its own `onLog`, except- * unresolved imports.+ * unresolved imports. Pseudo-packages such as `server-only` load as empty+ * modules ahead of every caller plugin.*/export async function buildWithNitroRolldown(- options: Record<string, unknown> & { readonly experimental?: Record<string, unknown> },+ options: Record<string, unknown> & {+ readonly experimental?: Record<string, unknown>;+ readonly plugins?: readonly unknown[];+ },): Promise<RolldownOutput> {assertCustomRolldownConditionNames(options);const { build } = await loadNitroRolldown();return await build({onLog: onRolldownBuildLog,...options,+ plugins: [createPseudoPackagePlugin(), ...(options.plugins ?? [])],// Debug module IDs contain temporary workspace paths and destabilize runtime fingerprints.experimental: { ...options.experimental, attachDebugInfo: "none" },});diff --git a/packages/eve/src/internal/bundler/pseudo-packages.ts b/packages/eve/src/internal/bundler/pseudo-packages.tsnew file mode 100644index 000000000..fe8d2c719--- /dev/null+++ b/packages/eve/src/internal/bundler/pseudo-packages.ts@@ -0,0 +1,30 @@+// Marker packages that only assert which React environment imports them. eve+// bundles run on the server outside React's module graph, so each loads as an+// empty module instead of resolving: `server-only` throws without the+// `react-server` condition, and a strict pnpm layout often cannot resolve the+// marker from where the bundle is evaluated.+const PSEUDO_PACKAGES = new Set([+ "server-only",+ "client-only",+ "next/dist/compiled/server-only",+ "next/dist/compiled/client-only",+]);++const PSEUDO_PACKAGE_ID_PREFIX = "\0eve-pseudo-package:";++/** Must run before any plugin that externalizes or resolves package imports. */+export function createPseudoPackagePlugin() {+ return {+ name: "eve-pseudo-packages",+ resolveId(source: string) {+ return PSEUDO_PACKAGES.has(source)+ ? { id: `${PSEUDO_PACKAGE_ID_PREFIX}${source}` }+ : undefined;+ },+ load(id: string) {+ return id.startsWith(PSEUDO_PACKAGE_ID_PREFIX)+ ? { code: "", moduleType: "js" as const }+ : undefined;+ },+ };+}diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.tsindex c9b4dfada..d28088b50 100644--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts@@ -28,6 +28,7 @@ import { prepareSkillServerAssets } from "#internal/nitro/host/skill-server-asseimport { createExtensionScopePlugin } from "#internal/bundler/extension-scope-plugin.js";import { extensionOverridePaths } from "#compiler/extension-mount-bindings.js";import { createExtensionMountPlugin } from "#internal/bundler/extension-mount-plugin.js";+import { createPseudoPackagePlugin } from "#internal/bundler/pseudo-packages.js";import {createExtensionExternalDependencyPlugin,resolveExtensionExternalDependencyPaths,@@ -611,7 +612,10 @@ function createApplicationNitroBundlerConfiguration(preparedHost.compileResult.manifest,...preparedHost.compileResult.manifest.subagents.map((subagent) => subagent.agent),].flatMap((node) => node.extensionMounts);+ // eve's plugins run before Nitro's externals and tracing plugins, so a+ // pseudo-package never reaches the output as a live import.const nitroBundlerPlugins = [+ createPseudoPackagePlugin(),options.development ? null : createDevelopmentRuntimePrunePlugin(),compiledSandboxProviderPrunePlugin,createOptionalEngineDependencyPlugin(unconfiguredOptionalEnginePackages),diff --git a/packages/eve/src/internal/nitro/host/react-server-module-map.scenario.test.ts b/packages/eve/src/internal/nitro/host/react-server-module-map.scenario.test.tsindex ee6fddf49..f555f7084 100644--- a/packages/eve/src/internal/nitro/host/react-server-module-map.scenario.test.ts+++ b/packages/eve/src/internal/nitro/host/react-server-module-map.scenario.test.ts@@ -11,50 +11,88 @@ const execFileAsync = promisify(execFile);describe("react-server module maps", () => {const scenarioApp = useScenarioApp();- // NODE_OPTIONS conditions resolve through the same `authoredModuleConditions`- // call; its unit test owns reading them from the environment.- it("builds and loads server-only channels with conditions from the Node command line", async () => {- const app = await scenarioApp({- name: "react-server-module-map",- installDependencies: true,- dependencies: { "server-only": "0.0.1" },- files: {- "agent/agent.ts": 'export default { model: "openai/gpt-5.4" };',- "agent/instructions.md": "Reply concisely.",- "agent/channels/probe.ts":- 'import "server-only"; import { defineChannel, GET } from "eve/channels"; export default defineChannel({ routes: [GET("/probe", () => new Response("server-only-ready"))] });',- "check.mjs": [- 'import { createServer } from "node:net";',- 'import { spawn } from "node:child_process";',- 'import { once } from "node:events";',- 'const portProbe = createServer().listen(0, "127.0.0.1");',- 'await once(portProbe, "listening");',- "const port = portProbe.address().port;",- "await new Promise((resolve) => portProbe.close(resolve));",- 'const child = spawn(process.execPath, [".output/server/index.mjs"], { env: { ...process.env, HOST: "127.0.0.1", PORT: String(port) }, stdio: "ignore" });',- 'const exited = once(child, "exit");',- "try {",- " for (let attempt = 0; attempt < 100; attempt++) {",- " try { const response = await fetch(`http://127.0.0.1:${port}/probe`); if (response.ok) { console.log(await response.text()); break; } } catch {}",- " await new Promise((resolve) => setTimeout(resolve, 100));",- " }",- '} finally { if (child.exitCode === null) child.kill("SIGTERM"); await exited; }',- ].join("\n"),- },- });- await execFileAsync(- process.execPath,- ["--conditions=react-server", join(app.appRoot, "node_modules/eve/bin/eve.js"), "build"],- {+ // `@acme/db` declares `server-only` itself, so the app cannot resolve it+ // under pnpm's strict layout. NODE_OPTIONS conditions resolve through the+ // same `authoredModuleConditions` call; its unit test owns reading them from+ // the environment.+ it.each([+ { conditions: [], expected: "server-only-ready:default" },+ { conditions: ["--conditions=react-server"], expected: "server-only-ready:react-server" },+ ])(+ "builds and serves a channel importing server-only with conditions $conditions",+ async ({ conditions, expected }) => {+ const app = await scenarioApp({+ name: "react-server-module-map",+ installDependencies: true,+ dependencies: { "@acme/condition": "workspace:*", "@acme/db": "workspace:*" },+ files: {+ "pnpm-workspace.yaml": "packages:\n - packages/*\n",+ "packages/db/package.json": JSON.stringify({+ name: "@acme/db",+ type: "module",+ exports: "./index.ts",+ dependencies: { "server-only": "0.0.1" },+ }),+ "packages/db/index.ts": [+ 'import "server-only";',+ 'export const message = "server-only-ready";',+ 'export async function lookup() { "use step"; return message; }',+ ].join("\n"),+ "packages/condition/package.json": JSON.stringify({+ name: "@acme/condition",+ type: "module",+ exports: { "react-server": "./react-server.js", default: "./default.js" },+ }),+ "packages/condition/react-server.js": 'export const condition = "react-server";',+ "packages/condition/default.js": 'export const condition = "default";',+ "agent/agent.ts": 'export default { model: "openai/gpt-5.4" };',+ "agent/instructions.md": "Reply concisely.",+ // Step modules reach the Nitro bundle directly instead of through the module map.+ "agent/tools/lookup.ts": [+ 'import "server-only";',+ 'import { defineWorkflowTool } from "eve/tools";',+ 'import { lookup } from "@acme/db";',+ 'export default defineWorkflowTool({ description: "Look up the message.", inputSchema: {}, async execute() { "use workflow"; return lookup(); } });',+ ].join("\n"),+ "agent/channels/probe.ts": [+ 'import { condition } from "@acme/condition";',+ 'import { message } from "@acme/db";',+ 'import { defineChannel, GET } from "eve/channels";',+ 'export default defineChannel({ routes: [GET("/probe", () => new Response(`${message}:${condition}`))] });',+ ].join("\n"),+ "check.mjs": [+ 'import { createServer } from "node:net";',+ 'import { spawn } from "node:child_process";',+ 'import { once } from "node:events";',+ 'const portProbe = createServer().listen(0, "127.0.0.1");',+ 'await once(portProbe, "listening");',+ "const port = portProbe.address().port;",+ "await new Promise((resolve) => portProbe.close(resolve));",+ 'const child = spawn(process.execPath, [".output/server/index.mjs"], { env: { ...process.env, HOST: "127.0.0.1", PORT: String(port) }, stdio: "ignore" });',+ 'const exited = once(child, "exit");',+ "try {",+ " for (let attempt = 0; attempt < 100; attempt++) {",+ " try { const response = await fetch(`http://127.0.0.1:${port}/probe`); if (response.ok) { console.log(await response.text()); break; } } catch {}",+ " await new Promise((resolve) => setTimeout(resolve, 100));",+ " }",+ '} finally { if (child.exitCode === null) child.kill("SIGTERM"); await exited; }',+ ].join("\n"),+ },+ });+ await execFileAsync(+ process.execPath,+ [...conditions, join(app.appRoot, "node_modules/eve/bin/eve.js"), "build"],+ {+ cwd: app.appRoot,+ timeout: 90_000,+ maxBuffer: 10 * 1024 * 1024,+ },+ );+ const { stdout } = await execFileAsync(process.execPath, ["check.mjs"], {cwd: app.appRoot,- timeout: 90_000,- maxBuffer: 10 * 1024 * 1024,- },- );- const { stdout } = await execFileAsync(process.execPath, ["check.mjs"], {- cwd: app.appRoot,- timeout: 20_000,- });- expect(stdout).toContain("server-only-ready");- });+ timeout: 20_000,+ });+ expect(stdout.trim()).toBe(expected);+ },+ );});diff --git a/packages/eve/src/internal/testing/workflow-step-registrations.ts b/packages/eve/src/internal/testing/workflow-step-registrations.tsindex 6961af26d..40e404d91 100644--- a/packages/eve/src/internal/testing/workflow-step-registrations.ts+++ b/packages/eve/src/internal/testing/workflow-step-registrations.ts@@ -6,7 +6,6 @@ import { buildSingleRolldownChunk } from "#internal/bundler/nitro-rolldown.js";import {createEvePackageImportsPlugin,createWorkflowImport,- createWorkflowPseudoPackagePlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin,WORKFLOW_SOURCE_EXTENSIONS,@@ -53,7 +52,6 @@ export async function bundleWorkflowStepRegistrations(input: {platform: "node",plugins: [createWorkflowVirtualEntryPlugin(virtualEntrySource),- createWorkflowPseudoPackagePlugin(),{name: "eve-workflow-runtime-aliases",resolveId(source: string) {diff --git a/packages/eve/src/internal/workflow-bundle/builder-support.ts b/packages/eve/src/internal/workflow-bundle/builder-support.tsindex 51f9bdf8a..e05e6abb6 100644--- a/packages/eve/src/internal/workflow-bundle/builder-support.ts+++ b/packages/eve/src/internal/workflow-bundle/builder-support.ts@@ -32,12 +32,6 @@ export interface WorkflowBundleBuilderOptions {/** Test-harness-only: also scans `src/internal/testing/`. */includeTestFixtures?: boolean;}-const PSEUDO_PACKAGES = new Set([- "server-only",- "client-only",- "next/dist/compiled/server-only",- "next/dist/compiled/client-only",-]);const NODE_BUILTIN_MODULES = new Set([...builtinModules,...builtinModules.map((moduleName) => `node:${moduleName}`),@@ -194,29 +188,6 @@ export function createWorkflowVirtualEntryPlugin(source: string): WorkflowRolldo};}-export function createWorkflowPseudoPackagePlugin(): WorkflowRolldownPlugin {- return {- name: "eve-workflow-pseudo-packages",- resolveId(source: string) {- if (!PSEUDO_PACKAGES.has(source)) {- return undefined;- }-- return { id: `\0eve-workflow-pseudo-package:${source}` };- },- load(id: string) {- if (!id.startsWith("\0eve-workflow-pseudo-package:")) {- return undefined;- }-- return {- code: "",- moduleType: "js",- };- },- };-}-/*** `workflow` resolves to the body-side shim. A `workflow/api` import still live* after step bodies were stubbed means a body calls the runtime API; fail thediff --git a/packages/eve/src/internal/workflow-bundle/builder.ts b/packages/eve/src/internal/workflow-bundle/builder.tsindex 0f7189c6d..9d782dfbd 100644--- a/packages/eve/src/internal/workflow-bundle/builder.ts+++ b/packages/eve/src/internal/workflow-bundle/builder.ts@@ -26,7 +26,6 @@ import {createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowDriverAliasPlugin,- createWorkflowPseudoPackagePlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin,WORKFLOW_SOURCE_EXTENSIONS,@@ -326,7 +325,6 @@ export class WorkflowBundleBuilder {platform: "neutral",plugins: [createWorkflowVirtualEntryPlugin(virtualEntrySource),- createWorkflowPseudoPackagePlugin(),createWorkflowDriverAliasPlugin(this.config.workingDir),createAuthoredRelativeExtensionResolverPlugin({extensions: WORKFLOW_SOURCE_EXTENSIONS,