Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): add build profiles (#814)

Casey Gowriebfbbe9217433
diff --git a/.changeset/build-profiles.md b/.changeset/build-profiles.md
new file mode 100644
index 000000000..6f20d51d8
--- /dev/null
+++ b/.changeset/build-profiles.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Add `eve build --profile <path>` for a machine-readable build-timing and final-output-size report.
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index 1e9bcbb3b..072c55dd8 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -90,11 +90,24 @@ Run this first when something behaves unexpectedly. It confirms a file was disco
## `eve build`
```bash
-eve build
+eve build [--profile <path>] [--skip-sandbox-prewarm]
```
Compiles and bundles in an invocation-owned directory under `.eve/builds/`, then publishes the completed host output and prints its path. Scratch workspaces are removed after success or failure.
+| Flag | Type | Default | Description |
+| ------------------------ | ------ | ------- | ----------------------------------------------------------------------------------------- |
+| `--profile <path>` | string | off | Write a versioned JSON report with build-phase timings and final output-size measurements |
+| `--skip-sandbox-prewarm` | flag | off | Skip sandbox template prewarm for a Vercel build; the output might not be deployable |
+
+Use a profile file to establish a repeatable baseline before changing the build pipeline:
+
+```bash
+eve build --profile .eve/build-profiles/baseline.json
+```
+
+The report is written only after a successful build. It records total elapsed time, completed phase timings, and final regular-file totals for file count, raw bytes, and the sum of each file compressed with gzip. For Vercel output it also includes a subtotal for every real `.func` directory, so app and flow bundles can be compared separately. The profile path resolves from the app root and must be outside the published output directory; profile collection does not add a file to the deployment.
+
Production builds do not write through the stable compiler, host, Nitro, or Workflow files owned by `eve dev`, so builds can run while a local dev server is active. A failed build leaves the last successful `.output/` and agent summary untouched. Concurrent completed builds serialize only the final publication window.
Useful stable artifacts written by inspection and development flows under `.eve/` include:
diff --git a/packages/eve/src/cli/commands/build.ts b/packages/eve/src/cli/commands/build.ts
new file mode 100644
index 000000000..14762166e
--- /dev/null
+++ b/packages/eve/src/cli/commands/build.ts
@@ -0,0 +1,74 @@
+import { resolve } from "node:path";
+
+import type { Command } from "#compiled/commander/index.js";
+import { resolveInternalVercelServiceOutput } from "#cli/vercel-service-output.js";
+import { createCliTheme, renderCliTaggedLine } from "#cli/ui/output.js";
+import type { ApplicationBuildOptions } from "#internal/nitro/host/types.js";
+
+export type BuildHost = (appRoot: string, options: ApplicationBuildOptions) => Promise<string>;
+
+interface BuildCommandLogger {
+ log(message: string): void;
+}
+
+interface BuildCliOptions {
+ profile?: string;
+ skipSandboxPrewarm?: boolean;
+}
+
+/** Registers the production application build command. */
+export function registerBuildCommand(input: {
+ readonly appRoot: string;
+ readonly buildHost?: BuildHost;
+ readonly logger: BuildCommandLogger;
+ readonly program: Command;
+}): void {
+ const theme = createCliTheme();
+
+ input.program
+ .command("build")
+ .description("Build the current eve application.")
+ .option("--profile <path>", "Write timing and output-size profile JSON to a file")
+ .option(
+ "--skip-sandbox-prewarm",
+ "Skip sandbox template prewarm for a Vercel build; output may not be deployable",
+ )
+ .action(async (options: BuildCliOptions) => {
+ const { loadDevelopmentEnvironmentFiles } = await import("#cli/dev/environment.js");
+
+ loadDevelopmentEnvironmentFiles(input.appRoot);
+
+ const buildHost =
+ input.buildHost ?? (await import("#internal/nitro/host.js")).buildApplication;
+ const profileOutputPath =
+ options.profile === undefined ? undefined : resolve(input.appRoot, options.profile);
+ const buildOptions: {
+ profileOutputPath?: string;
+ readonly skipVercelSandboxPrewarm: boolean;
+ readonly vercelServiceOutput: ApplicationBuildOptions["vercelServiceOutput"];
+ } = {
+ skipVercelSandboxPrewarm: options.skipSandboxPrewarm === true,
+ vercelServiceOutput: resolveInternalVercelServiceOutput(input.appRoot),
+ };
+ if (profileOutputPath !== undefined) {
+ buildOptions.profileOutputPath = profileOutputPath;
+ }
+ const outputDir = await buildHost(input.appRoot, buildOptions);
+ input.logger.log(
+ renderCliTaggedLine(theme, {
+ message: `built output at ${outputDir}`,
+ tag: "build",
+ tone: "success",
+ }),
+ );
+ if (profileOutputPath !== undefined) {
+ input.logger.log(
+ renderCliTaggedLine(theme, {
+ message: `wrote build profile to ${profileOutputPath}`,
+ tag: "build",
+ tone: "success",
+ }),
+ );
+ }
+ });
+}
diff --git a/packages/eve/src/cli/run.test.ts b/packages/eve/src/cli/run.test.ts
index fb69fea92..aceaa29d0 100644
--- a/packages/eve/src/cli/run.test.ts
+++ b/packages/eve/src/cli/run.test.ts
@@ -405,6 +405,27 @@ describe("eve dev local server ownership", () => {
});
describe("eve build output ownership", () => {
+ it("forwards a profile path relative to the application root and reports it", async () => {
+ const buildHost = vi.fn(async () => "/app/.output");
+ const output: string[] = [];
+ const profilePath = ".eve/build-profiles/notes.json";
+
+ await runCli(
+ ["build", "--profile", profilePath],
+ { error: () => {}, log: (message) => output.push(message) },
+ { buildHost },
+ );
+
+ expect(buildHost).toHaveBeenCalledWith(process.cwd(), {
+ profileOutputPath: resolve(process.cwd(), profilePath),
+ skipVercelSandboxPrewarm: false,
+ vercelServiceOutput: undefined,
+ });
+ expect(output.join("\n")).toContain(
+ `wrote build profile to ${resolve(process.cwd(), profilePath)}`,
+ );
+ });
+
it("resolves the internal service output directory from the build working directory", async () => {
const buildHost = vi.fn(async () => "/service/.vercel/output");
const configuredDirectory = ".eve/vercel-services/eve/.vercel/output";
diff --git a/packages/eve/src/cli/run.ts b/packages/eve/src/cli/run.ts
index e3a7e19fe..9646fcd43 100644
--- a/packages/eve/src/cli/run.ts
+++ b/packages/eve/src/cli/run.ts
@@ -1,10 +1,10 @@
import { Command, CommanderError, InvalidArgumentError } from "#compiled/commander/index.js";
+import { registerBuildCommand, type BuildHost } from "#cli/commands/build.js";
import { devBootPhase, type DevBootProgressReporter } from "#internal/dev-boot-progress.js";
import { resolveApplicationRoot } from "#internal/application/paths.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import { isCodingAgentLaunch } from "#cli/agent-detection.js";
import { eveCliBanner } from "#cli/banner.js";
-import { resolveInternalVercelServiceOutput } from "#cli/vercel-service-output.js";
import { registerProjectCommands } from "#cli/commands/register-project-commands.js";
import { resolveDevUiMode, resolveTuiDisplayOptions } from "#cli/dev/ui-options.js";
import {
@@ -20,7 +20,6 @@ import { startCliLiveRow } from "#cli/ui/live-row.js";
import { createCliTheme, renderCliTaggedLine } from "#cli/ui/output.js";
import { createLogger } from "#internal/logging.js";
import type {
- ApplicationBuildOptions,
DevelopmentServer,
DevelopmentServerOptions,
ProductionServerHandle,
@@ -60,17 +59,13 @@ interface ProductionCliOptions {
port?: number;
}
-interface BuildCliOptions {
- skipSandboxPrewarm?: boolean;
-}
-
interface CliRuntimeDependencies {
isCodingAgentLaunch(): Promise<boolean>;
isActiveDevelopmentServerForApp(input: {
readonly appRoot: string;
readonly serverUrl: string;
}): Promise<boolean>;
- buildHost(appRoot: string, options: ApplicationBuildOptions): Promise<string>;
+ buildHost: BuildHost;
printApplicationInfo(
logger: CliLogger,
appRoot: string,
@@ -132,10 +127,6 @@ interface EvalCliOptions {
verbose?: boolean;
}
-async function loadBuildHost(): Promise<CliRuntimeDependencies["buildHost"]> {
- return (await import("#internal/nitro/host.js")).buildApplication;
-}
-
async function loadPrintApplicationInfo(): Promise<CliRuntimeDependencies["printApplicationInfo"]> {
return (await import("#cli/commands/info.js")).printApplicationInfo;
}
@@ -366,31 +357,12 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm
registerProjectCommands({ program, logger, appRoot });
- program
- .command("build")
- .description("Build the current eve application.")
- .option(
- "--skip-sandbox-prewarm",
- "Skip Vercel sandbox template prewarm; output may not be deployable",
- )
- .action(async (options: BuildCliOptions) => {
- const { loadDevelopmentEnvironmentFiles } = await import("#cli/dev/environment.js");
-
- loadDevelopmentEnvironmentFiles(appRoot);
-
- const buildHost = runtime.buildHost ?? (await loadBuildHost());
- const outputDir = await buildHost(appRoot, {
- skipVercelSandboxPrewarm: options.skipSandboxPrewarm === true,
- vercelServiceOutput: resolveInternalVercelServiceOutput(appRoot),
- });
- logger.log(
- renderCliTaggedLine(theme, {
- message: `built output at ${outputDir}`,
- tag: "build",
- tone: "success",
- }),
- );
- });
+ registerBuildCommand({
+ appRoot,
+ buildHost: runtime.buildHost,
+ logger,
+ program,
+ });
program
.command("start")
diff --git a/packages/eve/src/internal/application/build-profile.test.ts b/packages/eve/src/internal/application/build-profile.test.ts
new file mode 100644
index 000000000..51de213cc
--- /dev/null
+++ b/packages/eve/src/internal/application/build-profile.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ APPLICATION_BUILD_PROFILE_SCHEMA_VERSION,
+ ApplicationBuildProfiler,
+ createApplicationBuildProfile,
+} from "./build-profile.js";
+
+describe("ApplicationBuildProfiler", () => {
+ it("records rounded phase timings and one total duration", async () => {
+ let now = 100;
+ const profiler = new ApplicationBuildProfiler({ now: () => now });
+
+ await profiler.measure("host.prepare", async () => {
+ now = 123.456;
+ });
+ await profiler.measure("nitro.all.bundle", () => {
+ now = 200;
+ });
+
+ expect(profiler.finish()).toEqual({
+ durationMs: 100,
+ phases: [
+ { durationMs: 23.5, name: "host.prepare" },
+ { durationMs: 76.5, name: "nitro.all.bundle" },
+ ],
+ });
+ });
+
+ it("keeps failed phase timing for callers that handle an error", async () => {
+ let now = 10;
+ const profiler = new ApplicationBuildProfiler({ now: () => now });
+
+ await expect(
+ profiler.measure("nitro.all.bundle", () => {
+ now = 25;
+ throw new Error("bundle failed");
+ }),
+ ).rejects.toThrow("bundle failed");
+
+ expect(profiler.finish()).toEqual({
+ durationMs: 15,
+ phases: [{ durationMs: 15, name: "nitro.all.bundle" }],
+ });
+ });
+});
+
+describe("createApplicationBuildProfile", () => {
+ it("creates a versioned, machine-readable profile", () => {
+ expect(
+ createApplicationBuildProfile({
+ output: {
+ files: 3,
+ functionBundles: [
+ { files: 2, gzipBytes: 18, path: "functions/eve/__server.func", rawBytes: 42 },
+ ],
+ gzipBytes: 27,
+ rawBytes: 64,
+ },
+ target: "vercel",
+ timing: {
+ durationMs: 125.4,
+ phases: [{ durationMs: 100, name: "nitro.flow.bundle" }],
+ },
+ }),
+ ).toEqual({
+ durationMs: 125.4,
+ kind: "eve-build-profile",
+ output: {
+ files: 3,
+ functionBundles: [
+ { files: 2, gzipBytes: 18, path: "functions/eve/__server.func", rawBytes: 42 },
+ ],
+ gzipBytes: 27,
+ rawBytes: 64,
+ },
+ phases: [{ durationMs: 100, name: "nitro.flow.bundle" }],
+ schemaVersion: APPLICATION_BUILD_PROFILE_SCHEMA_VERSION,
+ target: "vercel",
+ });
+ });
+});
diff --git a/packages/eve/src/internal/application/build-profile.ts b/packages/eve/src/internal/application/build-profile.ts
new file mode 100644
index 000000000..d5066f45c
--- /dev/null
+++ b/packages/eve/src/internal/application/build-profile.ts
@@ -0,0 +1,221 @@
+import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
+import { dirname, join, relative, sep } from "node:path";
+import { performance } from "node:perf_hooks";
+import { gzipSync } from "node:zlib";
+
+/** Version of the machine-readable `eve build --profile` report schema. */
+export const APPLICATION_BUILD_PROFILE_SCHEMA_VERSION = 1 as const;
+
+/** Deployment target represented by one build profile. */
+export type ApplicationBuildProfileTarget = "local" | "vercel";
+
+/** One completed phase in an application build profile. */
+export interface ApplicationBuildProfilePhase {
+ readonly durationMs: number;
+ readonly name: string;
+}
+
+/** Size totals for one Vercel function directory in the published output. */
+export interface ApplicationBuildProfileFunctionBundle {
+ readonly files: number;
+ readonly gzipBytes: number;
+ readonly path: string;
+ readonly rawBytes: number;
+}
+
+/** Final output-size measurements collected after a successful publication. */
+export interface ApplicationBuildProfileOutput {
+ readonly files: number;
+ readonly functionBundles: readonly ApplicationBuildProfileFunctionBundle[];
+ readonly gzipBytes: number;
+ readonly rawBytes: number;
+}
+
+/** Timing data gathered while an application build runs. */
+export interface ApplicationBuildProfileTiming {
+ readonly durationMs: number;
+ readonly phases: readonly ApplicationBuildProfilePhase[];
+}
+
+/** Stable JSON document written by `eve build --profile <path>`. */
+export interface ApplicationBuildProfile {
+ readonly durationMs: number;
+ readonly kind: "eve-build-profile";
+ readonly output: ApplicationBuildProfileOutput;
+ readonly phases: readonly ApplicationBuildProfilePhase[];
+ readonly schemaVersion: typeof APPLICATION_BUILD_PROFILE_SCHEMA_VERSION;
+ readonly target: ApplicationBuildProfileTarget;
+}
+
+interface MutableOutputSize {
+ files: number;
+ gzipBytes: number;
+ rawBytes: number;
+}
+
+interface FileSize {
+ readonly gzipBytes: number;
+ readonly rawBytes: number;
+}
+
+interface ApplicationBuildProfilerOptions {
+ readonly now?: () => number;
+}
+
+function roundDuration(durationMs: number): number {
+ return Math.round(Math.max(0, durationMs) * 10) / 10;
+}
+
+function createMutableOutputSize(): MutableOutputSize {
+ return { files: 0, gzipBytes: 0, rawBytes: 0 };
+}
+
+function toOutputSize(
+ size: MutableOutputSize,
+): Omit<ApplicationBuildProfileOutput, "functionBundles"> {
+ return {
+ files: size.files,
+ gzipBytes: size.gzipBytes,
+ rawBytes: size.rawBytes,
+ };
+}
+
+function toProfilePath(outputDirectory: string, directoryPath: string): string {
+ return relative(outputDirectory, directoryPath).split(sep).join("/");
+}
+
+function measureFileSize(contents: Buffer): FileSize {
+ return {
+ gzipBytes: gzipSync(contents).byteLength,
+ rawBytes: contents.byteLength,
+ };
+}
+
+function addFileSize(size: MutableOutputSize, fileSize: FileSize): void {
+ size.files += 1;
+ size.rawBytes += fileSize.rawBytes;
+ size.gzipBytes += fileSize.gzipBytes;
+}
+
+/**
+ * Records elapsed build phases only when profile output was requested. The
+ * injected clock keeps its serialization behavior independently testable.
+ */
+export class ApplicationBuildProfiler {
+ readonly #now: () => number;
+ readonly #phases: ApplicationBuildProfilePhase[] = [];
+ readonly #startedAt: number;
+ #finished = false;
+
+ constructor(options: ApplicationBuildProfilerOptions = {}) {
+ this.#now = options.now ?? performance.now.bind(performance);
+ this.#startedAt = this.#now();
+ }
+
+ async measure<T>(name: string, operation: () => T | Promise<T>): Promise<T> {
+ if (this.#finished) {
+ throw new Error("Cannot record a phase after the build profile has finished.");
+ }
+
+ const startedAt = this.#now();
+ try {
+ return await operation();
+ } finally {
+ this.#phases.push({
+ durationMs: roundDuration(this.#now() - startedAt),
+ name,
+ });
+ }
+ }
+
+ finish(): ApplicationBuildProfileTiming {
+ if (this.#finished) {
+ throw new Error("The build profile has already finished.");
+ }
+
+ this.#finished = true;
+ return {
+ durationMs: roundDuration(this.#now() - this.#startedAt),
+ phases: [...this.#phases],
+ };
+ }
+}
+
+/** Creates the versioned report shape from completed timings and output measurements. */
+export function createApplicationBuildProfile(input: {
+ readonly output: ApplicationBuildProfileOutput;
+ readonly target: ApplicationBuildProfileTarget;
+ readonly timing: ApplicationBuildProfileTiming;
+}): ApplicationBuildProfile {
+ return {
+ durationMs: input.timing.durationMs,
+ kind: "eve-build-profile",
+ output: input.output,
+ phases: input.timing.phases,
+ schemaVersion: APPLICATION_BUILD_PROFILE_SCHEMA_VERSION,
+ target: input.target,
+ };
+}
+
+/**
+ * Measures regular files in the published output without following symlinks.
+ * Each `.func` directory receives its own subtotal for Vercel output.
+ */
+export async function measureApplicationBuildOutput(
+ outputDirectory: string,
+): Promise<ApplicationBuildProfileOutput> {
+ const total = createMutableOutputSize();
+ const functionBundles = new Map<string, MutableOutputSize>();
+
+ const visit = async (
+ directoryPath: string,
+ activeFunctionBundle: string | undefined,
+ ): Promise<void> => {
+ const entries = await readdir(directoryPath, { withFileTypes: true });
+
+ for (const entry of entries) {
+ const entryPath = join(directoryPath, entry.name);
+
+ if (entry.isDirectory()) {
+ const functionBundle = entry.name.endsWith(".func")
+ ? toProfilePath(outputDirectory, entryPath)
+ : activeFunctionBundle;
+ await visit(entryPath, functionBundle);
+ continue;
+ }
+
+ if (!entry.isFile()) {
+ continue;
+ }
+
+ const contents = await readFile(entryPath);
+ const fileSize = measureFileSize(contents);
+ addFileSize(total, fileSize);
+
+ if (activeFunctionBundle !== undefined) {
+ const functionBundle =
+ functionBundles.get(activeFunctionBundle) ?? createMutableOutputSize();
+ addFileSize(functionBundle, fileSize);
+ functionBundles.set(activeFunctionBundle, functionBundle);
+ }
+ }
+ };
+
+ await visit(outputDirectory, undefined);
+
+ return {
+ ...toOutputSize(total),
+ functionBundles: [...functionBundles.entries()]
+ .map(([path, size]) => ({ path, ...toOutputSize(size) }))
+ .sort((left, right) => left.path.localeCompare(right.path)),
+ };
+}
+
+/** Writes one formatted profile JSON document outside the build output. */
+export async function writeApplicationBuildProfile(
+ outputPath: string,
+ profile: ApplicationBuildProfile,
+): Promise<void> {
+ await mkdir(dirname(outputPath), { recursive: true });
+ await writeFile(outputPath, `${JSON.stringify(profile, null, 2)}\n`, "utf8");
+}
diff --git a/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts b/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts
index 541c929df..238ba8e2c 100644
--- a/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts
@@ -5,6 +5,10 @@ import type { Nitro } from "nitro/types";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createCompiledAgentManifest } from "#compiler/manifest.js";
+import {
+ APPLICATION_BUILD_PROFILE_SCHEMA_VERSION,
+ type ApplicationBuildProfile,
+} from "#internal/application/build-profile.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import type { ApplicationBuildWorkspace } from "#internal/application/build-workspace.js";
import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
@@ -233,6 +237,66 @@ describe("buildApplication", () => {
expect((summary.agent as { name: string }).name).toBe("scenario-test-agent");
});
+ it("writes a versioned timing and output-size profile outside the published output", async () => {
+ vi.stubEnv("VERCEL", "");
+ const appRoot = await createScratchDirectory("eve-build-application-profile-");
+ const profilePath = join(appRoot, ".eve", "profiles", "build.json");
+
+ prepareProductionApplicationHostMock.mockImplementationOnce(prepareHostBuildWorkspace);
+ createProductionApplicationNitroMock.mockImplementationOnce(
+ async (_preparedHost: PreparedApplicationHost, options: { outputDir: string }) =>
+ createNitroStub(options.outputDir),
+ );
+
+ const { buildApplication } = await import("#internal/nitro/host/build-application.js");
+ await buildApplication(appRoot, {
+ profileOutputPath: profilePath,
+ skipVercelSandboxPrewarm: false,
+ });
+
+ const profile = JSON.parse(await readFile(profilePath, "utf8")) as ApplicationBuildProfile;
+
+ expect(profile).toMatchObject({
+ kind: "eve-build-profile",
+ schemaVersion: APPLICATION_BUILD_PROFILE_SCHEMA_VERSION,
+ target: "local",
+ });
+ expect(profile.durationMs).toBeGreaterThanOrEqual(0);
+ expect(profile.phases).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ name: "host.prepare" }),
+ expect.objectContaining({ name: "nitro.all.bundle" }),
+ expect.objectContaining({ name: "output.publish" }),
+ expect.objectContaining({ name: "workspace.remove" }),
+ ]),
+ );
+ expect(profile.phases.every((phase) => phase.durationMs >= 0)).toBe(true);
+ expect(profile.output.files).toBeGreaterThan(0);
+ expect(profile.output.rawBytes).toBeGreaterThan(0);
+ expect(profile.output.gzipBytes).toBeGreaterThan(0);
+ expect(profile.output.functionBundles).toEqual([
+ expect.objectContaining({
+ files: 2,
+ path: "functions/__server.func",
+ }),
+ ]);
+ });
+
+ it("rejects a profile path inside the published output", async () => {
+ vi.stubEnv("VERCEL", "");
+ const appRoot = await createScratchDirectory("eve-build-application-profile-output-");
+
+ const { buildApplication } = await import("#internal/nitro/host/build-application.js");
+ await expect(
+ buildApplication(appRoot, {
+ profileOutputPath: join(appRoot, ".output", "build-profile.json"),
+ skipVercelSandboxPrewarm: false,
+ }),
+ ).rejects.toThrow("must be outside the published output directory");
+
+ expect(prepareProductionApplicationHostMock).not.toHaveBeenCalled();
+ });
+
it("keeps the last-good output when Nitro mutates its target before failing", async () => {
vi.stubEnv("VERCEL", "");
const appRoot = await createScratchDirectory("eve-build-application-last-good-");
diff --git a/packages/eve/src/internal/nitro/host/build-application.ts b/packages/eve/src/internal/nitro/host/build-application.ts
index bfc9312cf..3acd19cf8 100644
--- a/packages/eve/src/internal/nitro/host/build-application.ts
+++ b/packages/eve/src/internal/nitro/host/build-application.ts
@@ -1,5 +1,5 @@
import { readFile } from "node:fs/promises";
-import { dirname, join, resolve } from "node:path";
+import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { build as buildNitro, copyPublicAssets, prepare, prerender } from "nitro/builder";
import type { Nitro } from "nitro/types";
@@ -14,6 +14,12 @@ import {
removeApplicationBuildWorkspace,
type ApplicationBuildWorkspace,
} from "#internal/application/build-workspace.js";
+import {
+ ApplicationBuildProfiler,
+ createApplicationBuildProfile,
+ measureApplicationBuildOutput,
+ writeApplicationBuildProfile,
+} from "#internal/application/build-profile.js";
import {
publishApplicationBuildArtifacts,
RecoverablePublicationError,
@@ -40,6 +46,33 @@ function trimTrailingSlash(path: string): string {
return path.replace(/[\\/]+$/, "");
}
+async function measureBuildPhase<T>(
+ profiler: ApplicationBuildProfiler | undefined,
+ name: string,
+ operation: () => T | Promise<T>,
+): Promise<T> {
+ return profiler === undefined ? operation() : profiler.measure(name, operation);
+}
+
+function isPathInside(directoryPath: string, candidatePath: string): boolean {
+ const relativePath = relative(directoryPath, candidatePath);
+ return (
+ relativePath.length === 0 ||
+ (!relativePath.startsWith(`..${sep}`) && relativePath !== ".." && !isAbsolute(relativePath))
+ );
+}
+
+function assertProfileOutputOutsideBuildOutput(
+ profileOutputPath: string | undefined,
+ outputDirectory: string,
+): void {
+ if (profileOutputPath !== undefined && isPathInside(outputDirectory, profileOutputPath)) {
+ throw new Error(
+ `Build profile path ${profileOutputPath} must be outside the published output directory ${outputDirectory}.`,
+ );
+ }
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
@@ -275,15 +308,23 @@ async function emitVercelWorkflowFunctions(input: {
});
}
-async function buildNitroOutput(nitro: Nitro): Promise<string> {
+async function buildNitroOutput(
+ nitro: Nitro,
+ profiler: ApplicationBuildProfiler | undefined,
+ phasePrefix: string,
+): Promise<string> {
const outputDirectory = trimTrailingSlash(nitro.options.output.dir);
- await prepareEveVersionedCacheDirectory(outputDirectory);
- await prepare(nitro);
- await copyPublicAssets(nitro);
- await prerender(nitro);
- await buildNitro(nitro);
- await writeEveVersionedCacheMetadata(outputDirectory);
+ await measureBuildPhase(profiler, `${phasePrefix}.cache.prepare`, () =>
+ prepareEveVersionedCacheDirectory(outputDirectory),
+ );
+ await measureBuildPhase(profiler, `${phasePrefix}.prepare`, () => prepare(nitro));
+ await measureBuildPhase(profiler, `${phasePrefix}.public-assets`, () => copyPublicAssets(nitro));
+ await measureBuildPhase(profiler, `${phasePrefix}.prerender`, () => prerender(nitro));
+ await measureBuildPhase(profiler, `${phasePrefix}.bundle`, () => buildNitro(nitro));
+ await measureBuildPhase(profiler, `${phasePrefix}.cache.write`, () =>
+ writeEveVersionedCacheMetadata(outputDirectory),
+ );
return outputDirectory;
}
@@ -292,17 +333,21 @@ async function buildVercelNitroSurface(
preparedHost: PreparedApplicationHost,
workspace: ApplicationBuildWorkspace,
surface: Exclude<NitroBuildSurface, "all">,
+ profiler: ApplicationBuildProfiler | undefined,
): Promise<string> {
- const nitro = await createProductionApplicationNitro(preparedHost, {
- buildDir: join(workspace.nitro.buildDir, surface),
- outputDir: join(workspace.nitro.surfaceOutputDir, surface),
- surface,
- });
+ const phasePrefix = `nitro.${surface}`;
+ const nitro = await measureBuildPhase(profiler, `${phasePrefix}.create`, () =>
+ createProductionApplicationNitro(preparedHost, {
+ buildDir: join(workspace.nitro.buildDir, surface),
+ outputDir: join(workspace.nitro.surfaceOutputDir, surface),
+ surface,
+ }),
+ );
try {
- return await buildNitroOutput(nitro);
+ return await buildNitroOutput(nitro, profiler, phasePrefix);
} finally {
- await nitro.close();
+ await measureBuildPhase(profiler, `${phasePrefix}.close`, () => nitro.close());
}
}
@@ -313,129 +358,191 @@ export async function buildApplication(
rootDir: string,
options: ApplicationBuildOptions,
): Promise<string> {
+ const profileOutputPath =
+ options.profileOutputPath === undefined ? undefined : resolve(options.profileOutputPath);
+ const profiler = profileOutputPath === undefined ? undefined : new ApplicationBuildProfiler();
+
// Extension packages use `eve extension build`. Keep agent `eve build` agent-only
// so a mistaken run fails with a clear redirect instead of a half-Nitro path.
- const extensionBuild = await tryReadExtensionBuildConfig(rootDir);
+ const extensionBuild = await measureBuildPhase(profiler, "extension.check", () =>
+ tryReadExtensionBuildConfig(rootDir),
+ );
if (extensionBuild !== null) {
throw new Error(
`Package "${extensionBuild.packageName}" is an eve extension. Run \`eve extension build\` instead of \`eve build\`.`,
);
}
- const project = await resolveDiscoveryProject(rootDir);
- const workspace = await createApplicationBuildWorkspace(
- project.appRoot,
- options.vercelServiceOutput?.serviceOutputDirectory,
+ const project = await measureBuildPhase(profiler, "project.resolve", () =>
+ resolveDiscoveryProject(rootDir),
+ );
+ const workspace = await measureBuildPhase(profiler, "workspace.create", () =>
+ createApplicationBuildWorkspace(
+ project.appRoot,
+ options.vercelServiceOutput?.serviceOutputDirectory,
+ ),
);
// A recoverable publication failure leaves the lock journal pointing at
// staged artifacts inside this workspace; the next build's recovery
// consumes and then removes it. Deleting it now would strand the journal.
let preserveWorkspaceForRecovery = false;
+ let outputDirectory: string;
try {
- return await buildApplicationInWorkspace(workspace, options);
+ assertProfileOutputOutsideBuildOutput(profileOutputPath, workspace.publication.output.finalDir);
+ outputDirectory = await buildApplicationInWorkspace(workspace, options, profiler);
} catch (error) {
preserveWorkspaceForRecovery = error instanceof RecoverablePublicationError;
throw error;
} finally {
if (!preserveWorkspaceForRecovery) {
- await removeApplicationBuildWorkspace(workspace);
+ await measureBuildPhase(profiler, "workspace.remove", () =>
+ removeApplicationBuildWorkspace(workspace),
+ );
}
}
+
+ if (profiler !== undefined && profileOutputPath !== undefined) {
+ const timing = profiler.finish();
+ const output = await measureApplicationBuildOutput(outputDirectory);
+ await writeApplicationBuildProfile(
+ profileOutputPath,
+ createApplicationBuildProfile({
+ output,
+ target: process.env.VERCEL ? "vercel" : "local",
+ timing,
+ }),
+ );
+ }
+
+ return outputDirectory;
}
async function buildApplicationInWorkspace(
workspace: ApplicationBuildWorkspace,
options: ApplicationBuildOptions,
+ profiler: ApplicationBuildProfiler | undefined,
): Promise<string> {
- const preparedHost = await prepareProductionApplicationHost(workspace);
+ const preparedHost = await measureBuildPhase(profiler, "host.prepare", () =>
+ prepareProductionApplicationHost(workspace),
+ );
if (!process.env.VERCEL) {
- const nitro = await createProductionApplicationNitro(preparedHost, {
- buildDir: workspace.nitro.buildDir,
- outputDir: workspace.publication.output.stagedDir,
- surface: "all",
- });
+ const nitro = await measureBuildPhase(profiler, "nitro.all.create", () =>
+ createProductionApplicationNitro(preparedHost, {
+ buildDir: workspace.nitro.buildDir,
+ outputDir: workspace.publication.output.stagedDir,
+ surface: "all",
+ }),
+ );
try {
- await buildNitroOutput(nitro);
- await emitVercelAgentSummary({
- manifest: preparedHost.compileResult.manifest,
- outputPath: workspace.publication.summary.stagedPath,
- });
- await stageProductionCompilerArtifacts({
- compilerArtifactsRoot: workspace.compiler.artifactsDir,
- outputDir: workspace.publication.output.stagedDir,
- });
+ await buildNitroOutput(nitro, profiler, "nitro.all");
+ await measureBuildPhase(profiler, "agent-summary.emit", () =>
+ emitVercelAgentSummary({
+ manifest: preparedHost.compileResult.manifest,
+ outputPath: workspace.publication.summary.stagedPath,
+ }),
+ );
+ await measureBuildPhase(profiler, "compiler-artifacts.stage", () =>
+ stageProductionCompilerArtifacts({
+ compilerArtifactsRoot: workspace.compiler.artifactsDir,
+ outputDir: workspace.publication.output.stagedDir,
+ }),
+ );
} finally {
- await nitro.close();
+ await measureBuildPhase(profiler, "nitro.all.close", () => nitro.close());
}
- await publishCompletedApplicationBuild(workspace);
+ await measureBuildPhase(profiler, "output.publish", () =>
+ publishCompletedApplicationBuild(workspace),
+ );
return workspace.publication.output.finalDir;
}
- const servicePrefix = await resolveCoDeployedEveServicePrefixForVercelFunctionOutput(
- preparedHost.appRoot,
- preparedHost.compileResult.project.agentRoot,
+ const servicePrefix = await measureBuildPhase(profiler, "vercel.service-prefix.resolve", () =>
+ resolveCoDeployedEveServicePrefixForVercelFunctionOutput(
+ preparedHost.appRoot,
+ preparedHost.compileResult.project.agentRoot,
+ ),
+ );
+ const nitro = await measureBuildPhase(profiler, "nitro.app.create", () =>
+ createProductionApplicationNitro(preparedHost, {
+ buildDir: join(workspace.nitro.buildDir, "app"),
+ outputDir: workspace.publication.output.stagedDir,
+ surface: "app",
+ }),
);
- const nitro = await createProductionApplicationNitro(preparedHost, {
- buildDir: join(workspace.nitro.buildDir, "app"),
- outputDir: workspace.publication.output.stagedDir,
- surface: "app",
- });
try {
- await buildNitroOutput(nitro);
+ await buildNitroOutput(nitro, profiler, "nitro.app");
// Run sandbox prewarm before emitting the workflow functions so a
// prewarm failure aborts the build before we spend time bundling
// function output that we would never deploy.
if (!options.skipVercelSandboxPrewarm) {
- await runVercelBuildPrewarm({
- appRoot: preparedHost.appRoot,
- compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(
- workspace.compiler.rootDir,
- {
- moduleMapLoaderPath: resolvePackageSourceFilePath(
- "src/internal/authored-module-map-loader.ts",
- ),
- sandboxAppRoot: preparedHost.appRoot,
+ await measureBuildPhase(profiler, "sandbox.prewarm", () =>
+ runVercelBuildPrewarm({
+ appRoot: preparedHost.appRoot,
+ compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(
+ workspace.compiler.rootDir,
+ {
+ moduleMapLoaderPath: resolvePackageSourceFilePath(
+ "src/internal/authored-module-map-loader.ts",
+ ),
+ sandboxAppRoot: preparedHost.appRoot,
+ },
+ ),
+ log(message) {
+ console.log(message);
},
- ),
- log(message) {
- console.log(message);
- },
- });
+ }),
+ );
}
- const flowNitroOutputDir = await buildVercelNitroSurface(preparedHost, workspace, "flow");
- await emitVercelWorkflowFunctions({
- agentName: preparedHost.compileResult.manifest.config.name,
- appRoot: preparedHost.appRoot,
- compiledArtifactsBootstrapPath: preparedHost.compiledArtifacts.bootstrapPath,
- flowNitroOutputDir,
- outputDir: workspace.publication.output.stagedDir,
- workflowBuildDir: workspace.workflow.buildDir,
- });
+ const flowNitroOutputDir = await buildVercelNitroSurface(
+ preparedHost,
+ workspace,
+ "flow",
+ profiler,
+ );
+ await measureBuildPhase(profiler, "workflow.emit", () =>
+ emitVercelWorkflowFunctions({
+ agentName: preparedHost.compileResult.manifest.config.name,
+ appRoot: preparedHost.appRoot,
+ compiledArtifactsBootstrapPath: preparedHost.compiledArtifacts.bootstrapPath,
+ flowNitroOutputDir,
+ outputDir: workspace.publication.output.stagedDir,
+ workflowBuildDir: workspace.workflow.buildDir,
+ }),
+ );
if (servicePrefix !== undefined) {
- await normalizeEveVercelFunctionOutput(workspace.publication.output.stagedDir, {
- servicePrefix,
- });
+ await measureBuildPhase(profiler, "vercel.functions.normalize", () =>
+ normalizeEveVercelFunctionOutput(workspace.publication.output.stagedDir, {
+ servicePrefix,
+ }),
+ );
}
- if (options.vercelServiceOutput !== undefined) {
- await copyHostMiddlewareFunctions({
- hostOutputDirectory: options.vercelServiceOutput.hostOutputDirectory,
- serviceOutputDirectory: workspace.publication.output.stagedDir,
- });
+ const vercelServiceOutput = options.vercelServiceOutput;
+ if (vercelServiceOutput !== undefined) {
+ await measureBuildPhase(profiler, "vercel.host-middleware.copy", () =>
+ copyHostMiddlewareFunctions({
+ hostOutputDirectory: vercelServiceOutput.hostOutputDirectory,
+ serviceOutputDirectory: workspace.publication.output.stagedDir,
+ }),
+ );
}
- await emitVercelAgentSummary({
- manifest: preparedHost.compileResult.manifest,
- outputPath: workspace.publication.summary.stagedPath,
- });
+ await measureBuildPhase(profiler, "agent-summary.emit", () =>
+ emitVercelAgentSummary({
+ manifest: preparedHost.compileResult.manifest,
+ outputPath: workspace.publication.summary.stagedPath,
+ }),
+ );
} finally {
- await nitro.close();
+ await measureBuildPhase(profiler, "nitro.app.close", () => nitro.close());
}
- await publishCompletedApplicationBuild(workspace);
+ await measureBuildPhase(profiler, "output.publish", () =>
+ publishCompletedApplicationBuild(workspace),
+ );
return workspace.publication.output.finalDir;
}
diff --git a/packages/eve/src/internal/nitro/host/types.ts b/packages/eve/src/internal/nitro/host/types.ts
index feadd80e4..50b57a0d1 100644
--- a/packages/eve/src/internal/nitro/host/types.ts
+++ b/packages/eve/src/internal/nitro/host/types.ts
@@ -13,6 +13,8 @@ export type NitroBuildSurface = "all" | "app" | "flow";
/** Options for one production application build. */
export interface ApplicationBuildOptions {
+ /** Absolute path for an optional machine-readable profile of a successful build. */
+ readonly profileOutputPath?: string;
readonly skipVercelSandboxPrewarm: boolean;
readonly vercelServiceOutput?: {
readonly hostOutputDirectory: string;