Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

refactor(eve): share Vercel service assembly (#1924)

OwenKephart2e3cc8acfefc
diff --git a/packages/eve/src/internal/agent-name.ts b/packages/eve/src/internal/agent-name.ts
new file mode 100644
index 000000000..d43726543
--- /dev/null
+++ b/packages/eve/src/internal/agent-name.ts
@@ -0,0 +1,14 @@
+const PUBLIC_AGENT_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/;
+
+/** Whether a name is safe to expose as an eve public route segment. */
+export function isValidPublicAgentName(name: string): boolean {
+ return PUBLIC_AGENT_NAME_PATTERN.test(name);
+}
+
+/** Assert that an authored agent name is safe to expose publicly. */
+export function assertValidPublicAgentName(name: string, subject: string): void {
+ if (isValidPublicAgentName(name)) return;
+ throw new Error(
+ `${subject} ${JSON.stringify(name)} is invalid. Use lowercase letters, numbers, hyphens, or underscores, beginning and ending with a letter or number.`,
+ );
+}
diff --git a/packages/eve/src/internal/nitro/host/build-application.ts b/packages/eve/src/internal/nitro/host/build-application.ts
index eb1ba8036..2c51e8718 100644
--- a/packages/eve/src/internal/nitro/host/build-application.ts
+++ b/packages/eve/src/internal/nitro/host/build-application.ts
@@ -40,7 +40,10 @@ import type { ApplicationBuildOptions } from "#internal/nitro/host/types.js";
import { findClosestVercelOutputDirectory } from "#shared/vercel-output-directory.js";
import { toErrorMessage } from "#shared/errors.js";
import { resolveDiscoveryProject } from "#discover/project.js";
+import { resolveCoDeployedEveServicePrefix } from "#internal/vercel/vercel-service-config-operations.js";
+import { parseVercelServicesConfig } from "#internal/vercel/vercel-services-config.js";
import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+import { isObject } from "#shared/guards.js";
function trimTrailingSlash(path: string): string {
return path.replace(/[\\/]+$/, "");
@@ -97,111 +100,6 @@ async function writeOptionalApplicationBuildProfile(input: {
}
}
-function isRecord(value: unknown): value is Record<string, unknown> {
- return value !== null && typeof value === "object" && !Array.isArray(value);
-}
-
-function normalizeEntrypoint(rootDir: string, entrypoint: unknown): string | null {
- if (typeof entrypoint !== "string" || entrypoint.trim().length === 0) {
- return null;
- }
-
- return resolve(rootDir, entrypoint);
-}
-
-function normalizeServiceRoot(rootDir: string, service: Record<string, unknown>): string | null {
- if (typeof service.root === "string" && service.root.trim().length > 0) {
- return resolve(rootDir, service.root);
- }
-
- return normalizeEntrypoint(rootDir, service.entrypoint);
-}
-
-function normalizeServicePrefix(service: Record<string, unknown>): string {
- if (typeof service.routePrefix === "string") {
- return service.routePrefix.trim();
- }
-
- if (typeof service.mount === "string") {
- return service.mount.trim();
- }
-
- if (
- isRecord(service.mount) &&
- typeof service.mount.path === "string" &&
- service.mount.path.trim().length > 0
- ) {
- return service.mount.path.trim();
- }
-
- return "";
-}
-
-function normalizeServiceCollection(
- value: unknown,
-): readonly Record<string, unknown>[] | undefined {
- if (isRecord(value)) {
- return Object.values(value).filter(isRecord);
- }
-
- if (Array.isArray(value)) {
- return value.filter(isRecord);
- }
-
- return undefined;
-}
-
-/**
- * Resolve the route prefix an eve service is mounted under when it is
- * co-deployed behind a host web service (Next.js, Nuxt, SvelteKit etc.).
- *
- * Any service whose framework is not `eve` is treated as a host that proxies
- * eve's transport routes behind a prefix. A standalone eve deployment (no host
- * service) returns `undefined` so its output stays routable at the root.
- */
-function resolveCoDeployedEveServicePrefix(input: {
- appRoots: readonly string[];
- configRoot: string;
- config: unknown;
-}): string | undefined {
- if (!isRecord(input.config)) {
- return undefined;
- }
-
- const services =
- normalizeServiceCollection(input.config.experimentalServices) ??
- normalizeServiceCollection(input.config.experimentalServicesV2) ??
- normalizeServiceCollection(input.config.services);
-
- if (services === undefined) {
- return undefined;
- }
-
- let hasHostService = false;
- let servicePrefix: string | undefined;
-
- for (const service of services) {
- if (service.framework !== "eve") {
- hasHostService = true;
- continue;
- }
-
- const eveEntrypoint = normalizeServiceRoot(input.configRoot, service);
- const routePrefix = normalizeServicePrefix(service);
-
- if (
- eveEntrypoint !== null &&
- input.appRoots.includes(eveEntrypoint) &&
- routePrefix.length > 0 &&
- routePrefix !== "/"
- ) {
- servicePrefix = routePrefix;
- }
- }
-
- return hasHostService ? servicePrefix : undefined;
-}
-
async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(
appRoot: string,
agentRoot: string,
@@ -211,9 +109,11 @@ async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(
if (outputDirectory !== undefined) {
try {
- const config = JSON.parse(
- await readFile(join(outputDirectory, "config.json"), "utf8"),
- ) as unknown;
+ const configPath = join(outputDirectory, "config.json");
+ const config = parseVercelServicesConfig(
+ JSON.parse(await readFile(configPath, "utf8")) as unknown,
+ configPath,
+ );
const servicePrefix = resolveCoDeployedEveServicePrefix({
appRoots,
configRoot: await resolveVercelOutputConfigRoot(outputDirectory),
@@ -238,7 +138,10 @@ async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(
join(currentDir, ".vercel", "output", "config.json"),
]) {
try {
- const config = JSON.parse(await readFile(configPath, "utf8")) as unknown;
+ const config = parseVercelServicesConfig(
+ JSON.parse(await readFile(configPath, "utf8")) as unknown,
+ configPath,
+ );
const configRoot = configPath.endsWith("vercel.json")
? currentDir
: await resolveVercelOutputConfigRoot(dirname(configPath));
@@ -276,13 +179,11 @@ async function resolveVercelOutputConfigRoot(outputDirectory: string): Promise<s
await readFile(join(projectRoot, ".vercel", "project.json"), "utf8"),
) as unknown;
- if (
- isRecord(projectConfig) &&
- isRecord(projectConfig.settings) &&
- typeof projectConfig.settings.rootDirectory === "string" &&
- projectConfig.settings.rootDirectory.trim().length > 0
- ) {
- return resolve(projectRoot, projectConfig.settings.rootDirectory);
+ if (isObject(projectConfig) && isObject(projectConfig.settings)) {
+ const rootDirectory = projectConfig.settings.rootDirectory;
+ if (typeof rootDirectory === "string" && rootDirectory.trim().length > 0) {
+ return resolve(projectRoot, rootDirectory);
+ }
}
} catch (error) {
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
diff --git a/packages/eve/src/internal/vercel/assemble-eve-services.ts b/packages/eve/src/internal/vercel/assemble-eve-services.ts
new file mode 100644
index 000000000..aefadb92c
--- /dev/null
+++ b/packages/eve/src/internal/vercel/assemble-eve-services.ts
@@ -0,0 +1,62 @@
+import {
+ compileEveVercelService,
+ type EveVercelAgentTarget,
+ type EveVercelBuildTarget,
+} from "#internal/vercel/eve-service-contribution.js";
+import {
+ findConfiguredEveServiceEntry,
+ insertEveServiceRequestPathRoute,
+ insertEveServiceRoutes,
+} from "#internal/vercel/vercel-service-config-operations.js";
+import type {
+ VercelRouteConfig,
+ VercelServiceConfig,
+} from "#internal/vercel/vercel-services-config.js";
+
+export interface EveVercelServiceTarget {
+ readonly agent: EveVercelAgentTarget;
+ readonly target: EveVercelBuildTarget;
+}
+
+export interface AssembledEveVercelServices {
+ readonly rootDirectories: readonly string[];
+ readonly routes: readonly VercelRouteConfig[];
+ readonly services: Readonly<Record<string, VercelServiceConfig>>;
+}
+
+/** Merge eve agents into one Vercel service graph. */
+export function assembleEveVercelServices(input: {
+ readonly agents: readonly EveVercelServiceTarget[];
+ readonly routes?: readonly VercelRouteConfig[];
+ readonly services?: Readonly<Record<string, VercelServiceConfig>>;
+}): AssembledEveVercelServices {
+ const existingServices = input.services ?? {};
+ const services: Record<string, VercelServiceConfig> = { ...existingServices };
+ const rootDirectories: string[] = [];
+ const eveRoutes: { routeSrc: string; serviceName: string }[] = [];
+
+ for (const { agent, target } of input.agents) {
+ const contribution = compileEveVercelService({ agent, target });
+ const configured = findConfiguredEveServiceEntry(existingServices, agent);
+ const serviceName = configured?.name ?? contribution.serviceName;
+
+ if (configured === undefined) rootDirectories.push(contribution.rootDirectory);
+ services[serviceName] =
+ configured === undefined
+ ? contribution.service
+ : {
+ ...configured.service,
+ routes: insertEveServiceRequestPathRoute(
+ configured.service.routes,
+ contribution.routeSrc,
+ ),
+ };
+ eveRoutes.push({ routeSrc: contribution.routeSrc, serviceName });
+ }
+
+ return {
+ rootDirectories,
+ routes: insertEveServiceRoutes(input.routes ?? [], eveRoutes),
+ services,
+ };
+}
diff --git a/packages/eve/src/internal/vercel/build-command.ts b/packages/eve/src/internal/vercel/build-command.ts
new file mode 100644
index 000000000..a70cb2d80
--- /dev/null
+++ b/packages/eve/src/internal/vercel/build-command.ts
@@ -0,0 +1,11 @@
+import { relative } from "node:path";
+
+/** Quote one argument for Vercel's POSIX build-command shell. */
+export function quoteVercelShellArgument(value: string): string {
+ return `'${value.replaceAll("'", "'\\''")}'`;
+}
+
+/** Return a portable relative path for a generated Vercel configuration. */
+export function toVercelRelativePath(from: string, to: string): string {
+ return relative(from, to).replaceAll("\\", "/") || ".";
+}
diff --git a/packages/eve/src/internal/vercel/eve-service-contribution.test.ts b/packages/eve/src/internal/vercel/eve-service-contribution.test.ts
new file mode 100644
index 000000000..920fe6ab7
--- /dev/null
+++ b/packages/eve/src/internal/vercel/eve-service-contribution.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from "vitest";
+
+import { createEveServiceName } from "#internal/vercel/eve-service-contribution.js";
+import { resolveCoDeployedEveServicePrefix } from "#internal/vercel/vercel-service-config-operations.js";
+import { isValidVercelServiceName } from "#internal/vercel/vercel-service-name.js";
+
+describe("resolveCoDeployedEveServicePrefix", () => {
+ it("resolves the matching eve service only when it is co-deployed with a host", () => {
+ expect(
+ resolveCoDeployedEveServicePrefix({
+ appRoots: ["/project/agents/support"],
+ config: {
+ services: {
+ eve: { framework: "eve", root: "agents/support", routePrefix: "/support" },
+ web: { framework: "nextjs", root: "." },
+ },
+ },
+ configRoot: "/project",
+ }),
+ ).toBe("/support");
+ expect(
+ resolveCoDeployedEveServicePrefix({
+ appRoots: ["/project/agents/support"],
+ config: {
+ services: {
+ eve: { framework: "eve", root: "agents/support", routePrefix: "/support" },
+ },
+ },
+ configRoot: "/project",
+ }),
+ ).toBeUndefined();
+ });
+
+ it("supports legacy service collections", () => {
+ expect(
+ resolveCoDeployedEveServicePrefix({
+ appRoots: ["/project/agent"],
+ config: {
+ experimentalServices: {
+ eve: { entrypoint: "agent", framework: "eve", mount: { path: "/agent" } },
+ web: { framework: "nextjs" },
+ },
+ },
+ configRoot: "/project",
+ }),
+ ).toBe("/agent");
+ });
+
+ it("ignores malformed legacy service collections", () => {
+ expect(
+ resolveCoDeployedEveServicePrefix({
+ appRoots: ["/project/agent"],
+ config: {
+ experimentalServices: null,
+ services: {
+ eve: { framework: "eve", root: "agent", routePrefix: "/agent" },
+ web: { framework: "nextjs" },
+ },
+ },
+ configRoot: "/project",
+ }),
+ ).toBe("/agent");
+ });
+});
+
+describe("createEveServiceName", () => {
+ it("preserves public agent names that are valid service suffixes", () => {
+ expect(createEveServiceName("customer-care")).toBe("eve-customer-care");
+ });
+
+ it("encodes digit-bearing public names into stable valid service names", () => {
+ const serviceName = createEveServiceName("support2");
+ expect(serviceName).toBe(createEveServiceName("support2"));
+ expect(serviceName).not.toBe(createEveServiceName("support3"));
+ expect(serviceName).toMatch(/^eve-support-[a-z]+$/);
+ expect(isValidVercelServiceName(serviceName)).toBe(true);
+ });
+
+ it("truncates long names while retaining a distinguishing suffix", () => {
+ const serviceName = createEveServiceName(`support-${"a".repeat(80)}`);
+ expect(serviceName.length).toBeLessThanOrEqual(64);
+ expect(isValidVercelServiceName(serviceName)).toBe(true);
+ });
+});
diff --git a/packages/eve/src/internal/vercel/eve-service-contribution.ts b/packages/eve/src/internal/vercel/eve-service-contribution.ts
new file mode 100644
index 000000000..1f38fbfa6
--- /dev/null
+++ b/packages/eve/src/internal/vercel/eve-service-contribution.ts
@@ -0,0 +1,132 @@
+import { createHash } from "node:crypto";
+import { join } from "node:path";
+
+import {
+ EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV,
+ EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV,
+} from "#internal/application/build-output-environment.js";
+import { EVE_ROUTE_PREFIX } from "#protocol/routes.js";
+import {
+ EVE_PUBLIC_ROUTE_PREFIX_ENV,
+ normalizePublicRoutePrefix,
+} from "#shared/public-route-prefix.js";
+import { quoteVercelShellArgument, toVercelRelativePath } from "#internal/vercel/build-command.js";
+import {
+ assertValidVercelServiceName,
+ isValidVercelServiceName,
+ MAX_VERCEL_SERVICE_NAME_LENGTH,
+} from "#internal/vercel/vercel-service-name.js";
+import type {
+ GeneratedVercelServiceConfig,
+ VercelRouteConfig,
+} from "#internal/vercel/vercel-services-config.js";
+
+const EVE_VERCEL_SERVICES_DIRECTORY = ".eve/vercel-services";
+
+export interface EveVercelAgentTarget {
+ readonly appRoot: string;
+ readonly buildCommand: string;
+ readonly name?: string;
+ readonly publicRoutePrefix: string;
+}
+
+export interface EveVercelBuildTarget {
+ readonly hostOutputDirectory: string;
+ readonly projectRoot: string;
+}
+
+export interface EveVercelServiceContribution {
+ readonly rootDirectory: string;
+ readonly routeSrc: string;
+ readonly service: GeneratedVercelServiceConfig;
+ readonly serviceName: string;
+}
+
+function createServiceNameHash(value: string): string {
+ return [...createHash("sha256").update(value).digest().subarray(0, 10)]
+ .map((byte) => String.fromCharCode(97 + (byte % 26)))
+ .join("");
+}
+
+/** Derive a stable Vercel service identifier without restricting the public agent name. */
+export function createEveServiceName(name: string | undefined): string {
+ if (name === undefined) return "eve";
+ const directName = `eve-${name}`;
+ if (isValidVercelServiceName(directName)) return directName;
+
+ const suffix = createServiceNameHash(name);
+ const readableName = name.replace(/[^a-z_-]+/g, "-").replace(/^[^a-z]+|[^a-z]+$/g, "") || "agent";
+ const readableLength = MAX_VERCEL_SERVICE_NAME_LENGTH - "eve--".length - suffix.length;
+ const readable = readableName.slice(0, readableLength).replace(/[^a-z]+$/g, "") || "agent";
+ const serviceName = `eve-${readable}-${suffix}`;
+ assertValidVercelServiceName(serviceName, "Generated eve service name");
+ return serviceName;
+}
+
+export function createEveServiceRouteSrc(publicRoutePrefix: string): string {
+ if (publicRoutePrefix.length === 0) return `^${EVE_ROUTE_PREFIX}/(.*)$`;
+ const prefix = publicRoutePrefix.startsWith("/") ? publicRoutePrefix : `/${publicRoutePrefix}`;
+ return `^${prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}${EVE_ROUTE_PREFIX}/(.*)$`;
+}
+
+export function createEveRequestPathRoute(routeSrc: string): VercelRouteConfig {
+ return {
+ src: routeSrc,
+ transforms: [{ args: `${EVE_ROUTE_PREFIX}/$1`, op: "set", type: "request.path" }],
+ };
+}
+
+export function createEvePublicRoute(serviceName: string, routeSrc: string): VercelRouteConfig {
+ return { destination: { service: serviceName, type: "service" }, src: routeSrc };
+}
+
+function createIsolatedBuild(input: {
+ readonly agent: EveVercelAgentTarget;
+ readonly hostOutputDirectory: string;
+ readonly projectRoot: string;
+ readonly serviceName: string;
+}): { readonly buildCommand: string; readonly root: string; readonly rootDirectory: string } {
+ const rootDirectory = join(input.projectRoot, EVE_VERCEL_SERVICES_DIRECTORY, input.serviceName);
+ const outputDirectory = join(rootDirectory, ".vercel", "output");
+ const prefix = normalizePublicRoutePrefix(input.agent.publicRoutePrefix);
+ const prefixExport =
+ prefix === undefined
+ ? ""
+ : ` && export ${EVE_PUBLIC_ROUTE_PREFIX_ENV}=${quoteVercelShellArgument(prefix)}`;
+
+ return {
+ buildCommand: `cd ${quoteVercelShellArgument(toVercelRelativePath(rootDirectory, input.agent.appRoot))} && export ${EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteVercelShellArgument(toVercelRelativePath(input.agent.appRoot, outputDirectory))} && export ${EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteVercelShellArgument(toVercelRelativePath(input.agent.appRoot, input.hostOutputDirectory))}${prefixExport} && ${input.agent.buildCommand}`,
+ root: toVercelRelativePath(input.projectRoot, rootDirectory),
+ rootDirectory,
+ };
+}
+
+/** Compile one eve agent into its complete Vercel service and ingress contribution. */
+export function compileEveVercelService(input: {
+ readonly agent: EveVercelAgentTarget;
+ readonly target: EveVercelBuildTarget;
+}): EveVercelServiceContribution {
+ const serviceName = createEveServiceName(input.agent.name);
+ const routeSrc = createEveServiceRouteSrc(input.agent.publicRoutePrefix);
+ const build = createIsolatedBuild({
+ agent: input.agent,
+ hostOutputDirectory: input.target.hostOutputDirectory,
+ projectRoot: input.target.projectRoot,
+ serviceName,
+ });
+
+ return {
+ rootDirectory: build.rootDirectory,
+ routeSrc,
+ service: {
+ buildCommand: build.buildCommand,
+ framework: "eve",
+ root: build.root,
+ routes: [createEveRequestPathRoute(routeSrc)],
+ ...(input.agent.publicRoutePrefix.length > 0
+ ? { routePrefix: input.agent.publicRoutePrefix }
+ : {}),
+ },
+ serviceName,
+ };
+}
diff --git a/packages/eve/src/internal/vercel/vercel-service-config-operations.ts b/packages/eve/src/internal/vercel/vercel-service-config-operations.ts
new file mode 100644
index 000000000..ddf5d01fb
--- /dev/null
+++ b/packages/eve/src/internal/vercel/vercel-service-config-operations.ts
@@ -0,0 +1,147 @@
+import { resolve } from "node:path";
+
+import {
+ createEvePublicRoute,
+ createEveRequestPathRoute,
+ createEveServiceName,
+ type EveVercelAgentTarget,
+} from "#internal/vercel/eve-service-contribution.js";
+import {
+ createServiceConfigRecord,
+ type VercelRouteConfig,
+ type VercelServiceConfig,
+ type VercelServicesCollection,
+ type VercelServicesConfig,
+} from "#internal/vercel/vercel-services-config.js";
+import { parseJsonObject, type JsonValue } from "#shared/json.js";
+
+export function resolveServicePrefix(service: VercelServiceConfig | undefined): string | undefined {
+ if (typeof service?.routePrefix === "string" && service.routePrefix.trim().length > 0) {
+ return service.routePrefix.trim();
+ }
+ if (typeof service?.mount === "string" && service.mount.trim().length > 0) {
+ return service.mount.trim();
+ }
+ if (
+ typeof service?.mount === "object" &&
+ typeof service.mount.path === "string" &&
+ service.mount.path.trim().length > 0
+ ) {
+ return service.mount.path.trim();
+ }
+ return undefined;
+}
+
+function parseLegacyServiceCollection(
+ value: JsonValue | undefined,
+): readonly VercelServiceConfig[] | undefined {
+ if (value === undefined) return undefined;
+ let entries: readonly JsonValue[];
+ try {
+ entries = Array.isArray(value) ? value : Object.values(parseJsonObject(value));
+ } catch {
+ return undefined;
+ }
+ return entries.flatMap((entry) => {
+ try {
+ return [parseJsonObject(entry) as VercelServiceConfig];
+ } catch {
+ return [];
+ }
+ });
+}
+
+function createServiceConfigList(
+ services: VercelServicesCollection | undefined,
+): readonly VercelServiceConfig[] | undefined {
+ return services === undefined ? undefined : Object.values(createServiceConfigRecord(services));
+}
+
+function resolveServiceRoot(configRoot: string, service: VercelServiceConfig): string | undefined {
+ const root = service.root ?? service.entrypoint;
+ return typeof root === "string" && root.trim().length > 0 ? resolve(configRoot, root) : undefined;
+}
+
+/** Resolve the mounted prefix for an eve service co-deployed with a host service. */
+export function resolveCoDeployedEveServicePrefix(input: {
+ readonly appRoots: readonly string[];
+ readonly config: VercelServicesConfig;
+ readonly configRoot: string;
+}): string | undefined {
+ const services =
+ parseLegacyServiceCollection(input.config.experimentalServices) ??
+ parseLegacyServiceCollection(input.config.experimentalServicesV2) ??
+ createServiceConfigList(input.config.services);
+ if (services === undefined || !services.some((service) => service.framework !== "eve")) {
+ return undefined;
+ }
+
+ for (const service of services) {
+ const prefix = resolveServicePrefix(service);
+ if (
+ service.framework === "eve" &&
+ prefix !== undefined &&
+ prefix !== "/" &&
+ input.appRoots.includes(resolveServiceRoot(input.configRoot, service) ?? "")
+ ) {
+ return prefix;
+ }
+ }
+ return undefined;
+}
+
+export function findConfiguredEveServiceEntry(
+ services: Record<string, VercelServiceConfig>,
+ agent: EveVercelAgentTarget,
+): { readonly name: string; readonly service: VercelServiceConfig } | undefined {
+ if (agent.name !== undefined) {
+ const name = createEveServiceName(agent.name);
+ const service = services[name];
+ return service?.framework === "eve" ? { name, service } : undefined;
+ }
+ const entry = Object.entries(services).find(([, service]) => service.framework === "eve");
+ return entry === undefined ? undefined : { name: entry[0], service: entry[1] };
+}
+
+export function insertEveServiceRequestPathRoute(
+ routes: readonly VercelRouteConfig[] | undefined,
+ routeSrc: string,
+): readonly VercelRouteConfig[] {
+ return [
+ createEveRequestPathRoute(routeSrc),
+ ...(routes ?? []).filter((route) => route.src !== routeSrc),
+ ];
+}
+
+function isEveServiceRoute(
+ route: VercelRouteConfig,
+ serviceName: string,
+ routeSrc: string,
+): boolean {
+ const destination = route.destination;
+ return (
+ route.src === routeSrc &&
+ typeof destination === "object" &&
+ destination.type === "service" &&
+ destination.service === serviceName
+ );
+}
+
+export function insertEveServiceRoutes(
+ routes: readonly VercelRouteConfig[],
+ eveRoutes: readonly { readonly routeSrc: string; readonly serviceName: string }[],
+): readonly VercelRouteConfig[] {
+ const retained = routes.filter(
+ (route) =>
+ !eveRoutes.some(({ routeSrc, serviceName }) =>
+ isEveServiceRoute(route, serviceName, routeSrc),
+ ),
+ );
+ const generated = eveRoutes.map(({ routeSrc, serviceName }) =>
+ createEvePublicRoute(serviceName, routeSrc),
+ );
+ const filesystemIndex = retained.findIndex((route) => route.handle === "filesystem");
+ return filesystemIndex < 0
+ ? [...generated, ...retained]
+ : [...retained.slice(0, filesystemIndex), ...generated, ...retained.slice(filesystemIndex)];
+}
diff --git a/packages/eve/src/internal/vercel/vercel-service-name.test.ts b/packages/eve/src/internal/vercel/vercel-service-name.test.ts
new file mode 100644
index 000000000..52c649543
--- /dev/null
+++ b/packages/eve/src/internal/vercel/vercel-service-name.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ assertValidVercelServiceName,
+ isValidVercelServiceName,
+} from "#internal/vercel/vercel-service-name.js";
+
+describe("Vercel service names", () => {
+ it("accepts the Vercel Services naming grammar", () => {
+ expect(isValidVercelServiceName("eve-support_agent")).toBe(true);
+ expect(isValidVercelServiceName("a".repeat(64))).toBe(true);
+ });
+
+ it("rejects digits, invalid boundaries, and names longer than 64 characters", () => {
+ expect(isValidVercelServiceName("eve-agent1")).toBe(false);
+ expect(isValidVercelServiceName("-eve")).toBe(false);
+ expect(isValidVercelServiceName("a".repeat(65))).toBe(false);
+ expect(() => assertValidVercelServiceName("eve-agent1", "Service name")).toThrow(
+ /Service name/,
+ );
+ });
+});
diff --git a/packages/eve/src/internal/vercel/vercel-service-name.ts b/packages/eve/src/internal/vercel/vercel-service-name.ts
new file mode 100644
index 000000000..e898e93b7
--- /dev/null
+++ b/packages/eve/src/internal/vercel/vercel-service-name.ts
@@ -0,0 +1,17 @@
+const VERCEL_SERVICE_NAME_PATTERN = /^[a-z](?:[a-z_-]*[a-z])?$/;
+
+/** Maximum service-name length accepted by Vercel Services. */
+export const MAX_VERCEL_SERVICE_NAME_LENGTH = 64;
+
+/** Whether a name satisfies the Vercel Services naming contract. */
+export function isValidVercelServiceName(name: string): boolean {
+ return name.length <= MAX_VERCEL_SERVICE_NAME_LENGTH && VERCEL_SERVICE_NAME_PATTERN.test(name);
+}
+
+/** Assert that a generated or authored service name can be deployed to Vercel. */
+export function assertValidVercelServiceName(name: string, subject: string): void {
+ if (isValidVercelServiceName(name)) return;
+ throw new Error(
+ `${subject} ${JSON.stringify(name)} is invalid. Vercel service names must use 1-${MAX_VERCEL_SERVICE_NAME_LENGTH} lowercase letters, hyphens, or underscores, beginning and ending with a letter.`,
+ );
+}
diff --git a/packages/eve/src/internal/vercel/vercel-services-config.test.ts b/packages/eve/src/internal/vercel/vercel-services-config.test.ts
new file mode 100644
index 000000000..51532cb97
--- /dev/null
+++ b/packages/eve/src/internal/vercel/vercel-services-config.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ createServiceConfigRecord,
+ parseVercelServicesConfig,
+} from "#internal/vercel/vercel-services-config.js";
+
+describe("parseVercelServicesConfig", () => {
+ it("normalizes named service arrays", () => {
+ const config = parseVercelServicesConfig(
+ { services: [{ name: "eve", framework: "eve", root: "agent" }] },
+ "vercel.json",
+ );
+ expect(createServiceConfigRecord(config.services)).toEqual({
+ eve: { framework: "eve", root: "agent" },
+ });
+ });
+
+ it.each([
+ [null, /must contain a JSON object/],
+ [{ services: null }, /services must be a JSON object or named service array/],
+ [{ services: { eve: null } }, /service "eve" must contain a JSON object/],
+ [{ services: [{}] }, /must have a non-empty name/],
+ [{ services: { eve: { framework: 42 } } }, /framework must be a string/],
+ [{ services: { eve: { mount: false } } }, /mount must be a string or JSON object/],
+ [{ services: { eve: { routes: {} } } }, /routes must be an array/],
+ [{ routes: {} }, /routes must be an array/],
+ [{ routes: [{ destination: 42 }] }, /destination must be a string or JSON object/],
+ ])("rejects malformed configuration %#", (value, expected) => {
+ expect(() => parseVercelServicesConfig(value, "vercel.json")).toThrow(expected);
+ });
+});
diff --git a/packages/eve/src/internal/vercel/vercel-services-config.ts b/packages/eve/src/internal/vercel/vercel-services-config.ts
new file mode 100644
index 000000000..409e744cd
--- /dev/null
+++ b/packages/eve/src/internal/vercel/vercel-services-config.ts
@@ -0,0 +1,220 @@
+import { readFile } from "node:fs/promises";
+
+import { parseJsonObject, type JsonObject, type JsonValue } from "#shared/json.js";
+
+export interface VercelServiceMount {
+ readonly path?: string;
+ readonly subdomain?: string;
+}
+
+export interface VercelServiceRouteDestination {
+ readonly service?: string;
+ readonly type?: string;
+}
+
+export interface VercelRouteTransform {
+ readonly args?: string;
+ readonly op?: string;
+ readonly type?: string;
+ readonly [key: string]: JsonValue | undefined;
+}
+
+export interface VercelRouteConfig {
+ readonly destination?: string | VercelServiceRouteDestination;
+ readonly handle?: string;
+ readonly src?: string;
+ readonly transforms?: readonly VercelRouteTransform[];
+ readonly [key: string]: unknown;
+}
+
+export interface VercelServiceConfig {
+ readonly buildCommand?: string;
+ readonly entrypoint?: string;
+ readonly framework?: string;
+ readonly mount?: string | VercelServiceMount;
+ readonly routes?: readonly VercelRouteConfig[];
+ readonly routePrefix?: string;
+ readonly root?: string;
+ readonly type?: string;
+}
+
+export interface GeneratedVercelServiceConfig extends VercelServiceConfig {
+ readonly buildCommand: string;
+ readonly framework: "eve";
+ readonly root: string;
+ readonly routes: readonly VercelRouteConfig[];
+}
+
+export type VercelServicesCollection =
+ | Record<string, VercelServiceConfig>
+ | readonly (VercelServiceConfig & { readonly name: string })[];
+
+export interface VercelServicesConfig {
+ readonly experimentalServices?: JsonValue;
+ readonly experimentalServicesV2?: JsonValue;
+ readonly routes?: readonly VercelRouteConfig[];
+ readonly services?: VercelServicesCollection;
+ readonly [key: string]: unknown;
+}
+
+function optionalString(value: JsonValue | undefined, path: string): string | undefined {
+ if (value === undefined) return undefined;
+ if (typeof value !== "string") throw new Error(`${path} must be a string.`);
+ return value;
+}
+
+function objectValue(value: JsonValue, path: string): JsonObject {
+ try {
+ return parseJsonObject(value);
+ } catch {
+ throw new Error(`${path} must contain a JSON object.`);
+ }
+}
+
+function parseDestination(
+ value: JsonValue | undefined,
+ path: string,
+): string | VercelServiceRouteDestination | undefined {
+ if (value === undefined || typeof value === "string") return value;
+ let destination: JsonObject;
+ try {
+ destination = parseJsonObject(value);
+ } catch {
+ throw new Error(`${path} must be a string or JSON object.`);
+ }
+ return {
+ ...destination,
+ service: optionalString(destination.service, `${path}.service`),
+ type: optionalString(destination.type, `${path}.type`),
+ };
+}
+
+function parseRoute(value: JsonValue, path: string): VercelRouteConfig {
+ const route = objectValue(value, path);
+ return {
+ ...route,
+ destination: parseDestination(route.destination, `${path}.destination`),
+ handle: optionalString(route.handle, `${path}.handle`),
+ src: optionalString(route.src, `${path}.src`),
+ };
+}
+
+function parseArray<T>(
+ value: JsonValue | undefined,
+ path: string,
+ parseEntry: (entry: JsonValue, path: string) => T,
+): readonly T[] | undefined {
+ if (value === undefined) return undefined;
+ if (!Array.isArray(value)) throw new Error(`${path} must be an array.`);
+ return value.map((entry, index) => parseEntry(entry, `${path}[${index}]`));
+}
+
+function parseMount(
+ value: JsonValue | undefined,
+ path: string,
+): string | VercelServiceMount | undefined {
+ if (value === undefined || typeof value === "string") return value;
+ let mount: JsonObject;
+ try {
+ mount = parseJsonObject(value);
+ } catch {
+ throw new Error(`${path} must be a string or JSON object.`);
+ }
+ return {
+ ...mount,
+ path: optionalString(mount.path, `${path}.path`),
+ subdomain: optionalString(mount.subdomain, `${path}.subdomain`),
+ };
+}
+
+function parseServiceConfig(value: JsonValue, path: string): VercelServiceConfig {
+ const service = objectValue(value, path);
+ return {
+ ...service,
+ buildCommand: optionalString(service.buildCommand, `${path}.buildCommand`),
+ entrypoint: optionalString(service.entrypoint, `${path}.entrypoint`),
+ framework: optionalString(service.framework, `${path}.framework`),
+ mount: parseMount(service.mount, `${path}.mount`),
+ routes: parseArray(service.routes, `${path}.routes`, parseRoute),
+ routePrefix: optionalString(service.routePrefix, `${path}.routePrefix`),
+ root: optionalString(service.root, `${path}.root`),
+ type: optionalString(service.type, `${path}.type`),
+ };
+}
+
+function parseServices(
+ value: JsonValue | undefined,
+ fileName: string,
+): VercelServicesCollection | undefined {
+ if (value === undefined) return undefined;
+ if (Array.isArray(value)) {
+ return value.map((entry, index) => {
+ const path = `${fileName} services[${index}]`;
+ const service = objectValue(entry, path);
+ const name = optionalString(service.name, `${path}.name`);
+ if (name === undefined || name.trim().length === 0) {
+ throw new Error(`${path} must have a non-empty name.`);
+ }
+ const { name: _name, ...config } = service;
+ return { ...parseServiceConfig(config, path), name };
+ });
+ }
+
+ let services: JsonObject;
+ try {
+ services = parseJsonObject(value);
+ } catch {
+ throw new Error(`${fileName} services must be a JSON object or named service array.`);
+ }
+ return Object.fromEntries(
+ Object.entries(services).map(([name, service]) => [
+ name,
+ parseServiceConfig(service, `${fileName} service ${JSON.stringify(name)}`),
+ ]),
+ );
+}
+
+/** Parse the Vercel configuration fields used by eve while preserving other JSON fields. */
+export function parseVercelServicesConfig(value: unknown, fileName: string): VercelServicesConfig {
+ let config: JsonObject;
+ try {
+ config = parseJsonObject(value);
+ } catch {
+ throw new Error(`${fileName} must contain a JSON object.`);
+ }
+
+ return {
+ ...config,
+ routes: parseArray(config.routes, `${fileName} routes`, parseRoute),
+ services: parseServices(config.services, fileName),
+ };
+}
+
+function isNamedServiceArray(
+ services: VercelServicesCollection,
+): services is readonly (VercelServiceConfig & { readonly name: string })[] {
+ return Array.isArray(services);
+}
+
+export function createServiceConfigRecord(
+ services: VercelServicesCollection | undefined,
+): Record<string, VercelServiceConfig> {
+ if (services === undefined) return {};
+ if (!isNamedServiceArray(services)) return services;
+ return Object.fromEntries(services.map(({ name, ...service }) => [name, service]));
+}
+
+export function hasServices(
+ services: VercelServicesCollection | undefined,
+): services is VercelServicesCollection {
+ return Object.keys(createServiceConfigRecord(services)).length > 0;
+}
+
+export async function readVercelJsonFile(path: string): Promise<VercelServicesConfig> {
+ try {
+ return parseVercelServicesConfig(JSON.parse(await readFile(path, "utf8")) as unknown, path);
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return {};
+ throw error;
+ }
+}
diff --git a/packages/eve/src/public/next/index.integration.test.ts b/packages/eve/src/public/next/index.integration.test.ts
index c136bcadf..3689294ae 100644
--- a/packages/eve/src/public/next/index.integration.test.ts
+++ b/packages/eve/src/public/next/index.integration.test.ts
@@ -384,7 +384,7 @@ describe("withEve Vercel config", () => {
},
"eve-support": {
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' && export EVE_PUBLIC_ROUTE_PREFIX='/eve/agents/support' && node '../../node_modules/eve/bin/eve.js' build",
+ "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' && export EVE_PUBLIC_ROUTE_PREFIX='/eve/agents/support' && node 'node_modules/eve/bin/eve.js' build",
framework: "eve",
routes: [
{
@@ -483,7 +483,7 @@ describe("withEve Vercel config", () => {
services: {
"eve-billing": {
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' && export EVE_PUBLIC_ROUTE_PREFIX='/eve/agents/billing' && node '../../node_modules/eve/bin/eve.js' build",
+ "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' && export EVE_PUBLIC_ROUTE_PREFIX='/eve/agents/billing' && node 'node_modules/eve/bin/eve.js' build",
framework: "eve",
routes: [
{
diff --git a/packages/eve/src/public/next/index.test.ts b/packages/eve/src/public/next/index.test.ts
index c8d2728d0..4ce4ea433 100644
--- a/packages/eve/src/public/next/index.test.ts
+++ b/packages/eve/src/public/next/index.test.ts
@@ -355,7 +355,7 @@ describe("withEve", () => {
},
{
appRoot: expect.stringContaining("/agents/support"),
- buildCommand: "node '../../node_modules/eve/bin/eve.js' build",
+ buildCommand: "node 'node_modules/eve/bin/eve.js' build",
name: "support",
publicRoutePrefix: "/eve/agents/support",
servicePrefix: `${EVE_NEXT_SERVICE_PREFIX}/support`,
@@ -395,6 +395,22 @@ describe("withEve", () => {
);
});
+ it("accepts digit-bearing public agent names", async () => {
+ vi.stubEnv("NODE_ENV", "production");
+ const config = await withEve<TestConfig>({}, { agents: { support2: "./agents/support" } })(
+ "phase-production-build",
+ { defaultConfig: {} },
+ );
+
+ await expect(config.rewrites?.()).resolves.toEqual(
+ expect.objectContaining({
+ beforeFiles: expect.arrayContaining([
+ expect.objectContaining({ source: "/eve/agents/support2/eve/v1/:path+" }),
+ ]),
+ }),
+ );
+ });
+
it("rejects eveRoot when named agents are configured", () => {
expect(() =>
withEve<TestConfig>(
diff --git a/packages/eve/src/public/next/index.ts b/packages/eve/src/public/next/index.ts
index 3a05e1ce3..94c40f016 100644
--- a/packages/eve/src/public/next/index.ts
+++ b/packages/eve/src/public/next/index.ts
@@ -1,7 +1,9 @@
-import { isAbsolute, relative, resolve } from "node:path";
+import { isAbsolute, resolve } from "node:path";
import type { NextConfig } from "next";
+import { assertValidPublicAgentName } from "#internal/agent-name.js";
+import { quoteVercelShellArgument, toVercelRelativePath } from "#internal/vercel/build-command.js";
import { EVE_ROUTE_PREFIX } from "#protocol/routes.js";
import { resolveEveBinaryPath } from "#shared/resolve-eve-binary.js";
import { resolveEveDestinationPrefix } from "./server.js";
@@ -17,7 +19,6 @@ const EVE_NEXT_PRODUCTION_ORIGIN_ENV = "EVE_NEXT_PRODUCTION_ORIGIN";
const EVE_NEXT_PRODUCTION_PORT_ENV = "EVE_NEXT_PRODUCTION_PORT";
const DEFAULT_EVE_NEXT_PRODUCTION_PORT = 4274;
const EVE_NAMED_AGENT_ROUTE_PREFIX = "/eve/agents";
-const AGENT_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]*$/;
type ArrayElement<T> = T extends readonly (infer TElement)[] ? TElement : never;
type NextRewrites = Awaited<ReturnType<NonNullable<NextConfig["rewrites"]>>>;
@@ -309,40 +310,21 @@ async function resolveNextConfig<TConfig extends EveNextConfig>(
}
function assertValidAgentName(name: string): void {
- if (!AGENT_NAME_PATTERN.test(name)) {
- throw new Error(
- `eve Next.js agent name ${JSON.stringify(
- name,
- )} is invalid. Use lowercase letters, numbers, underscores, or hyphens, starting with a letter or number.`,
- );
- }
-}
-
-function quoteShellArg(value: string): string {
- return `'${value.replaceAll("'", "'\\''")}'`;
-}
-
-function toPosixPath(path: string): string {
- return path.replaceAll("\\", "/");
+ assertValidPublicAgentName(name, "eve Next.js agent name");
}
-function createDefaultBuildCommand(input: {
- readonly agentRoot: string;
- readonly nextRoot: string;
-}): string {
- const eveBinaryPath = toPosixPath(
- relative(input.agentRoot, resolveEveBinaryPath(input.nextRoot)),
+function createDefaultBuildCommand(input: { readonly agentRoot: string }): string {
+ const eveBinaryPath = toVercelRelativePath(
+ input.agentRoot,
+ resolveEveBinaryPath(input.agentRoot),
);
- return `node ${quoteShellArg(eveBinaryPath)} build`;
+ return `node ${quoteVercelShellArgument(eveBinaryPath)} build`;
}
-function normalizeAgentsConfig(
- options: WithEveOptions,
- nextRoot: string,
-): readonly ResolvedEveNextAgent[] {
+function normalizeAgentsConfig(options: WithEveOptions): readonly ResolvedEveNextAgent[] {
const servicePrefixBase = normalizeRoutePrefix(options.servicePrefix ?? EVE_NEXT_SERVICE_PREFIX);
const resolveBuildCommand = (agentRoot: string, buildCommand: string | undefined) =>
- buildCommand ?? options.eveBuildCommand ?? createDefaultBuildCommand({ agentRoot, nextRoot });
+ buildCommand ?? options.eveBuildCommand ?? createDefaultBuildCommand({ agentRoot });
if (options.agents === undefined) {
const appRoot = resolveApplicationRoot(options.eveRoot);
@@ -403,7 +385,7 @@ export function withEve<TConfig extends EveNextConfig>(
): EveNextConfigFunction<TConfig> {
const nextRoot = process.cwd();
const devServerTimeoutMs = resolveDevServerTimeout(options.devServerTimeoutMs);
- const agents = normalizeAgentsConfig(options, nextRoot);
+ const agents = normalizeAgentsConfig(options);
return async function eveNextConfig(phase, context) {
const nextConfig = await resolveNextConfig(configOrFunction, phase, context);
diff --git a/packages/eve/src/public/next/vercel-output-config.ts b/packages/eve/src/public/next/vercel-output-config.ts
index 41b7418d9..e91118ed2 100644
--- a/packages/eve/src/public/next/vercel-output-config.ts
+++ b/packages/eve/src/public/next/vercel-output-config.ts
@@ -1,14 +1,18 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
-import { dirname, join, relative } from "node:path";
+import { dirname, join } from "node:path";
+import { assembleEveVercelServices } from "#internal/vercel/assemble-eve-services.js";
import {
- EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV,
- EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV,
-} from "#internal/application/build-output-environment.js";
+ findConfiguredEveServiceEntry,
+ resolveServicePrefix,
+} from "#internal/vercel/vercel-service-config-operations.js";
import {
- EVE_PUBLIC_ROUTE_PREFIX_ENV,
- normalizePublicRoutePrefix,
-} from "#shared/public-route-prefix.js";
+ createServiceConfigRecord,
+ hasServices,
+ parseVercelServicesConfig,
+ type VercelServiceConfig,
+ type VercelServicesConfig,
+} from "#internal/vercel/vercel-services-config.js";
import {
findClosestLinkedVercelDirectory,
findClosestVercelOutputDirectory,
@@ -17,67 +21,6 @@ import {
const VERCEL_JSON_FILE_NAME = "vercel.json";
const VERCEL_OUTPUT_CONFIG_FILE_NAME = ".vercel/output/config.json";
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;
- readonly subdomain?: string;
-}
-
-interface VercelServiceConfig {
- readonly buildCommand?: string;
- readonly entrypoint?: string;
- readonly framework?: string;
- readonly mount?: string | VercelServiceMount;
- readonly routes?: readonly VercelRouteConfig[];
- readonly routePrefix?: string;
- readonly root?: string;
- readonly type?: string;
-}
-
-interface MutableGeneratedVercelServiceConfig {
- buildCommand: string;
- framework: "eve";
- routePrefix?: string;
- routes: readonly VercelRouteConfig[];
- root: string;
-}
-
-interface VercelNamedServiceConfig extends VercelServiceConfig {
- readonly name?: string;
-}
-
-type VercelServicesCollection =
- | Record<string, VercelServiceConfig>
- | readonly VercelNamedServiceConfig[];
-
-interface VercelServiceRouteDestination {
- readonly service?: string;
- readonly type?: string;
-}
-
-interface VercelRequestPathTransform {
- readonly args: string;
- readonly op: "set";
- readonly type: "request.path";
-}
-
-interface VercelRouteConfig {
- readonly destination?: string | VercelServiceRouteDestination;
- readonly handle?: string;
- readonly src?: string;
- readonly transforms?: readonly VercelRequestPathTransform[];
- readonly [key: string]: unknown;
-}
-
-interface VercelServicesConfig {
- readonly routes?: readonly VercelRouteConfig[];
- readonly services?: VercelServicesCollection;
- readonly [key: string]: unknown;
-}
interface VercelOutputConfig extends VercelServicesConfig {
readonly version?: number;
@@ -100,93 +43,6 @@ export interface EnsureVercelOutputConfigAgentResult {
readonly servicePrefix: string;
}
-function isRecord(value: unknown): value is Record<string, unknown> {
- return value !== null && typeof value === "object" && !Array.isArray(value);
-}
-
-function hasServices(
- services: VercelServicesCollection | undefined,
-): services is VercelServicesCollection {
- return services !== undefined && Object.keys(createServiceConfigRecord(services)).length > 0;
-}
-
-function isNamedServiceConfigArray(
- services: VercelServicesCollection,
-): services is readonly VercelNamedServiceConfig[] {
- return Array.isArray(services);
-}
-
-function createServiceConfigRecord(
- services: VercelServicesCollection | undefined,
-): Record<string, VercelServiceConfig> {
- if (services === undefined) {
- return {};
- }
-
- if (isNamedServiceConfigArray(services)) {
- const record: Record<string, VercelServiceConfig> = {};
-
- for (const service of services) {
- if (typeof service.name === "string" && service.name.trim().length > 0) {
- const { name, ...serviceConfig } = service;
- record[name] = serviceConfig;
- }
- }
-
- return record;
- }
-
- return services;
-}
-
-function resolveRelativeEntrypoint(fromRoot: string, toRoot: string): string {
- const relativePath = relative(fromRoot, toRoot);
-
- if (relativePath.length === 0) {
- return ".";
- }
-
- 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,
- );
- // Named agents are publicly mounted under this prefix while the service
- // itself receives prefix-stripped `/eve/v1/*` paths, so the build must
- // carry the prefix into the workflow runtime for callback-URL minting.
- const publicRoutePrefix = normalizePublicRoutePrefix(input.agent.publicRoutePrefix);
- const publicRoutePrefixExport =
- publicRoutePrefix === undefined
- ? ""
- : ` && export ${EVE_PUBLIC_ROUTE_PREFIX_ENV}=${quoteShellArgument(publicRoutePrefix)}`;
-
- return {
- buildCommand: `cd ${quoteShellArgument(workingDirectory)} && export ${EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(configuredOutputDirectory)} && export ${EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(configuredHostOutputDirectory)}${publicRoutePrefixExport} && ${input.agent.buildCommand}`,
- root: resolveRelativeEntrypoint(input.nextRoot, rootDirectory),
- rootDirectory,
- };
-}
-
async function resolveVercelOutputConfigLocation(nextRoot: string): Promise<{
readonly canWriteGeneratedOutput: boolean;
readonly outputConfigPath: string;
@@ -219,45 +75,12 @@ async function resolveVercelOutputConfigLocation(nextRoot: string): Promise<{
};
}
-function normalizeVercelServicesConfig(value: unknown, fileName: string): VercelServicesConfig {
- if (!isRecord(value)) {
- throw new Error(`${fileName} must contain a JSON object.`);
- }
-
- const services = value.services;
-
- if (
- services !== undefined &&
- !isRecord(services) &&
- !(
- Array.isArray(services) &&
- services.every(
- (service) =>
- isRecord(service) && typeof service.name === "string" && service.name.trim().length > 0,
- )
- )
- ) {
- throw new Error(`${fileName} services must be a JSON object or named service array.`);
- }
-
- const routes = value.routes;
-
- if (routes !== undefined && !Array.isArray(routes)) {
- throw new Error(`${fileName} routes must be an array.`);
- }
-
- return value as VercelServicesConfig;
-}
-
async function readVercelServicesConfig(
path: string,
fileName: string,
): Promise<VercelServicesConfig> {
try {
- return normalizeVercelServicesConfig(
- JSON.parse(await readFile(path, "utf8")) as unknown,
- fileName,
- );
+ return parseVercelServicesConfig(JSON.parse(await readFile(path, "utf8")) as unknown, fileName);
} catch (error) {
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
return {};
@@ -267,47 +90,6 @@ async function readVercelServicesConfig(
}
}
-function findServiceEntryByFramework(
- services: Record<string, VercelServiceConfig>,
- framework: string,
-): { readonly name: string; readonly service: VercelServiceConfig } | undefined {
- return Object.entries(services)
- .map(([name, service]) => ({ name, service }))
- .find((entry) => entry.service.framework === framework);
-}
-
-function findServiceEntryByName(
- services: Record<string, VercelServiceConfig>,
- name: string,
-): { readonly name: string; readonly service: VercelServiceConfig } | undefined {
- const service = services[name];
- return service === undefined ? undefined : { name, service };
-}
-
-function resolveServicePrefix(service: VercelServiceConfig | undefined): string | undefined {
- if (service === undefined) {
- return undefined;
- }
-
- if (typeof service.routePrefix === "string" && service.routePrefix.trim().length > 0) {
- return service.routePrefix.trim();
- }
-
- if (typeof service.mount === "string" && service.mount.trim().length > 0) {
- return service.mount.trim();
- }
-
- if (
- isRecord(service.mount) &&
- typeof service.mount.path === "string" &&
- service.mount.path.trim().length > 0
- ) {
- return service.mount.path.trim();
- }
-
- return undefined;
-}
-
function resolveConfiguredServicePrefix(input: {
readonly agent: EnsureVercelOutputConfigAgentInput;
readonly services: Record<string, VercelServiceConfig>;
@@ -316,20 +98,6 @@ function resolveConfiguredServicePrefix(input: {
return resolveServicePrefix(configuredEveService) ?? input.agent.servicePrefix;
}
-function findConfiguredEveServiceEntry(
- services: Record<string, VercelServiceConfig>,
- agent: EnsureVercelOutputConfigAgentInput,
-): { readonly name: string; readonly service: VercelServiceConfig } | undefined {
- if (agent.name !== undefined) {
- const namedService = findServiceEntryByName(services, createEveServiceName(agent.name));
- if (namedService?.service.framework === "eve") {
- return namedService;
- }
- }
-
- return agent.name === undefined ? findServiceEntryByFramework(services, "eve") : undefined;
-}
-
function assertRootServicesIncludeEve(input: {
readonly agents: readonly EnsureVercelOutputConfigAgentInput[];
readonly services: Record<string, VercelServiceConfig>;
@@ -354,110 +122,6 @@ function assertRootServicesIncludeEve(input: {
return results;
}
-function createEveServiceRouteSrc(publicRoutePrefix: string): string {
- if (publicRoutePrefix.length === 0) {
- return EVE_SERVICE_ROUTE_SRC;
- }
-
- const normalizedPrefix = publicRoutePrefix.startsWith("/")
- ? publicRoutePrefix
- : `/${publicRoutePrefix}`;
- return `^${escapeRegExp(normalizedPrefix)}/eve/v1/(.*)$`;
-}
-
-function escapeRegExp(value: string): string {
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-}
-
-function createEveServiceName(name: string | undefined): string {
- return name === undefined ? EVE_SERVICE_NAME : `${EVE_SERVICE_NAME}-${name}`;
-}
-
-function isEveServiceRoute(
- route: VercelRouteConfig,
- serviceName: string,
- routeSrc: string,
-): boolean {
- const destination = route.destination;
-
- return (
- route.src === routeSrc &&
- isRecord(destination) &&
- destination.type === "service" &&
- destination.service === serviceName
- );
-}
-
-function createEveServiceRoute(serviceName: string, routeSrc: string): VercelRouteConfig {
- return {
- destination: {
- service: serviceName,
- type: "service",
- },
- src: routeSrc,
- };
-}
-
-function isEveServiceRequestPathRoute(route: VercelRouteConfig, routeSrc: string): boolean {
- return route.src === routeSrc;
-}
-
-function createEveServiceRequestPathRoute(routeSrc: string): VercelRouteConfig {
- return {
- src: routeSrc,
- transforms: [
- {
- args: EVE_SERVICE_ROUTE_PATH,
- op: "set",
- type: "request.path",
- },
- ],
- };
-}
-
-function insertEveServiceRequestPathRoute(
- routes: readonly VercelRouteConfig[] | undefined,
- routeSrc: string,
-): readonly VercelRouteConfig[] {
- const existingRoutes = routes ?? [];
- const routesWithoutGeneratedRoute = existingRoutes.filter(
- (route) => !isEveServiceRequestPathRoute(route, routeSrc),
- );
-
- return [createEveServiceRequestPathRoute(routeSrc), ...routesWithoutGeneratedRoute];
-}
-
-function insertEveServiceRoutes(
- routes: readonly VercelRouteConfig[],
- eveRoutes: readonly {
- readonly routeSrc: string;
- readonly serviceName: string;
- }[],
-): readonly VercelRouteConfig[] {
- const routesWithoutEveRoutes = routes.filter(
- (route) =>
- !eveRoutes.some((eveRoute) =>
- isEveServiceRoute(route, eveRoute.serviceName, eveRoute.routeSrc),
- ),
- );
- const filesystemRouteIndex = routesWithoutEveRoutes.findIndex(
- (route) => route.handle === "filesystem",
- );
- const nextEveRoutes = eveRoutes.map((eveRoute) =>
- createEveServiceRoute(eveRoute.serviceName, eveRoute.routeSrc),
- );
-
- if (filesystemRouteIndex === -1) {
- return [...nextEveRoutes, ...routesWithoutEveRoutes];
- }
-
- return [
- ...routesWithoutEveRoutes.slice(0, filesystemRouteIndex),
- ...nextEveRoutes,
- ...routesWithoutEveRoutes.slice(filesystemRouteIndex),
- ];
-}
-
export async function ensureEveVercelOutputConfig(input: {
readonly agents: readonly EnsureVercelOutputConfigAgentInput[];
readonly nextRoot: string;
@@ -498,60 +162,24 @@ export async function ensureEveVercelOutputConfig(input: {
};
}
- const services: Record<string, VercelServiceConfig> = {
- ...existingServices,
- };
- const eveRoutes: {
- routeSrc: string;
- serviceName: string;
- }[] = [];
-
- for (const agent of input.agents) {
- const configuredEveServiceEntry = findConfiguredEveServiceEntry(existingServices, agent);
- const serviceName = configuredEveServiceEntry?.name ?? createEveServiceName(agent.name);
- const routeSrc = createEveServiceRouteSrc(agent.publicRoutePrefix);
-
- if (configuredEveServiceEntry === undefined) {
- const generatedServiceBuild = createGeneratedServiceBuild({
- agent,
+ const assembled = assembleEveVercelServices({
+ agents: input.agents.map((agent) => ({
+ agent,
+ target: {
hostOutputDirectory: dirname(outputConfigPath),
- nextRoot: input.nextRoot,
- serviceName,
- });
- await mkdir(generatedServiceBuild.rootDirectory, { recursive: true });
- const serviceConfig: MutableGeneratedVercelServiceConfig = {
- buildCommand: generatedServiceBuild.buildCommand,
- framework: "eve",
- routes: insertEveServiceRequestPathRoute(undefined, routeSrc),
- root: generatedServiceBuild.root,
- };
-
- if (agent.publicRoutePrefix.length > 0) {
- serviceConfig.routePrefix = agent.publicRoutePrefix;
- }
-
- services[serviceName] = serviceConfig;
- } else {
- services[serviceName] = {
- ...configuredEveServiceEntry.service,
- routes: insertEveServiceRequestPathRoute(
- configuredEveServiceEntry.service.routes,
- routeSrc,
- ),
- };
- }
-
- eveRoutes.push({
- routeSrc,
- serviceName,
- });
- }
+ projectRoot: input.nextRoot,
+ },
+ })),
+ routes: existingConfig.routes,
+ services: existingServices,
+ });
+ await Promise.all(assembled.rootDirectories.map((root) => mkdir(root, { recursive: true })));
const { services: _services, ...configWithoutLegacyServices } = existingConfig;
const vercelConfig: VercelOutputConfig = {
...configWithoutLegacyServices,
- routes: insertEveServiceRoutes(existingConfig.routes ?? [], eveRoutes),
- services,
+ routes: assembled.routes,
+ services: assembled.services,
version: VERCEL_BUILD_OUTPUT_VERSION,
};