The Open Framework for Building Agents
feat(eve): share framework dev-server startup between eve/next and eve/nuxt (#4110)
Hugo3f6d9cff6251
diff --git a/.changeset/nuxt-dev-server-parity.md b/.changeset/nuxt-dev-server-parity.mdnew file mode 100644index 000000000..0e50ddf06--- /dev/null+++ b/.changeset/nuxt-dev-server-parity.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`eve/nuxt` now shares the Next.js dev-server startup: it waits up to 180 seconds by default (configurable with the new `devServerTimeoutMs` option), ignores non-local URLs in eve's startup output, and prefixes eve's logs with `[eve:dev]`. Restarting `nuxt dev` no longer leaves eve requests proxied to a stopped dev server.diff --git a/docs/guides/frontend/nuxt.mdx b/docs/guides/frontend/nuxt.mdxindex 29f454520..8ceef6537 100644--- a/docs/guides/frontend/nuxt.mdx+++ b/docs/guides/frontend/nuxt.mdx@@ -30,7 +30,26 @@ export default defineNuxtConfig({});```-The `eve` key accepts only two options, `eveRoot` and `eveBuildCommand`.+### `eve/nuxt` options++All fields are optional.++| Option | Type | Default | Purpose |+| -------------------- | -------- | ----------------- | ----------------------------------------------------------------------------------------------------------------- |+| `eveRoot` | `string` | Nuxt project root | eve project root, relative to the Nuxt project root unless absolute. |+| `eveBuildCommand` | `string` | generated | Build command for the generated eve Vercel service. |+| `devServerTimeoutMs` | `number` | `180000` | Maximum time to wait for the eve development server to start, including when another Nuxt process is starting it. |++For slow cold starts, increase the development timeout:++```ts+export default defineNuxtConfig({+ modules: ["eve/nuxt"],+ eve: {+ devServerTimeoutMs: 300_000,+ },+});+```## Call the composable@@ -65,7 +84,7 @@ The browser still needs a production authentication policy. See [Authenticate br## Dev vs deploy topology-- **Local dev.** `npm run dev` starts the eve dev server next to `nuxt dev` and proxies the eve routes through it. As far as the browser knows, everything is the Nuxt origin.+- **Local dev.** `npm run dev` starts the eve dev server next to `nuxt dev` and proxies the eve routes through it. As far as the browser knows, everything is the Nuxt origin. Concurrent Nuxt processes for the same eve root share one eve dev server. Set `EVE_BASE_URL` to proxy to an eve dev server you already run instead.- **Vercel.** The web app and the eve runtime deploy as a single project. On Vercel builds the module adds Build Output [`services`](https://vercel.com/docs/services) for eve and `routes` that send `/eve/v1/**` to that service before filesystem routing; the Nuxt app itself remains the default app. No `vercel.json` is required. By default the generated service runs the installed eve binary from the agent root, so the agent directory does not need its own `package.json`. When the agent needs its own build step, set `eveBuildCommand`:```ts@@ -77,13 +96,14 @@ The browser still needs a production authentication policy. See [Authenticate br});```-- **Non-Vercel hosts.** Point Nuxt at a separate eve origin with `EVE_NUXT_PRODUCTION_ORIGIN`. To override the local port (default `4274`), use `EVE_NUXT_PRODUCTION_PORT`:+- **Non-Vercel hosts.** The module does not start eve in production; run the eve service yourself. `nuxt build` writes a proxy rule that sends `/eve/v1/**` to `EVE_NUXT_PRODUCTION_ORIGIN`, or to `http://127.0.0.1:4274` when that variable is unset. Override the local port with `EVE_NUXT_PRODUCTION_PORT`. Set these variables when you run `nuxt build`, because the destination is fixed in the build output:```bashEVE_NUXT_PRODUCTION_ORIGIN=https://agent.example.com npm run build- EVE_NUXT_PRODUCTION_PORT=5000 npm run build && npm run preview```+ `eve build` and `nuxt build` both write `.output/`. When the agent lives in the Nuxt project root, build and serve eve from a separate directory (set `eveRoot` to it) so the two outputs do not overwrite each other. See [Self-host eve](../deployment/self-hosting) for running the eve service.+## Managing vercel.json yourselfWhen `vercel.json` declares [`services`](https://vercel.com/docs/services), the module generates nothing and your configuration owns routing. It must include the eve service (`framework: "eve"`) and a rewrite that exposes the eve transport, or the module fails the build:diff --git a/packages/eve/src/public/next/index.ts b/packages/eve/src/public/next/index.tsindex 63b93fbed..0f3f2680a 100644--- a/packages/eve/src/public/next/index.ts+++ b/packages/eve/src/public/next/index.ts@@ -7,8 +7,13 @@ import { findEveProjectContext } from "#internal/project-context.js";import { quoteVercelShellArgument, toVercelRelativePath } from "#internal/vercel/build-command.js";import { EVE_ROUTE_PREFIX } from "#protocol/routes.js";import { joinEveRoutePath } from "#shared/eve-route-path.js";+import { resolveDevServerTimeout } from "#shared/framework-eve-server.js";import { resolveEveBinaryPath } from "#shared/resolve-eve-binary.js";-import { NEXT_PHASE_PRODUCTION_BUILD, resolveEveDestinationPrefix } from "./server.js";+import {+ EVE_NEXT_HOST,+ NEXT_PHASE_PRODUCTION_BUILD,+ resolveEveDestinationPrefix,+} from "./server.js";import { ensureEveVercelOutputConfig } from "./vercel-output-config.js";/**@@ -162,18 +167,6 @@ function resolveApplicationRoot(appPath: string | undefined): string {return resolve(process.cwd(), appPath);}-function resolveDevServerTimeout(timeoutMs: number | undefined): number | undefined {- if (timeoutMs === undefined) {- return undefined;- }-- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {- throw new Error("eve Next.js development server timeout must be a positive number.");- }-- return timeoutMs;-}-function normalizeRoutePrefix(prefix: string): string {const prefixed = prefix.startsWith("/") ? prefix : `/${prefix}`;const normalized = prefixed.replace(/\/+$/, "");@@ -440,7 +433,7 @@ export function withEve<TConfig extends EveNextConfig>(options: WithEveOptions = {},): EveNextConfigFunction<TConfig> {const nextRoot = process.cwd();- const devServerTimeoutMs = resolveDevServerTimeout(options.devServerTimeoutMs);+ const devServerTimeoutMs = resolveDevServerTimeout(options.devServerTimeoutMs, EVE_NEXT_HOST);assertValidWithEveOptions(options);return async function eveNextConfig(phase, context) {const [agents, nextConfig] = await Promise.all([diff --git a/packages/eve/src/public/next/server.ts b/packages/eve/src/public/next/server.tsindex a0058adbd..987afca05 100644--- a/packages/eve/src/public/next/server.ts+++ b/packages/eve/src/public/next/server.ts@@ -1,41 +1,18 @@-import { spawn, type ChildProcess } from "node:child_process";-import { existsSync } from "node:fs";-import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises";-import { join } from "node:path";--import { resolvePackageRoot } from "#internal/application/package.js";-import { readDevelopmentRuntimeArtifactsRevision } from "#services/dev-client/runtime-artifacts.js";+import {+ resolveSharedEveDevServer,+ startEveProductionServer,+ type EveFrameworkHost,+ type EveProcessHandle,+} from "#shared/framework-eve-server.js";const EVE_BASE_URL_ENV = "EVE_BASE_URL";-const DEFAULT_SERVER_READY_TIMEOUT_MS = 180_000;-const DEV_SERVER_REGISTRY_TIMEOUT_MS = 180_000;-const DEV_SERVER_REGISTRY_POLL_MS = 100;-const DEV_SERVER_READINESS_TIMEOUT_MS = 1_000;-const DEV_SERVER_STALE_LOCK_MS = 30_000;-const EVE_CACHE_DIRECTORY_NAME = ".eve";-const EVE_NEXT_DEV_SERVER_FILE_NAME = "next-dev-server.json";-const EVE_NEXT_DEV_SERVER_LOCK_FILE_NAME = "next-dev-server.lock";-const ANSI_ESCAPE = String.fromCharCode(27);-const ANSI_ESCAPE_PATTERN = new RegExp(`${ANSI_ESCAPE}\\[[0-?]*[ -/]*[@-~]`, "g");-const SERVER_URL_CANDIDATE_PATTERN = /https?:\/\/[^\s"'<>]+/g;export const NEXT_PHASE_PRODUCTION_BUILD = "phase-production-build";--interface EveProcessHandle {- readonly origin: string;- readonly process?: ChildProcess;-}+export const EVE_NEXT_HOST: EveFrameworkHost = { label: "Next.js", slug: "next" };interface EveNextGlobalState {readonly servers: Map<string, Promise<EveProcessHandle>>;}-interface EveDevServerRegistry {- readonly appRoot: string;- readonly origin: string;- readonly pid: number | null;- readonly updatedAt: string;-}-const globalStateSymbol = Symbol.for("eve.next.state");function getGlobalState(): EveNextGlobalState {@@ -50,10 +27,6 @@ function getGlobalState(): EveNextGlobalState {return globalWithState[globalStateSymbol];}-function normalizeOrigin(origin: string): string {- return new URL(origin).origin;-}-function readEveBaseUrlEnvironment(): string | undefined {const configuredUrl = process.env[EVE_BASE_URL_ENV];@@ -61,457 +34,7 @@ function readEveBaseUrlEnvironment(): string | undefined {return undefined;}- return normalizeOrigin(configuredUrl);-}--function isNodeErrorWithCode(error: unknown, code: string): boolean {- return error instanceof Error && "code" in error && error.code === code;-}--function delay(ms: number): Promise<void> {- return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));-}--function isRecord(value: unknown): value is Record<string, unknown> {- return value !== null && typeof value === "object" && !Array.isArray(value);-}--function resolveEveCacheDirectory(appRoot: string): string {- return join(appRoot, EVE_CACHE_DIRECTORY_NAME);-}--function resolveEveDevServerRegistryPath(appRoot: string): string {- return join(resolveEveCacheDirectory(appRoot), EVE_NEXT_DEV_SERVER_FILE_NAME);-}--function resolveEveDevServerLockPath(appRoot: string): string {- return join(resolveEveCacheDirectory(appRoot), EVE_NEXT_DEV_SERVER_LOCK_FILE_NAME);-}--function normalizeDevServerRegistry(value: unknown): EveDevServerRegistry | undefined {- if (!isRecord(value)) {- return undefined;- }-- if (- typeof value.appRoot !== "string" ||- typeof value.origin !== "string" ||- typeof value.updatedAt !== "string"- ) {- return undefined;- }-- if (value.pid !== null && typeof value.pid !== "number") {- return undefined;- }-- try {- return {- appRoot: value.appRoot,- origin: normalizeOrigin(value.origin),- pid: value.pid,- updatedAt: value.updatedAt,- };- } catch {- return undefined;- }-}--async function readUsableEveDevServerRegistry(appRoot: string): Promise<string | undefined> {- try {- const registry = normalizeDevServerRegistry(- JSON.parse(await readFile(resolveEveDevServerRegistryPath(appRoot), "utf8")) as unknown,- );-- if (registry === undefined || registry.appRoot !== appRoot) {- return undefined;- }-- if (- (await readDevelopmentRuntimeArtifactsRevision({- serverUrl: registry.origin,- timeoutMs: DEV_SERVER_READINESS_TIMEOUT_MS,- })) === undefined- ) {- return undefined;- }-- return registry.origin;- } catch (error) {- if (isNodeErrorWithCode(error, "ENOENT")) {- return undefined;- }-- throw error;- }-}--async function writeEveDevServerRegistry(appRoot: string, handle: EveProcessHandle): Promise<void> {- await mkdir(resolveEveCacheDirectory(appRoot), {- recursive: true,- });- await writeFile(- resolveEveDevServerRegistryPath(appRoot),- `${JSON.stringify(- {- appRoot,- origin: handle.origin,- pid: handle.process?.pid ?? null,- updatedAt: new Date().toISOString(),- } satisfies EveDevServerRegistry,- null,- 2,- )}\n`,- );-}--async function removeStaleEveDevServerLock(lockPath: string): Promise<void> {- try {- const lockStat = await stat(lockPath);- if (Date.now() - lockStat.mtimeMs > DEV_SERVER_STALE_LOCK_MS) {- await rm(lockPath, {- force: true,- });- }- } catch (error) {- if (!isNodeErrorWithCode(error, "ENOENT")) {- throw error;- }- }-}--async function acquireEveDevServerLock(- appRoot: string,- timeoutMs: number,-): Promise<() => Promise<void>> {- const cacheDirectory = resolveEveCacheDirectory(appRoot);- const lockPath = resolveEveDevServerLockPath(appRoot);- const deadline = Date.now() + timeoutMs;-- await mkdir(cacheDirectory, {- recursive: true,- });-- while (true) {- try {- const lockFile = await open(lockPath, "wx");- await lockFile.writeFile(`${String(process.pid)}\n`);- await lockFile.close();-- return async () => {- await rm(lockPath, {- force: true,- });- };- } catch (error) {- if (!isNodeErrorWithCode(error, "EEXIST")) {- throw error;- }-- const registeredOrigin = await readUsableEveDevServerRegistry(appRoot);- if (registeredOrigin !== undefined) {- return async () => {};- }-- await removeStaleEveDevServerLock(lockPath);-- if (Date.now() > deadline) {- throw new Error(- `Timed out after ${timeoutMs}ms waiting for another Next.js process to start eve.`,- );- }-- await delay(DEV_SERVER_REGISTRY_POLL_MS);- }- }-}--function createEveBinaryPath(): string {- return join(resolvePackageRoot(), "bin", "eve.js");-}--function isLoopbackHostname(hostname: string): boolean {- return (- hostname === "localhost" ||- hostname === "::1" ||- hostname === "[::1]" ||- /^127(?:\.\d{1,3}){3}$/.test(hostname)- );-}--function parseLocalServerOrigin(urlText: string): string | undefined {- const url = URL.parse(urlText);- // Dev-server discovery reads mixed subprocess output. Build metadata and- // dependency warnings can print unrelated URLs before eve reports its listener,- // but withEve only owns the app-local loopback server it started.- if (- url === null ||- (url.protocol !== "http:" && url.protocol !== "https:") ||- !isLoopbackHostname(url.hostname) ||- url.port.length === 0- ) {- return undefined;- }-- return url.origin;-}--function findLocalServerOrigin(output: string): string | undefined {- for (const match of output.matchAll(SERVER_URL_CANDIDATE_PATTERN)) {- const candidate = match[0];- const origin = parseLocalServerOrigin(candidate);- if (origin !== undefined) {- return origin;- }- }-- return undefined;-}--function formatEveDevOutputLine(line: string, logLabel: string | undefined): string | undefined {- const normalizedLine = line.replace(/\r$/, "");- const trimmedLine = normalizedLine.replace(ANSI_ESCAPE_PATTERN, "").trim();-- if (- trimmedLine.length === 0 ||- /^☰eve\b/.test(trimmedLine) ||- trimmedLine === "CONFIGURATION_FIELD_CONFLICT" ||- trimmedLine.startsWith("[CONFIGURATION_FIELD_CONFLICT]")- ) {- return undefined;- }-- const tag = logLabel === undefined ? "[eve:dev]" : `[eve:dev:${logLabel}]`;- const serverMatch = /server listening at\s+(https?:\/\/[^\s]+)/i.exec(normalizedLine);- if (serverMatch !== null) {- return `${tag} server listening at ${serverMatch[1]}`;- }-- return `${tag} ${normalizedLine}`;-}--function createEveDevOutputWriter(input: {- readonly logLabel?: string;- readonly stream: NodeJS.WriteStream;-}): {- readonly flush: () => void;- readonly write: (chunk: Buffer) => void;-} {- let pendingLine = "";-- const writeLine = (line: string) => {- const formattedLine = formatEveDevOutputLine(line, input.logLabel);- if (formattedLine !== undefined) {- input.stream.write(`${formattedLine}\n`);- }- };-- return {- flush() {- if (pendingLine.length === 0) {- return;- }-- writeLine(pendingLine);- pendingLine = "";- },- write(chunk) {- pendingLine += chunk.toString("utf8");- const lines = pendingLine.split("\n");- pendingLine = lines.pop() ?? "";-- for (const line of lines) {- writeLine(line);- }- },- };-}--function startServerProcess(input: {- readonly args: readonly string[];- readonly command: string;- readonly cwd: string;- readonly env?: Record<string, string>;- readonly logLabel?: string;- readonly timeoutMs?: number;-}): Promise<EveProcessHandle> {- return new Promise((resolvePromise, reject) => {- const child = spawn(input.command, input.args, {- cwd: input.cwd,- env: {- ...process.env,- ...input.env,- },- stdio: ["ignore", "pipe", "pipe"],- });- const stderrWriter = createEveDevOutputWriter({- logLabel: input.logLabel,- stream: process.stderr,- });- const stdoutWriter = createEveDevOutputWriter({- logLabel: input.logLabel,- stream: process.stdout,- });- const timeout = setTimeout(() => {- child.kill();- reject(- new Error(- `Timed out after ${input.timeoutMs ?? DEFAULT_SERVER_READY_TIMEOUT_MS}ms waiting for eve to print its server URL.`,- ),- );- }, input.timeoutMs ?? DEFAULT_SERVER_READY_TIMEOUT_MS);-- const cleanup = () => {- clearTimeout(timeout);- child.off("error", handleError);- child.off("exit", handleEarlyExit);- };- const flushOutput = () => {- stdoutWriter.flush();- stderrWriter.flush();- };- const handleError = (error: Error) => {- flushOutput();- cleanup();- reject(error);- };- const handleEarlyExit = (code: number | null, signal: NodeJS.Signals | null) => {- flushOutput();- cleanup();- reject(- new Error(- `eve server process exited before printing its server URL (code ${String(code)}, signal ${String(signal)}).`,- ),- );- };- const handleOutput = (chunk: Buffer) => {- const origin = findLocalServerOrigin(chunk.toString("utf8"));-- if (origin === undefined) {- return;- }-- cleanup();- resolvePromise({- origin,- process: child,- });- };- const handleStdout = (chunk: Buffer) => {- stdoutWriter.write(chunk);- handleOutput(chunk);- };- const handleStderr = (chunk: Buffer) => {- stderrWriter.write(chunk);- handleOutput(chunk);- };-- child.once("error", handleError);- child.once("exit", handleEarlyExit);- child.stdout.on("data", handleStdout);- child.stderr.on("data", handleStderr);- });-}--function installProcessShutdown(handle: EveProcessHandle): EveProcessHandle {- const childProcess = handle.process;-- if (childProcess === undefined) {- return handle;- }-- const close = () => {- if (!childProcess.killed) {- childProcess.kill();- }- };-- process.once("beforeExit", close);- process.once("exit", close);-- return handle;-}--function startEveDevServer(- appRoot: string,- timeoutMs: number,- logLabel: string | undefined,- workspaceAgentName: string | undefined,-): Promise<EveProcessHandle> {- return startServerProcess({- args: [- createEveBinaryPath(),- "dev",- "--no-ui",- "--port",- "0",- ...(workspaceAgentName === undefined ? [] : ["--agent", workspaceAgentName]),- ],- command: process.execPath,- cwd: appRoot,- logLabel,- timeoutMs,- }).then((handle) => {- return installProcessShutdown(handle);- });-}--function startEveProductionServer(input: {- readonly appRoot: string;- readonly origin: string;-}): Promise<EveProcessHandle> {- const parsedOrigin = new URL(input.origin);- const port = parsedOrigin.port;- const serverEntry = join(input.appRoot, ".output", "server", "index.mjs");-- if (!existsSync(serverEntry)) {- throw new Error(- `eve production output is missing at ${serverEntry}. Run eve build from ${input.appRoot} before starting Next.js.`,- );- }-- return startServerProcess({- args: [serverEntry],- command: process.execPath,- cwd: input.appRoot,- env: {- HOST: parsedOrigin.hostname,- NITRO_HOST: parsedOrigin.hostname,- NITRO_PORT: port,- PORT: port,- },- }).then(installProcessShutdown);-}--async function resolveSharedEveDevServer(- appRoot: string,- timeoutMs: number,- logLabel: string | undefined,- workspaceAgentName: string | undefined,-): Promise<EveProcessHandle> {- const registeredOrigin = await readUsableEveDevServerRegistry(appRoot);- if (registeredOrigin !== undefined) {- return {- origin: registeredOrigin,- };- }-- const releaseLock = await acquireEveDevServerLock(appRoot, timeoutMs);-- try {- const lockedRegisteredOrigin = await readUsableEveDevServerRegistry(appRoot);- if (lockedRegisteredOrigin !== undefined) {- return {- origin: lockedRegisteredOrigin,- };- }-- const handle = await startEveDevServer(appRoot, timeoutMs, logLabel, workspaceAgentName);- await writeEveDevServerRegistry(appRoot, handle);- return handle;- } finally {- await releaseLock();- }+ return new URL(configuredUrl).origin;}export async function resolveEveDestinationPrefix(input: {@@ -539,6 +62,7 @@ export async function resolveEveDestinationPrefix(input: {? undefined: startEveProductionServer({appRoot: input.appRoot,+ host: EVE_NEXT_HOST,origin: input.productionServerOrigin,});if (productionServer !== undefined) {@@ -570,12 +94,13 @@ export async function resolveEveDestinationPrefix(input: {let server = state.servers.get(key);if (server === undefined) {- server = resolveSharedEveDevServer(- input.appRoot,- input.devServerTimeoutMs ?? DEV_SERVER_REGISTRY_TIMEOUT_MS,- input.logLabel,- input.workspaceAgentName,- ).catch((error) => {+ server = resolveSharedEveDevServer({+ appRoot: input.appRoot,+ host: EVE_NEXT_HOST,+ logLabel: input.logLabel,+ timeoutMs: input.devServerTimeoutMs,+ workspaceAgentName: input.workspaceAgentName,+ }).catch((error) => {state.servers.delete(key);throw error;});diff --git a/packages/eve/src/public/nuxt/dev-server.integration.test.ts b/packages/eve/src/public/nuxt/dev-server.integration.test.tsdeleted file mode 100644index e3896c4ee..000000000--- a/packages/eve/src/public/nuxt/dev-server.integration.test.ts+++ /dev/null@@ -1,50 +0,0 @@-import { mkdir, mkdtemp, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";--import { afterEach, describe, expect, it, vi } from "vitest";--import { EVE_BASE_URL_ENV, resolveSharedEveDevServer } from "./dev-server.js";--async function createTempAppRoot(): Promise<string> {- return await mkdtemp(join(tmpdir(), "eve-nuxt-dev-server-"));-}--async function writeRegistry(appRoot: string, registry: Record<string, unknown>): Promise<void> {- await mkdir(join(appRoot, ".eve"), { recursive: true });- await writeFile(- join(appRoot, ".eve", "nuxt-dev-server.json"),- `${JSON.stringify(registry, null, 2)}\n`,- );-}--afterEach(() => {- vi.unstubAllEnvs();- vi.unstubAllGlobals();- delete process.env[EVE_BASE_URL_ENV];-});--describe("resolveSharedEveDevServer", () => {- it("reuses a ready registered server instead of spawning", async () => {- const appRoot = await createTempAppRoot();- const fetchMock = vi.fn(async () => Response.json({ revision: "rev-1" }));- vi.stubGlobal("fetch", fetchMock);-- await writeRegistry(appRoot, {- appRoot,- origin: "http://127.0.0.1:49152",- pid: null,- updatedAt: new Date().toISOString(),- });-- const handle = await resolveSharedEveDevServer(appRoot);-- expect(handle).toEqual({ origin: "http://127.0.0.1:49152" });- expect(handle.process).toBeUndefined();- expect(process.env[EVE_BASE_URL_ENV]).toBe("http://127.0.0.1:49152");- expect(fetchMock).toHaveBeenCalledWith(- new URL("/eve/v1/dev/runtime-artifacts", "http://127.0.0.1:49152"),- { redirect: "error", signal: expect.any(AbortSignal) },- );- });-});diff --git a/packages/eve/src/public/nuxt/dev-server.test.ts b/packages/eve/src/public/nuxt/dev-server.test.tsdeleted file mode 100644index 4f2ad69de..000000000--- a/packages/eve/src/public/nuxt/dev-server.test.ts+++ /dev/null@@ -1,53 +0,0 @@-import { describe, expect, it } from "vitest";--import { normalizeDevServerRegistry } from "./dev-server.js";--describe("normalizeDevServerRegistry", () => {- it("normalizes a well-formed record and canonicalizes the origin", () => {- expect(- normalizeDevServerRegistry({- appRoot: "/app",- origin: "http://127.0.0.1:49152/",- pid: 1234,- updatedAt: "2026-05-28T00:00:00.000Z",- }),- ).toEqual({- appRoot: "/app",- origin: "http://127.0.0.1:49152",- pid: 1234,- updatedAt: "2026-05-28T00:00:00.000Z",- });- });-- it("accepts a null pid", () => {- expect(- normalizeDevServerRegistry({- appRoot: "/app",- origin: "http://127.0.0.1:49152",- pid: null,- updatedAt: "2026-05-28T00:00:00.000Z",- })?.pid,- ).toBeNull();- });-- const invalidCases: readonly { readonly label: string; readonly value: unknown }[] = [- { label: "a scalar", value: "not a record" },- { label: "null", value: null },- { label: "an array", value: ["array"] },- { label: "missing appRoot", value: { origin: "http://x", pid: null, updatedAt: "now" } },- { label: "missing origin", value: { appRoot: "/app", pid: null, updatedAt: "now" } },- { label: "missing updatedAt", value: { appRoot: "/app", origin: "http://x", pid: null } },- {- label: "a non-number pid",- value: { appRoot: "/app", origin: "http://x", pid: "1", updatedAt: "now" },- },- {- label: "an invalid origin",- value: { appRoot: "/app", origin: "not a url", pid: null, updatedAt: "now" },- },- ];-- it.each(invalidCases)("returns undefined for $label", ({ value }) => {- expect(normalizeDevServerRegistry(value)).toBeUndefined();- });-});diff --git a/packages/eve/src/public/nuxt/dev-server.ts b/packages/eve/src/public/nuxt/dev-server.tsdeleted file mode 100644index f18760e87..000000000--- a/packages/eve/src/public/nuxt/dev-server.ts+++ /dev/null@@ -1,275 +0,0 @@-import { spawn, type ChildProcess } from "node:child_process";-import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises";-import { join } from "node:path";--import { resolvePackageRoot } from "#internal/application/package.js";-import { readDevelopmentRuntimeArtifactsRevision } from "#services/dev-client/runtime-artifacts.js";--import { normalizeOrigin } from "./routing.js";--export const EVE_BASE_URL_ENV = "EVE_BASE_URL";--const DEFAULT_SERVER_READY_TIMEOUT_MS = 30_000;-const DEV_SERVER_REGISTRY_TIMEOUT_MS = 30_000;-const DEV_SERVER_REGISTRY_POLL_MS = 100;-const DEV_SERVER_READINESS_TIMEOUT_MS = 1_000;-const DEV_SERVER_STALE_LOCK_MS = 30_000;-const EVE_CACHE_DIRECTORY_NAME = ".eve";-const EVE_NUXT_DEV_SERVER_FILE_NAME = "nuxt-dev-server.json";-const EVE_NUXT_DEV_SERVER_LOCK_FILE_NAME = "nuxt-dev-server.lock";-const LOCAL_SERVER_URL_PATTERN = /https?:\/\/(?:\[[^\]\s]+\]|[^\s/:[\]]+)(?::\d+)?/;--interface EveProcessHandle {- readonly origin: string;- readonly process?: ChildProcess;-}--interface EveDevServerRegistry {- readonly appRoot: string;- readonly origin: string;- readonly pid: number | null;- readonly updatedAt: string;-}--function isNodeErrorWithCode(error: unknown, code: string): boolean {- return error instanceof Error && "code" in error && error.code === code;-}--function delay(ms: number): Promise<void> {- return new Promise((r) => setTimeout(r, ms));-}--function isRecord(value: unknown): value is Record<string, unknown> {- return value !== null && typeof value === "object" && !Array.isArray(value);-}--function resolveEveCacheDirectory(appRoot: string): string {- return join(appRoot, EVE_CACHE_DIRECTORY_NAME);-}--function resolveEveDevServerRegistryPath(appRoot: string): string {- return join(resolveEveCacheDirectory(appRoot), EVE_NUXT_DEV_SERVER_FILE_NAME);-}--function resolveEveDevServerLockPath(appRoot: string): string {- return join(resolveEveCacheDirectory(appRoot), EVE_NUXT_DEV_SERVER_LOCK_FILE_NAME);-}--/**- * Parse and validate a persisted dev-server registry record. Returns- * `undefined` for anything that is not a well-formed registry so callers fall- * back to spawning a fresh server.- */-export function normalizeDevServerRegistry(value: unknown): EveDevServerRegistry | undefined {- if (!isRecord(value)) return undefined;- if (- typeof value.appRoot !== "string" ||- typeof value.origin !== "string" ||- typeof value.updatedAt !== "string"- )- return undefined;- if (value.pid !== null && typeof value.pid !== "number") return undefined;- try {- return {- appRoot: value.appRoot,- origin: normalizeOrigin(value.origin),- pid: value.pid,- updatedAt: value.updatedAt,- };- } catch {- return undefined;- }-}--async function readUsableEveDevServerRegistry(appRoot: string): Promise<string | undefined> {- try {- const registry = normalizeDevServerRegistry(- JSON.parse(await readFile(resolveEveDevServerRegistryPath(appRoot), "utf8")) as unknown,- );- if (registry === undefined || registry.appRoot !== appRoot) return undefined;- if (- (await readDevelopmentRuntimeArtifactsRevision({- serverUrl: registry.origin,- timeoutMs: DEV_SERVER_READINESS_TIMEOUT_MS,- })) === undefined- )- return undefined;- return registry.origin;- } catch (error) {- if (isNodeErrorWithCode(error, "ENOENT")) return undefined;- throw error;- }-}--async function writeEveDevServerRegistry(appRoot: string, handle: EveProcessHandle): Promise<void> {- await mkdir(resolveEveCacheDirectory(appRoot), { recursive: true });- await writeFile(- resolveEveDevServerRegistryPath(appRoot),- `${JSON.stringify(- {- appRoot,- origin: handle.origin,- pid: handle.process?.pid ?? null,- updatedAt: new Date().toISOString(),- } satisfies EveDevServerRegistry,- null,- 2,- )}\n`,- );-}--async function removeStaleEveDevServerLock(lockPath: string): Promise<void> {- try {- const lockStat = await stat(lockPath);- if (Date.now() - lockStat.mtimeMs > DEV_SERVER_STALE_LOCK_MS) {- await rm(lockPath, { force: true });- }- } catch (error) {- if (!isNodeErrorWithCode(error, "ENOENT")) throw error;- }-}--async function acquireEveDevServerLock(appRoot: string): Promise<() => Promise<void>> {- const cacheDirectory = resolveEveCacheDirectory(appRoot);- const lockPath = resolveEveDevServerLockPath(appRoot);- const deadline = Date.now() + DEV_SERVER_REGISTRY_TIMEOUT_MS;- await mkdir(cacheDirectory, { recursive: true });-- while (true) {- try {- const lockFile = await open(lockPath, "wx");- await lockFile.writeFile(`${String(process.pid)}\n`);- await lockFile.close();- return async () => {- await rm(lockPath, { force: true });- };- } catch (error) {- if (!isNodeErrorWithCode(error, "EEXIST")) throw error;- const registeredOrigin = await readUsableEveDevServerRegistry(appRoot);- if (registeredOrigin !== undefined) return async () => {};- await removeStaleEveDevServerLock(lockPath);- if (Date.now() > deadline) {- throw new Error(- `Timed out after ${DEV_SERVER_REGISTRY_TIMEOUT_MS}ms waiting for another Nuxt process to start eve.`,- );- }- await delay(DEV_SERVER_REGISTRY_POLL_MS);- }- }-}--function createEveBinaryPath(): string {- return join(resolvePackageRoot(), "bin", "eve.js");-}--function startServerProcess(input: {- readonly args: readonly string[];- readonly command: string;- readonly cwd: string;- readonly env?: Record<string, string>;-}): Promise<EveProcessHandle> {- return new Promise((resolvePromise, reject) => {- const child = spawn(input.command, input.args, {- cwd: input.cwd,- env: { ...process.env, ...input.env },- stdio: ["ignore", "pipe", "pipe"],- });- const timeout = setTimeout(() => {- child.kill();- reject(- new Error(- `Timed out after ${DEFAULT_SERVER_READY_TIMEOUT_MS}ms waiting for eve to print its server URL.`,- ),- );- }, DEFAULT_SERVER_READY_TIMEOUT_MS);-- const cleanup = () => {- clearTimeout(timeout);- child.off("error", handleError);- child.off("exit", handleEarlyExit);- };- const handleError = (error: Error) => {- cleanup();- reject(error);- };- const handleEarlyExit = (code: number | null, signal: NodeJS.Signals | null) => {- cleanup();- reject(- new Error(- `eve server process exited before printing its server URL (code ${String(code)}, signal ${String(signal)}).`,- ),- );- };- let resolved = false;- const handleOutput = (chunk: Buffer) => {- if (resolved) return;- const match = LOCAL_SERVER_URL_PATTERN.exec(chunk.toString("utf8"));- if (match === null) return;- resolved = true;- cleanup();- resolvePromise({ origin: normalizeOrigin(match[0]), process: child });- };-- child.once("error", handleError);- child.once("exit", handleEarlyExit);- child.stdout.on("data", (chunk: Buffer) => {- process.stdout.write(chunk);- handleOutput(chunk);- });- child.stderr.on("data", (chunk: Buffer) => {- process.stderr.write(chunk);- handleOutput(chunk);- });- });-}--function installProcessShutdown(handle: EveProcessHandle): EveProcessHandle {- const childProcess = handle.process;- if (childProcess === undefined) return handle;- const close = () => {- process.off("beforeExit", close);- process.off("exit", close);- if (!childProcess.killed) childProcess.kill();- };- process.once("beforeExit", close);- process.once("exit", close);- return handle;-}--function startEveDevServer(appRoot: string): Promise<EveProcessHandle> {- return startServerProcess({- args: [createEveBinaryPath(), "dev", "--no-ui", "--port", "0"],- command: process.execPath,- cwd: appRoot,- }).then((handle) => {- process.env[EVE_BASE_URL_ENV] = handle.origin;- return installProcessShutdown(handle);- });-}--/**- * Resolve a shared eve dev server for {@link appRoot}, reusing a healthy- * registered server when one exists and otherwise spawning a new one behind a- * cross-process lock so concurrent Nuxt processes don't each boot eve.- */-export async function resolveSharedEveDevServer(appRoot: string): Promise<EveProcessHandle> {- const registeredOrigin = await readUsableEveDevServerRegistry(appRoot);- if (registeredOrigin !== undefined) {- process.env[EVE_BASE_URL_ENV] = registeredOrigin;- return { origin: registeredOrigin };- }-- const releaseLock = await acquireEveDevServerLock(appRoot);- try {- const lockedRegisteredOrigin = await readUsableEveDevServerRegistry(appRoot);- if (lockedRegisteredOrigin !== undefined) {- process.env[EVE_BASE_URL_ENV] = lockedRegisteredOrigin;- return { origin: lockedRegisteredOrigin };- }- const handle = await startEveDevServer(appRoot);- await writeEveDevServerRegistry(appRoot, handle);- return handle;- } finally {- await releaseLock();- }-}diff --git a/packages/eve/src/public/nuxt/module.ts b/packages/eve/src/public/nuxt/module.tsindex afc95573f..7c5148ed7 100644--- a/packages/eve/src/public/nuxt/module.ts+++ b/packages/eve/src/public/nuxt/module.ts@@ -5,19 +5,32 @@ import { addImports, defineNuxtModule, extendRouteRules } from "@nuxt/kit";import type { NuxtModule } from "@nuxt/schema";import { EVE_ROUTE_PREFIX } from "#protocol/routes.js";+import {+ resolveDevServerTimeout,+ resolveSharedEveDevServer,+ type EveFrameworkHost,+} from "#shared/framework-eve-server.js";import {ensureEveVercelServicesConfig,mergeEveVercelConfig,type VercelBuildConfig,} from "#shared/vercel-services.js";-import { EVE_BASE_URL_ENV, resolveSharedEveDevServer } from "./dev-server.js";import { joinRoutePrefix, normalizeOrigin, resolveProductionTarget } from "./routing.js";+const EVE_BASE_URL_ENV = "EVE_BASE_URL";+const EVE_NUXT_HOST: EveFrameworkHost = { label: "Nuxt", slug: "nuxt" };+/*** Options for the eve Nuxt module.*/export interface EveNuxtModuleOptions {+ /**+ * Maximum time in milliseconds to wait for the eve development server to+ * start, including waiting for another Nuxt process to start it. Defaults+ * to 180000 (three minutes).+ */+ devServerTimeoutMs?: number;/*** Path to the eve application root, resolved relative to the Nuxt project* root unless absolute. Defaults to the Nuxt project root. The dev server is@@ -64,6 +77,7 @@ interface NitroVercelConfigHost {async function resolveEveProxyTarget(input: {readonly appRoot: string;readonly dev: boolean;+ readonly devServerTimeoutMs?: number;readonly onDevServerSpawned?: (child: ChildProcess) => void;}): Promise<string> {if (!input.dev) {@@ -75,7 +89,11 @@ async function resolveEveProxyTarget(input: {return joinRoutePrefix(normalizeOrigin(configuredEveBaseUrl), EVE_ROUTE_PREFIX);}- const handle = await resolveSharedEveDevServer(input.appRoot);+ const handle = await resolveSharedEveDevServer({+ appRoot: input.appRoot,+ host: EVE_NUXT_HOST,+ timeoutMs: input.devServerTimeoutMs,+ });if (handle.process !== undefined) {input.onDevServerSpawned?.(handle.process);}@@ -104,6 +122,7 @@ const eveNuxtModule: NuxtModule<EveNuxtModuleOptions> = defineNuxtModule<EveNuxtasync setup(options, nuxt) {const nuxtRoot = nuxt.options.rootDir;const appRoot = resolveApplicationRoot(nuxtRoot, options.eveRoot);+ const devServerTimeoutMs = resolveDevServerTimeout(options.devServerTimeoutMs, EVE_NUXT_HOST);// Auto-import the Vue composable so app code can call `useEveAgent()`// without an explicit import, matching Nuxt's composable conventions.@@ -140,10 +159,11 @@ const eveNuxtModule: NuxtModule<EveNuxtModuleOptions> = defineNuxtModule<EveNuxtconst proxyTarget = await resolveEveProxyTarget({appRoot,dev: nuxt.options.dev,+ devServerTimeoutMs,onDevServerSpawned: (child) => {// Prefer Nuxt's lifecycle for cleanup so the dev server is torn// down on graceful shutdown and dev restarts. The process-exit- // guard in dev-server.ts remains as a fallback for non-graceful+ // guard in framework-eve-server.ts remains as a fallback for non-graceful// exits.nuxt.hook("close", () => {if (!child.killed) {diff --git a/packages/eve/src/shared/framework-eve-server.integration.test.ts b/packages/eve/src/shared/framework-eve-server.integration.test.tsnew file mode 100644index 000000000..e4341a9da--- /dev/null+++ b/packages/eve/src/shared/framework-eve-server.integration.test.ts@@ -0,0 +1,52 @@+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { afterEach, describe, expect, it, vi } from "vitest";++const spawnMock = vi.hoisted(() => vi.fn());++vi.mock("node:child_process", () => ({+ spawn: spawnMock,+}));++import { resolveSharedEveDevServer } from "./framework-eve-server.js";++const tempRoots: string[] = [];++afterEach(async () => {+ spawnMock.mockReset();+ vi.unstubAllGlobals();+ await Promise.all(tempRoots.splice(0).map((root) => rm(root, { force: true, recursive: true })));+});++describe("resolveSharedEveDevServer", () => {+ it("reuses a ready server registered by another process instead of spawning", async () => {+ const appRoot = await mkdtemp(join(tmpdir(), "eve-framework-dev-server-"));+ tempRoots.push(appRoot);+ const fetchMock = vi.fn(async () => Response.json({ revision: "rev-1" }));+ vi.stubGlobal("fetch", fetchMock);+ await mkdir(join(appRoot, ".eve"), { recursive: true });+ await writeFile(+ join(appRoot, ".eve", "nuxt-dev-server.json"),+ JSON.stringify({+ appRoot,+ origin: "http://127.0.0.1:49152",+ pid: null,+ updatedAt: new Date().toISOString(),+ }),+ );++ const handle = await resolveSharedEveDevServer({+ appRoot,+ host: { label: "Nuxt", slug: "nuxt" },+ });++ expect(handle).toEqual({ origin: "http://127.0.0.1:49152" });+ expect(spawnMock).not.toHaveBeenCalled();+ expect(fetchMock).toHaveBeenCalledWith(+ new URL("/eve/v1/dev/runtime-artifacts", "http://127.0.0.1:49152"),+ { redirect: "error", signal: expect.any(AbortSignal) },+ );+ });+});diff --git a/packages/eve/src/shared/framework-eve-server.ts b/packages/eve/src/shared/framework-eve-server.tsnew file mode 100644index 000000000..7e0ff858e--- /dev/null+++ b/packages/eve/src/shared/framework-eve-server.ts@@ -0,0 +1,526 @@+import { spawn, type ChildProcess } from "node:child_process";+import { existsSync } from "node:fs";+import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises";+import { join } from "node:path";++import { resolvePackageRoot } from "#internal/application/package.js";+import { readDevelopmentRuntimeArtifactsRevision } from "#services/dev-client/runtime-artifacts.js";+import { isLoopbackHostname } from "#shared/network-address.js";++/** Default time to wait for an eve server spawned by a framework integration. */+export const DEFAULT_EVE_SERVER_TIMEOUT_MS = 180_000;++const DEV_SERVER_REGISTRY_POLL_MS = 100;+const DEV_SERVER_READINESS_TIMEOUT_MS = 1_000;+const DEV_SERVER_STALE_LOCK_MS = 30_000;+const EVE_CACHE_DIRECTORY_NAME = ".eve";+const ANSI_ESCAPE = String.fromCharCode(27);+const ANSI_ESCAPE_PATTERN = new RegExp(`${ANSI_ESCAPE}\\[[0-?]*[ -/]*[@-~]`, "g");+const SERVER_URL_CANDIDATE_PATTERN = /https?:\/\/[^\s"'<>]+/g;++/**+ * Framework that owns the eve server process. `label` appears in errors;+ * `slug` keeps each framework's dev-server registry and lock separate.+ */+export interface EveFrameworkHost {+ readonly label: string;+ readonly slug: string;+}++export interface EveProcessHandle {+ readonly origin: string;+ readonly process?: ChildProcess;+}++interface EveDevServerRegistry {+ readonly appRoot: string;+ readonly origin: string;+ readonly pid: number | null;+ readonly updatedAt: string;+}++function normalizeOrigin(origin: string): string {+ return new URL(origin).origin;+}++function isNodeErrorWithCode(error: unknown, code: string): boolean {+ return error instanceof Error && "code" in error && error.code === code;+}++function delay(ms: number): Promise<void> {+ return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}++function resolveEveCacheDirectory(appRoot: string): string {+ return join(appRoot, EVE_CACHE_DIRECTORY_NAME);+}++function resolveEveDevServerRegistryPath(appRoot: string, host: EveFrameworkHost): string {+ return join(resolveEveCacheDirectory(appRoot), `${host.slug}-dev-server.json`);+}++function resolveEveDevServerLockPath(appRoot: string, host: EveFrameworkHost): string {+ return join(resolveEveCacheDirectory(appRoot), `${host.slug}-dev-server.lock`);+}++/**+ * Validate a framework-supplied dev-server timeout. Returns `undefined` when+ * unset so callers fall back to {@link DEFAULT_EVE_SERVER_TIMEOUT_MS}.+ */+export function resolveDevServerTimeout(+ timeoutMs: number | undefined,+ host: EveFrameworkHost,+): number | undefined {+ if (timeoutMs === undefined) {+ return undefined;+ }++ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {+ throw new Error(`eve ${host.label} development server timeout must be a positive number.`);+ }++ return timeoutMs;+}++function normalizeDevServerRegistry(value: unknown): EveDevServerRegistry | undefined {+ if (!isRecord(value)) {+ return undefined;+ }++ if (+ typeof value.appRoot !== "string" ||+ typeof value.origin !== "string" ||+ typeof value.updatedAt !== "string"+ ) {+ return undefined;+ }++ if (value.pid !== null && typeof value.pid !== "number") {+ return undefined;+ }++ try {+ return {+ appRoot: value.appRoot,+ origin: normalizeOrigin(value.origin),+ pid: value.pid,+ updatedAt: value.updatedAt,+ };+ } catch {+ return undefined;+ }+}++async function readUsableEveDevServerRegistry(+ appRoot: string,+ host: EveFrameworkHost,+): Promise<string | undefined> {+ try {+ const registry = normalizeDevServerRegistry(+ JSON.parse(await readFile(resolveEveDevServerRegistryPath(appRoot, host), "utf8")) as unknown,+ );++ if (registry === undefined || registry.appRoot !== appRoot) {+ return undefined;+ }++ if (+ (await readDevelopmentRuntimeArtifactsRevision({+ serverUrl: registry.origin,+ timeoutMs: DEV_SERVER_READINESS_TIMEOUT_MS,+ })) === undefined+ ) {+ return undefined;+ }++ return registry.origin;+ } catch (error) {+ if (isNodeErrorWithCode(error, "ENOENT")) {+ return undefined;+ }++ throw error;+ }+}++async function writeEveDevServerRegistry(+ appRoot: string,+ host: EveFrameworkHost,+ handle: EveProcessHandle,+): Promise<void> {+ await mkdir(resolveEveCacheDirectory(appRoot), {+ recursive: true,+ });+ await writeFile(+ resolveEveDevServerRegistryPath(appRoot, host),+ `${JSON.stringify(+ {+ appRoot,+ origin: handle.origin,+ pid: handle.process?.pid ?? null,+ updatedAt: new Date().toISOString(),+ } satisfies EveDevServerRegistry,+ null,+ 2,+ )}\n`,+ );+}++async function removeStaleEveDevServerLock(lockPath: string): Promise<void> {+ try {+ const lockStat = await stat(lockPath);+ if (Date.now() - lockStat.mtimeMs > DEV_SERVER_STALE_LOCK_MS) {+ await rm(lockPath, {+ force: true,+ });+ }+ } catch (error) {+ if (!isNodeErrorWithCode(error, "ENOENT")) {+ throw error;+ }+ }+}++async function acquireEveDevServerLock(+ appRoot: string,+ host: EveFrameworkHost,+ timeoutMs: number,+): Promise<() => Promise<void>> {+ const cacheDirectory = resolveEveCacheDirectory(appRoot);+ const lockPath = resolveEveDevServerLockPath(appRoot, host);+ const deadline = Date.now() + timeoutMs;++ await mkdir(cacheDirectory, {+ recursive: true,+ });++ while (true) {+ try {+ const lockFile = await open(lockPath, "wx");+ await lockFile.writeFile(`${String(process.pid)}\n`);+ await lockFile.close();++ return async () => {+ await rm(lockPath, {+ force: true,+ });+ };+ } catch (error) {+ if (!isNodeErrorWithCode(error, "EEXIST")) {+ throw error;+ }++ const registeredOrigin = await readUsableEveDevServerRegistry(appRoot, host);+ if (registeredOrigin !== undefined) {+ return async () => {};+ }++ await removeStaleEveDevServerLock(lockPath);++ if (Date.now() > deadline) {+ throw new Error(+ `Timed out after ${timeoutMs}ms waiting for another ${host.label} process to start eve.`,+ );+ }++ await delay(DEV_SERVER_REGISTRY_POLL_MS);+ }+ }+}++function createEveBinaryPath(): string {+ return join(resolvePackageRoot(), "bin", "eve.js");+}++function parseLocalServerOrigin(urlText: string): string | undefined {+ const url = URL.parse(urlText);+ // Dev-server discovery reads mixed subprocess output. Build metadata and+ // dependency warnings can print unrelated URLs before eve reports its listener,+ // but the integration only owns the app-local loopback server it started.+ if (+ url === null ||+ (url.protocol !== "http:" && url.protocol !== "https:") ||+ !isLoopbackHostname(url.hostname) ||+ url.port.length === 0+ ) {+ return undefined;+ }++ return url.origin;+}++function findLocalServerOrigin(output: string): string | undefined {+ for (const match of output.matchAll(SERVER_URL_CANDIDATE_PATTERN)) {+ const origin = parseLocalServerOrigin(match[0]);+ if (origin !== undefined) {+ return origin;+ }+ }++ return undefined;+}++function formatEveDevOutputLine(line: string, logLabel: string | undefined): string | undefined {+ const normalizedLine = line.replace(/\r$/, "");+ const trimmedLine = normalizedLine.replace(ANSI_ESCAPE_PATTERN, "").trim();++ if (+ trimmedLine.length === 0 ||+ /^☰eve\b/.test(trimmedLine) ||+ trimmedLine === "CONFIGURATION_FIELD_CONFLICT" ||+ trimmedLine.startsWith("[CONFIGURATION_FIELD_CONFLICT]")+ ) {+ return undefined;+ }++ const tag = logLabel === undefined ? "[eve:dev]" : `[eve:dev:${logLabel}]`;+ const serverMatch = /server listening at\s+(https?:\/\/[^\s]+)/i.exec(normalizedLine);+ if (serverMatch !== null) {+ return `${tag} server listening at ${serverMatch[1]}`;+ }++ return `${tag} ${normalizedLine}`;+}++function createEveDevOutputWriter(input: {+ readonly logLabel?: string;+ readonly stream: NodeJS.WriteStream;+}): {+ readonly flush: () => void;+ readonly write: (chunk: Buffer) => void;+} {+ let pendingLine = "";++ const writeLine = (line: string) => {+ const formattedLine = formatEveDevOutputLine(line, input.logLabel);+ if (formattedLine !== undefined) {+ input.stream.write(`${formattedLine}\n`);+ }+ };++ return {+ flush() {+ if (pendingLine.length === 0) {+ return;+ }++ writeLine(pendingLine);+ pendingLine = "";+ },+ write(chunk) {+ pendingLine += chunk.toString("utf8");+ const lines = pendingLine.split("\n");+ pendingLine = lines.pop() ?? "";++ for (const line of lines) {+ writeLine(line);+ }+ },+ };+}++function startServerProcess(input: {+ readonly args: readonly string[];+ readonly command: string;+ readonly cwd: string;+ readonly env?: Record<string, string>;+ readonly logLabel?: string;+ readonly timeoutMs?: number;+}): Promise<EveProcessHandle> {+ const timeoutMs = input.timeoutMs ?? DEFAULT_EVE_SERVER_TIMEOUT_MS;++ return new Promise((resolvePromise, reject) => {+ const child = spawn(input.command, input.args, {+ cwd: input.cwd,+ env: {+ ...process.env,+ ...input.env,+ },+ stdio: ["ignore", "pipe", "pipe"],+ });+ const stderrWriter = createEveDevOutputWriter({+ logLabel: input.logLabel,+ stream: process.stderr,+ });+ const stdoutWriter = createEveDevOutputWriter({+ logLabel: input.logLabel,+ stream: process.stdout,+ });+ const timeout = setTimeout(() => {+ child.kill();+ reject(new Error(`Timed out after ${timeoutMs}ms waiting for eve to print its server URL.`));+ }, timeoutMs);++ const cleanup = () => {+ clearTimeout(timeout);+ child.off("error", handleError);+ child.off("exit", handleEarlyExit);+ };+ const flushOutput = () => {+ stdoutWriter.flush();+ stderrWriter.flush();+ };+ const handleError = (error: Error) => {+ flushOutput();+ cleanup();+ reject(error);+ };+ const handleEarlyExit = (code: number | null, signal: NodeJS.Signals | null) => {+ flushOutput();+ cleanup();+ reject(+ new Error(+ `eve server process exited before printing its server URL (code ${String(code)}, signal ${String(signal)}).`,+ ),+ );+ };+ const handleOutput = (chunk: Buffer) => {+ const origin = findLocalServerOrigin(chunk.toString("utf8"));++ if (origin === undefined) {+ return;+ }++ cleanup();+ resolvePromise({+ origin,+ process: child,+ });+ };+ const handleStdout = (chunk: Buffer) => {+ stdoutWriter.write(chunk);+ handleOutput(chunk);+ };+ const handleStderr = (chunk: Buffer) => {+ stderrWriter.write(chunk);+ handleOutput(chunk);+ };++ child.once("error", handleError);+ child.once("exit", handleEarlyExit);+ child.stdout.on("data", handleStdout);+ child.stderr.on("data", handleStderr);+ });+}++function installProcessShutdown(handle: EveProcessHandle): EveProcessHandle {+ const childProcess = handle.process;++ if (childProcess === undefined) {+ return handle;+ }++ const close = () => {+ if (!childProcess.killed) {+ childProcess.kill();+ }+ };++ process.once("beforeExit", close);+ process.once("exit", close);++ return handle;+}++function startEveDevServer(input: {+ readonly appRoot: string;+ readonly logLabel?: string;+ readonly timeoutMs: number;+ readonly workspaceAgentName?: string;+}): Promise<EveProcessHandle> {+ return startServerProcess({+ args: [+ createEveBinaryPath(),+ "dev",+ "--no-ui",+ "--port",+ "0",+ ...(input.workspaceAgentName === undefined ? [] : ["--agent", input.workspaceAgentName]),+ ],+ command: process.execPath,+ cwd: input.appRoot,+ logLabel: input.logLabel,+ timeoutMs: input.timeoutMs,+ }).then(installProcessShutdown);+}++/**+ * Serve an existing `eve build` output from `.output/server/index.mjs` on+ * {@link input.origin}'s loopback port.+ */+export function startEveProductionServer(input: {+ readonly appRoot: string;+ readonly host: EveFrameworkHost;+ readonly origin: string;+}): Promise<EveProcessHandle> {+ const parsedOrigin = new URL(input.origin);+ const port = parsedOrigin.port;+ const serverEntry = join(input.appRoot, ".output", "server", "index.mjs");++ if (!existsSync(serverEntry)) {+ throw new Error(+ `eve production output is missing at ${serverEntry}. Run eve build from ${input.appRoot} before starting ${input.host.label}.`,+ );+ }++ return startServerProcess({+ args: [serverEntry],+ command: process.execPath,+ cwd: input.appRoot,+ env: {+ HOST: parsedOrigin.hostname,+ NITRO_HOST: parsedOrigin.hostname,+ NITRO_PORT: port,+ PORT: port,+ },+ }).then(installProcessShutdown);+}++/**+ * Resolve a shared eve dev server for `appRoot`, reusing a healthy registered+ * server when one exists and otherwise spawning `eve dev` behind a+ * cross-process lock so concurrent framework processes don't each boot eve.+ * `process` is set only when this call spawned the server.+ */+export async function resolveSharedEveDevServer(input: {+ readonly appRoot: string;+ readonly host: EveFrameworkHost;+ readonly logLabel?: string;+ readonly timeoutMs?: number;+ /** Workspace member selected when spawning the local eve dev server. */+ readonly workspaceAgentName?: string;+}): Promise<EveProcessHandle> {+ const timeoutMs = input.timeoutMs ?? DEFAULT_EVE_SERVER_TIMEOUT_MS;+ const registeredOrigin = await readUsableEveDevServerRegistry(input.appRoot, input.host);+ if (registeredOrigin !== undefined) {+ return {+ origin: registeredOrigin,+ };+ }++ const releaseLock = await acquireEveDevServerLock(input.appRoot, input.host, timeoutMs);++ try {+ const lockedRegisteredOrigin = await readUsableEveDevServerRegistry(input.appRoot, input.host);+ if (lockedRegisteredOrigin !== undefined) {+ return {+ origin: lockedRegisteredOrigin,+ };+ }++ const handle = await startEveDevServer({+ appRoot: input.appRoot,+ logLabel: input.logLabel,+ timeoutMs,+ workspaceAgentName: input.workspaceAgentName,+ });+ await writeEveDevServerRegistry(input.appRoot, input.host, handle);+ return handle;+ } finally {+ await releaseLock();+ }+}