The Open Framework for Building Agents
fix(eve): fail the hosted build when the output lacks a configured external (#3603)
roboeve[bot]5666d2f0d8b7
diff --git a/.changeset/external-dependency-app-resolution.md b/.changeset/external-dependency-app-resolution.mdnew file mode 100644index 000000000..5b00136fa--- /dev/null+++ b/.changeset/external-dependency-app-resolution.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Hosted builds now fail with a clear error when the build output imports a `build.externalDependencies` package, or a subpath of one, that Node's ESM resolver does not resolve to a file inside the output. Previously the build succeeded and the deployed function crashed at boot with `ERR_MODULE_NOT_FOUND` (for example when only a workspace package installed the dependency) or `ERR_PACKAGE_PATH_NOT_EXPORTED` (when the copied version does not export the imported subpath). The error names the import and the app `package.json` to add the package to.diff --git a/packages/eve/src/internal/authored-package-boundary.ts b/packages/eve/src/internal/authored-package-boundary.tsindex da819ffd9..198a696a8 100644--- a/packages/eve/src/internal/authored-package-boundary.ts+++ b/packages/eve/src/internal/authored-package-boundary.ts@@ -312,7 +312,8 @@ export function normalizeExternalDependencies(return [...new Set(externalDependencies)].sort();}-function resolveConfiguredExternalDependency(+/** Returns the configured external that `source` imports (the entry itself or one of its subpaths). */+export function resolveConfiguredExternalDependency(source: string,externalDependencies: readonly string[],): string | undefined {@@ -321,7 +322,8 @@ function resolveConfiguredExternalDependency();}-function packageImportName(source: string): string {+/** Returns the package part of a bare specifier: `@acme/db/x` → `@acme/db`, `pg/native` → `pg`. */+export function packageImportName(source: string): string {return source.startsWith("@") ? source.split("/", 2).join("/") : source.split("/", 1)[0]!;}diff --git a/packages/eve/src/internal/bundler/nitro-rolldown.ts b/packages/eve/src/internal/bundler/nitro-rolldown.tsindex ecf9a10f8..a1bc59a42 100644--- a/packages/eve/src/internal/bundler/nitro-rolldown.ts+++ b/packages/eve/src/internal/bundler/nitro-rolldown.ts@@ -6,7 +6,7 @@ import {onVendoredDependencyLog,} from "#internal/bundler/vendored-dependency-log.js";-type RolldownOutputChunk = {+export type RolldownOutputChunk = {readonly type: "chunk";readonly code: string;readonly fileName: string;@@ -14,7 +14,7 @@ type RolldownOutputChunk = {readonly dynamicImports: readonly string[];};-type RolldownOutputAsset = {+export type RolldownOutputAsset = {readonly type: "asset";readonly fileName: string;readonly source: string | Uint8Array;diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.tsindex 4e5a187e4..eb0fe6169 100644--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts@@ -37,6 +37,7 @@ import {configureProductionNitroRoutes,} from "#internal/nitro/host/configure-nitro-routes.js";import { applyEveCronHandlerRoute } from "#internal/nitro/host/cron-handler-route.js";+import { createExternalDependencyOutputCheckPlugin } from "#internal/nitro/host/external-dependency-output-check-plugin.js";import { createNitroBundlerConfig } from "#internal/nitro/host/nitro-bundler-config.js";import {createOptionalEngineDependencyPlugin,@@ -112,14 +113,9 @@ function collectHostedTraceDependencies(const extensionExternalDependencies = new Set(collectExtensionExternalDependencies(preparedHost.compileResult.manifest),);- const configuredExternalDependencies = [- ...(preparedHost.compileResult.manifest.config.build?.externalDependencies ?? []),- ...preparedHost.compileResult.manifest.subagents.flatMap((subagent) =>- subagent.configResolver === undefined- ? (subagent.agent.config.build?.externalDependencies ?? [])- : (subagent.configResolver.build?.externalDependencies ?? []),- ),- ];+ const configuredExternalDependencies = collectConfiguredExternalDependencies(+ preparedHost.compileResult.manifest,+ );// Nitro already classifies known native and non-bundleable packages through// its nf3 database. traceDeps is only for eve-owned or author-configured// additions to that upstream policy.@@ -140,6 +136,17 @@ function collectHostedTraceDependencies();}+function collectConfiguredExternalDependencies(manifest: CompiledAgentManifest): string[] {+ return [+ ...(manifest.config.build?.externalDependencies ?? []),+ ...manifest.subagents.flatMap((subagent) =>+ subagent.configResolver === undefined+ ? (subagent.agent.config.build?.externalDependencies ?? [])+ : (subagent.configResolver.build?.externalDependencies ?? []),+ ),+ ];+}+function collectExtensionExternalDependencies(manifest: CompiledAgentManifest): string[] {return [manifest, ...manifest.subagents.map((subagent) => subagent.agent)].flatMap((node) =>node.extensionMounts.flatMap((mount) => mount.externalDependencies),@@ -610,6 +617,14 @@ function createApplicationNitroBundlerConfiguration(compiledSandboxProviderPrunePlugin,createOptionalEngineDependencyPlugin(unconfiguredOptionalEnginePackages),createExtensionExternalDependencyPlugin(extensionMounts),+ options.development+ ? null+ : createExternalDependencyOutputCheckPlugin({+ appRoot: preparedHost.appRoot,+ externalDependencies: collectConfiguredExternalDependencies(+ preparedHost.compileResult.manifest,+ ),+ }),createExtensionMountPlugin(extensionMounts,extensionOverridePaths(preparedHost.compileResult.manifest),diff --git a/packages/eve/src/internal/nitro/host/external-dependency-output-check-plugin.integration.test.ts b/packages/eve/src/internal/nitro/host/external-dependency-output-check-plugin.integration.test.tsnew file mode 100644index 000000000..258d23709--- /dev/null+++ b/packages/eve/src/internal/nitro/host/external-dependency-output-check-plugin.integration.test.ts@@ -0,0 +1,162 @@+import { mkdir, readdir, symlink, writeFile } from "node:fs/promises";+import { join } from "node:path";++import { describe, expect, it } from "vitest";++import { createExternalDependencyOutputCheckPlugin } from "#internal/nitro/host/external-dependency-output-check-plugin.js";+import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";++const createDirectory = useTemporaryDirectories();++const APP_ROOT = join("/app");++// A `pg` install whose exports include `./lib/client` only when `withClient`.+async function writePackage(packageDir: string, input: { readonly withClient: boolean }) {+ await mkdir(join(packageDir, "lib"), { recursive: true });+ await writeFile(join(packageDir, "index.js"), "export default {};\n");+ await writeFile(join(packageDir, "lib", "client.js"), "export default {};\n");+ const exports = input.withClient+ ? { ".": "./index.js", "./lib/client": "./lib/client.js" }+ : { ".": "./index.js" };+ await writeFile(join(packageDir, "package.json"), JSON.stringify({ exports, name: "pg" }));+}++async function checkOutput(input: {+ readonly installAt: "server" | "above" | "linked" | "nowhere";+ readonly withClient?: boolean;+}) {+ const root = await createDirectory("eve-external-output-check-");+ const serverDir = join(root, "server");+ await mkdir(join(serverDir, "_chunks"), { recursive: true });+ const withClient = input.withClient ?? true;+ if (input.installAt === "server") {+ await writePackage(join(serverDir, "node_modules", "pg"), { withClient });+ }+ if (input.installAt === "above") {+ await writePackage(join(root, "node_modules", "pg"), { withClient });+ }+ if (input.installAt === "linked") {+ // pnpm's layout: the output's node_modules entry links to a store+ // outside it (on Windows, possibly another drive).+ await writePackage(join(root, "store", "pg"), { withClient });+ await mkdir(join(serverDir, "node_modules"), { recursive: true });+ await symlink(join(root, "store", "pg"), join(serverDir, "node_modules", "pg"), "junction");+ }++ const plugin = createExternalDependencyOutputCheckPlugin({+ appRoot: APP_ROOT,+ externalDependencies: ["pg"],+ });+ await plugin?.writeBundle(+ { dir: serverDir },+ {+ "_chunks/db.mjs": {+ code: "",+ dynamicImports: [],+ fileName: "_chunks/db.mjs",+ imports: ["pg/lib/client"],+ type: "chunk",+ },+ "index.mjs": {+ code: "",+ dynamicImports: ["pg"],+ fileName: "index.mjs",+ imports: ["_chunks/db.mjs", "zod"],+ type: "chunk",+ },+ },+ );+}++// Installs `pg` in the output from `files` (path -> contents, `package.json`+// included) and checks a chunk that imports bare `pg`. Returns the output's+// remaining file list, so tests can assert the probes are cleaned up.+async function checkInstalledPackage(files: Readonly<Record<string, string>>) {+ const serverDir = join(await createDirectory("eve-external-output-check-"), "server");+ const packageDir = join(serverDir, "node_modules", "pg");+ await mkdir(packageDir, { recursive: true });+ for (const [path, contents] of Object.entries(files)) {+ await writeFile(join(packageDir, path), contents);+ }+ await createExternalDependencyOutputCheckPlugin({+ appRoot: APP_ROOT,+ externalDependencies: ["pg"],+ })?.writeBundle(+ { dir: serverDir },+ {+ "index.mjs": {+ code: "",+ dynamicImports: [],+ fileName: "index.mjs",+ imports: ["pg"],+ type: "chunk",+ },+ },+ );+ return readdir(serverDir, { recursive: true });+}++const missing = (specifier: string, chunk: string) =>+ `"${specifier}" is listed in build.externalDependencies and imported by the hosted bundle (${chunk}), but the build output cannot resolve it. Add "pg" to the dependencies in ${join(APP_ROOT, "package.json")}.`;++describe("external dependency output check", () => {+ it("accepts a configured external the output resolves", async () => {+ await expect(checkOutput({ installAt: "server" })).resolves.toBeUndefined();+ });++ it("rejects a configured external the output does not contain", async () => {+ await expect(checkOutput({ installAt: "nowhere" })).rejects.toThrow(+ missing("pg/lib/client", "_chunks/db.mjs"),+ );+ });++ it("rejects a package that only resolves from above the output", async () => {+ await expect(checkOutput({ installAt: "above" })).rejects.toThrow(+ missing("pg/lib/client", "_chunks/db.mjs"),+ );+ });++ it("rejects a package linked into the output from outside it", async () => {+ await expect(checkOutput({ installAt: "linked" })).rejects.toThrow(+ missing("pg/lib/client", "_chunks/db.mjs"),+ );+ });++ it("rejects an imported subpath the packaged version does not export", async () => {+ await expect(checkOutput({ installAt: "server", withClient: false })).rejects.toThrow(+ missing("pg/lib/client", "_chunks/db.mjs"),+ );+ });++ it("rejects a legacy main that only resolves by adding an extension Node does not try", async () => {+ await expect(+ checkInstalledPackage({+ "index.mjs": "export default {};\n",+ "package.json": JSON.stringify({ main: "./index", name: "pg" }),+ }),+ ).rejects.toThrow(missing("pg", "index.mjs"));+ });++ it("accepts a legacy main that names its file", async () => {+ await expect(+ checkInstalledPackage({+ "index.mjs": "export default {};\n",+ "package.json": JSON.stringify({ main: "./index.mjs", name: "pg" }),+ }),+ ).resolves.not.toContainEqual(expect.stringContaining(".eve-resolve-"));+ });++ it("rejects an exports target the output does not contain", async () => {+ await expect(+ checkInstalledPackage({+ "package.json": JSON.stringify({ exports: "./index.js", name: "pg" }),+ }),+ ).rejects.toThrow(missing("pg", "index.mjs"));+ });++ it("does nothing when no externals are configured", () => {+ expect(+ createExternalDependencyOutputCheckPlugin({ appRoot: APP_ROOT, externalDependencies: [] }),+ ).toBeNull();+ });+});diff --git a/packages/eve/src/internal/nitro/host/external-dependency-output-check-plugin.ts b/packages/eve/src/internal/nitro/host/external-dependency-output-check-plugin.tsnew file mode 100644index 000000000..36258a269--- /dev/null+++ b/packages/eve/src/internal/nitro/host/external-dependency-output-check-plugin.ts@@ -0,0 +1,143 @@+import { execFile } from "node:child_process";+import { randomUUID } from "node:crypto";+import { realpathSync, statSync } from "node:fs";+import { rm, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { promisify } from "node:util";++import {+ packageImportName,+ resolveConfiguredExternalDependency,+} from "#internal/authored-package-boundary.js";+import type { RolldownOutputAsset, RolldownOutputChunk } from "#internal/bundler/nitro-rolldown.js";+import { isPathInsideOrEqual } from "#internal/nitro/dev-runtime-source-snapshot-local-roots.js";++interface ExternalDependencyOutputCheckPlugin {+ readonly name: string;+ writeBundle(+ outputOptions: { readonly dir: string },+ bundle: Readonly<Record<string, RolldownOutputChunk | RolldownOutputAsset>>,+ ): Promise<void>;+}++interface ExternalImport {+ readonly chunk: string;+ readonly probe: string;+ readonly specifier: string;+}++/** Placed beside a chunk, so `import.meta.resolve` resolves exactly as that chunk's imports do. */+const PROBE_SOURCE = "export const resolve = (specifier) => import.meta.resolve(specifier);\n";++/**+ * Fails the hosted build when a written chunk imports (statically or by a+ * literal dynamic import) a configured external that Node does not resolve,+ * from that chunk, to a file inside the output. Nitro's tracer only warns+ * when it cannot find a package to copy, so without this check the build+ * succeeds and the deployed function fails with ERR_MODULE_NOT_FOUND (or+ * ERR_PACKAGE_PATH_NOT_EXPORTED when it copied a different version).+ *+ * Resolution is Node's own ESM resolver, run by the build's Node in a child+ * process; no dependency code is loaded.+ */+export function createExternalDependencyOutputCheckPlugin(input: {+ readonly appRoot: string;+ readonly externalDependencies: readonly string[];+}): ExternalDependencyOutputCheckPlugin | null {+ if (input.externalDependencies.length === 0) {+ return null;+ }++ return {+ name: "eve-external-dependency-output-check",+ async writeBundle(outputOptions, bundle) {+ const outputDir = realpathSync(outputOptions.dir);+ const probeName = `.eve-resolve-${randomUUID()}.mjs`;+ const externalImports: ExternalImport[] = [];+ for (const output of Object.values(bundle)) {+ if (output.type !== "chunk") {+ continue;+ }+ const probe = join(dirname(join(outputDir, output.fileName)), probeName);+ for (const specifier of [...output.imports, ...output.dynamicImports]) {+ if (+ resolveConfiguredExternalDependency(specifier, input.externalDependencies) !== undefined+ ) {+ externalImports.push({ chunk: output.fileName, probe, specifier });+ }+ }+ }+ if (externalImports.length === 0) {+ return;+ }++ const resolved = await resolveWithNode(outputDir, probeName, externalImports);+ externalImports.forEach(({ chunk, specifier }, index) => {+ const url = resolved[index];+ const path = url?.startsWith("file:") === true ? fileURLToPath(url) : undefined;+ if (+ path === undefined ||+ statSync(path, { throwIfNoEntry: false })?.isFile() !== true ||+ !isPathInsideOrEqual(path, outputDir)+ ) {+ throw new Error(+ `"${specifier}" is listed in build.externalDependencies and imported by the hosted bundle (${chunk}), but the build output cannot resolve it. Add "${packageImportName(specifier)}" to the dependencies in ${join(input.appRoot, "package.json")}.`,+ );+ }+ });+ },+ };+}++/**+ * Returns, for each import, the URL Node's ESM resolver selects from beside+ * its chunk, or null when resolution throws. `import.meta.resolve` returns an+ * `exports` target's URL even when that file is missing, so callers must+ * check the file exists.+ */+async function resolveWithNode(+ outputDir: string,+ probeName: string,+ externalImports: readonly ExternalImport[],+): Promise<readonly (string | null)[]> {+ const probes = [...new Set(externalImports.map(({ probe }) => probe))];+ const driver = join(outputDir, probeName.replace(/\.mjs$/, "-driver.mjs"));+ const requests = externalImports.map(({ probe, specifier }) => ({+ probe: pathToFileURL(probe).href,+ specifier,+ }));+ try {+ await Promise.all(probes.map((probe) => writeFile(probe, PROBE_SOURCE)));+ await writeFile(+ driver,+ [+ `const results = [];`,+ `for (const { probe, specifier } of ${JSON.stringify(requests)}) {`,+ ` const { resolve } = await import(probe);`,+ ` try { results.push(resolve(specifier)); } catch { results.push(null); }`,+ `}`,+ `process.stdout.write(JSON.stringify(results));`,+ ``,+ ].join("\n"),+ );+ const { NODE_OPTIONS: _nodeOptions, ...env } = process.env;+ let stdout: string;+ try {+ ({ stdout } = await promisify(execFile)(process.execPath, [driver], {+ cwd: outputDir,+ env,+ maxBuffer: 10 * 1024 * 1024,+ }));+ } catch (error) {+ // execFile's message carries the child's stderr.+ throw new Error(+ `Cannot check build.externalDependencies in the hosted output: ${error instanceof Error ? error.message : String(error)}`,+ { cause: error },+ );+ }+ return JSON.parse(stdout) as (string | null)[];+ } finally {+ await Promise.all([driver, ...probes].map((path) => rm(path, { force: true })));+ }+}diff --git a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.tsindex b8a2728ca..81b21b493 100644--- a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts+++ b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts@@ -1,6 +1,7 @@+import { spawnSync } from "node:child_process";import { existsSync } from "node:fs";-import { mkdir, readdir, readFile, symlink, writeFile } from "node:fs/promises";-import { join } from "node:path";+import { cp, mkdir, readdir, readFile, realpath, symlink, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";import { pathToFileURL } from "node:url";import { afterEach, describe, expect, it, vi } from "vitest";@@ -9,6 +10,7 @@ import {resolveInstalledPackageInfo,resolvePackageRoot,} from "../../src/internal/application/package.js";+import { compileAgent } from "../../src/compiler/compile-agent.js";import { buildApplication } from "../../src/internal/nitro/host.js";import { useTemporaryDirectories } from "../../src/internal/testing/use-temporary-app-roots.js";@@ -66,6 +68,248 @@ async function readTracedServerPackageJson(outputDir: string): Promise<{}}+/**+ * Writes an isolated (pnpm-style, nothing hoisted) workspace: `apps/agent`+ * depends on the `packages/backend` source package, which installs+ * `fixture-workspace-external` in its own node_modules. The agent marks it+ * external; with `appDeclaresExternal` the app installs it too.+ */+async function writeWorkspaceExternalFixture(input: {+ readonly appDeclaresExternal: boolean;+ readonly dynamicImport?: boolean;+ /** The workspace package imports `fixture-workspace-external/extra`, which only v2 exports. */+ readonly subpathImport?: boolean;+ /** Every installation's `.` export selects by this condition first; see `writeExternalInstallation`. */+ readonly exportCondition?: ExportCondition;+}): Promise<{ readonly appRoot: string }> {+ const version = input.subpathImport === true ? "2.0.0" : "1.0.0";+ const workspaceRoot = await createScratchDirectory("eve-workspace-external-dep-build-");+ const appRoot = join(workspaceRoot, "apps", "agent");+ const packageRoot = join(workspaceRoot, "packages", "backend");++ await mkdir(join(appRoot, "agent", "tools"), { recursive: true });+ await mkdir(join(appRoot, "node_modules", "@fixture"), { recursive: true });+ await mkdir(join(packageRoot, "src"), { recursive: true });+ const appDependencies: Record<string, string> = { "@fixture/backend": "workspace:*" };+ if (input.appDeclaresExternal) {+ appDependencies["fixture-workspace-external"] = version;+ await writeExternalInstallation(+ join(appRoot, "node_modules", "fixture-workspace-external"),+ version,+ input.exportCondition,+ );+ }+ await writeFile(+ join(appRoot, "package.json"),+ `${JSON.stringify(+ {+ dependencies: appDependencies,+ name: "workspace-external-dependency-app",+ private: true,+ type: "module",+ },+ null,+ 2,+ )}\n`,+ );+ await writeFile(+ join(appRoot, "agent", "agent.ts"),+ [+ "export default {",+ " build: {",+ ' externalDependencies: ["fixture-workspace-external"],',+ " },",+ ' model: "openai/gpt-5.4-mini",',+ "};",+ "",+ ].join("\n"),+ );+ await writeFile(join(appRoot, "agent", "instructions.md"), "Workspace external dependency.\n");+ await writeFile(+ join(appRoot, "agent", "tools", "use_backend.ts"),+ [+ 'import { value } from "@fixture/backend";',+ "",+ "export default {",+ ' description: "Use a workspace package.",',+ " execute() {",+ " return value;",+ " },",+ "};",+ "",+ ].join("\n"),+ );++ await writeFile(+ join(packageRoot, "package.json"),+ `${JSON.stringify(+ {+ dependencies: { "fixture-workspace-external": version },+ exports: "./src/index.ts",+ name: "@fixture/backend",+ private: true,+ type: "module",+ },+ null,+ 2,+ )}\n`,+ );+ await writeFile(+ join(packageRoot, "src", "index.ts"),+ input.dynamicImport === true+ ? 'export const value = async () => (await import("fixture-workspace-external")).value;\n'+ : input.subpathImport === true+ ? 'export { value } from "fixture-workspace-external/extra";\n'+ : 'export { value } from "fixture-workspace-external";\n',+ );+ await writeExternalInstallation(+ join(packageRoot, "node_modules", "fixture-workspace-external"),+ version,+ input.exportCondition,+ );+ await symlink(packageRoot, join(appRoot, "node_modules", "@fixture", "backend"), "dir");++ return { appRoot };+}++type ExportCondition = "node" | "node-addons";++/**+ * v1 exports only `.`; v2 also exports `./extra`. With `exportCondition`, `.`+ * selects `./<condition>.js` under that condition before `import`.+ */+async function writeExternalInstallation(+ externalRoot: string,+ version: "1.0.0" | "2.0.0" = "1.0.0",+ exportCondition?: ExportCondition,+): Promise<void> {+ await mkdir(externalRoot, { recursive: true });+ const rootExport =+ exportCondition === undefined+ ? "./index.js"+ : { [exportCondition]: `./${exportCondition}.js`, import: "./index.js" };+ await writeFile(+ join(externalRoot, "package.json"),+ `${JSON.stringify(+ {+ exports: version === "1.0.0" ? rootExport : { ".": rootExport, "./extra": "./extra.js" },+ name: "fixture-workspace-external",+ type: "module",+ version,+ },+ null,+ 2,+ )}\n`,+ );+ await writeFile(join(externalRoot, "index.js"), 'export const value = "workspace external";\n');+ if (version === "2.0.0") {+ await writeFile(join(externalRoot, "extra.js"), 'export const value = "workspace extra";\n');+ }+ if (exportCondition !== undefined) {+ await writeFile(+ join(externalRoot, `${exportCondition}.js`),+ `export const value = "workspace external (${exportCondition})";\n`,+ );+ }+}++/**+ * Mounts `@fixture/ext`, an installed extension that declares+ * `fixture-workspace-external` and installs its own v1 copy. With+ * `exportsPackageJson`, Nitro can locate the extension's package and copies+ * that v1 copy into the output.+ */+async function writeMountedExtensionDeclaringExternal(+ appRoot: string,+ input: { readonly exportsPackageJson: boolean },+): Promise<void> {+ const appPackagePath = join(appRoot, "package.json");+ const appPackage = JSON.parse(await readFile(appPackagePath, "utf8")) as {+ dependencies: Record<string, string>;+ };+ appPackage.dependencies["@fixture/ext"] = "1.0.0";+ await writeFile(appPackagePath, `${JSON.stringify(appPackage, null, 2)}\n`);+ const extensionRoot = join(appRoot, "node_modules", "@fixture", "ext");+ await mkdir(join(extensionRoot, "dist", "extension"), { recursive: true });+ await writeFile(+ join(extensionRoot, "package.json"),+ `${JSON.stringify(+ {+ dependencies: { "fixture-workspace-external": "1.0.0" },+ eve: { extension: { dist: "dist/extension", source: "extension" } },+ exports: input.exportsPackageJson+ ? { ".": "./index.js", "./package.json": "./package.json" }+ : "./index.js",+ name: "@fixture/ext",+ type: "module",+ version: "1.0.0",+ },+ null,+ 2,+ )}\n`,+ );+ await writeFile(join(extensionRoot, "index.js"), 'export default { name: "fx" };\n');+ await writeFile(+ join(extensionRoot, "dist", "extension", "_manifest.json"),+ `${JSON.stringify({+ build: { externalDependencies: ["fixture-workspace-external"] },+ builtWithEve: "0.0.0",+ formatVersion: 2,+ kind: "eve-extension",+ requires: {},+ })}\n`,+ );+ await writeExternalInstallation(+ join(extensionRoot, "node_modules", "fixture-workspace-external"),+ );+ await mkdir(join(appRoot, "agent", "extensions"), { recursive: true });+ await writeFile(+ join(appRoot, "agent", "extensions", "fx.ts"),+ 'export { default } from "@fixture/ext";\n',+ );+}++/**+ * Copies the build output away from the workspace, so no source installation+ * is reachable, then imports the external in Node by its bare specifier from+ * beside the chunk that imports it, exactly as the bundled module does.+ */+async function importRelocatedWorkspaceExternal(+ outputDir: string,+ specifier = "fixture-workspace-external",+): Promise<unknown> {+ const relocatedRoot = await createScratchDirectory("eve-workspace-external-relocated-");+ await cp(outputDir, relocatedRoot, { recursive: true });+ const serverDirectory = await realpath(join(relocatedRoot, "server"));+ const entries = await readdir(serverDirectory, { recursive: true, withFileTypes: true });+ const importers = (+ await Promise.all(+ entries+ .filter((entry) => entry.isFile() && entry.name.endsWith(".mjs"))+ .filter((entry) => !join(entry.parentPath, entry.name).includes("/node_modules/"))+ .map(async (entry) => {+ const path = join(entry.parentPath, entry.name);+ // An import statement or a literal dynamic import, not a mention in the embedded manifest.+ const code = await readFile(path, "utf8");+ return code.includes(`from "${specifier}"`) || code.includes(`import("${specifier}")`)+ ? path+ : null;+ }),+ )+ ).filter((path) => path !== null);+ expect(importers).not.toHaveLength(0);+ const probePath = join(dirname(importers[0]!), "relocated-external-probe.mjs");+ await writeFile(+ probePath,+ `import { value } from ${JSON.stringify(specifier)};\nprocess.stdout.write(JSON.stringify(value));\n`,+ );+ const probe = spawnSync(process.execPath, [probePath], { cwd: relocatedRoot, encoding: "utf8" });+ if (probe.status !== 0) {+ throw new Error(probe.stderr);+ }+ return JSON.parse(probe.stdout) as unknown;+}+describe("app runtime dependency tracing", () => {afterEach(() => {delete (globalThis as Record<string, unknown>).__fixtureInstrumentationDep;@@ -741,6 +985,127 @@ describe("app runtime dependency tracing", () => {}}, 30_000);+ it("fails the build when the app cannot resolve an external a workspace package imports", async () => {+ // Hosted output resolves externals from the app. Building this fixture+ // used to succeed and then fail at boot with ERR_MODULE_NOT_FOUND.+ const { appRoot } = await writeWorkspaceExternalFixture({ appDeclaresExternal: false });++ const build = buildApplication(appRoot, DEPLOYABLE_BUILD_OPTIONS);++ await expect(build).rejects.toThrow(+ /"fixture-workspace-external" is listed in build\.externalDependencies and imported by the hosted bundle \(.+\), but the build output cannot resolve it\./,+ );+ await expect(build).rejects.toThrow(+ /Add "fixture-workspace-external" to the dependencies in \S*\/apps\/agent\/package\.json\./,+ );+ }, 60_000);++ it("fails the build when a literal dynamic import needs an external the output lacks", async () => {+ const { appRoot } = await writeWorkspaceExternalFixture({+ appDeclaresExternal: false,+ dynamicImport: true,+ });++ await expect(buildApplication(appRoot, DEPLOYABLE_BUILD_OPTIONS)).rejects.toThrow(+ /"fixture-workspace-external" is listed in build\.externalDependencies and imported by the hosted bundle \(.+\), but the build output cannot resolve it\./,+ );+ }, 60_000);++ it("ships a workspace package's external once the app declares it", async () => {+ const { appRoot } = await writeWorkspaceExternalFixture({ appDeclaresExternal: true });++ const outputDir = await buildApplication(appRoot, DEPLOYABLE_BUILD_OPTIONS);++ await expect(importRelocatedWorkspaceExternal(outputDir)).resolves.toBe("workspace external");+ }, 60_000);++ it("fails the build when only a mounted extension declares the missing external", async () => {+ // A mounted extension declares the external and installs its own copy,+ // but nothing makes Nitro's tracer copy it. This used to build and then+ // fail to resolve from the relocated output.+ const { appRoot } = await writeWorkspaceExternalFixture({ appDeclaresExternal: false });+ await writeMountedExtensionDeclaringExternal(appRoot, { exportsPackageJson: false });+ await mkdir(join(appRoot, "agent", "instrumentation"), { recursive: true });+ await writeFile(+ join(appRoot, "agent", "instrumentation", "provider.ts"),+ [+ 'import { value } from "@fixture/backend";',+ "",+ "export default {",+ " setup() {",+ " (globalThis as Record<string, unknown>).__workspaceExternal = value;",+ " },",+ "};",+ "",+ ].join("\n"),+ );++ const compiled = await compileAgent({ startPath: join(appRoot, "agent") });+ expect(compiled.manifest.extensionMounts.map((mount) => mount.externalDependencies)).toEqual([+ ["fixture-workspace-external"],+ ]);++ await expect(buildApplication(appRoot, DEPLOYABLE_BUILD_OPTIONS)).rejects.toThrow(+ /"fixture-workspace-external" is listed in build\.externalDependencies and imported by the hosted bundle \(.+\), but the build output cannot resolve it\./,+ );+ }, 60_000);++ it("fails the build when the packaged version does not export the imported subpath", async () => {+ // The workspace package imports a v2-only subpath; the mounted extension's+ // v1 copy is what Nitro packages. This used to build and then fail at boot+ // with ERR_PACKAGE_PATH_NOT_EXPORTED.+ const { appRoot } = await writeWorkspaceExternalFixture({+ appDeclaresExternal: false,+ subpathImport: true,+ });+ await writeMountedExtensionDeclaringExternal(appRoot, { exportsPackageJson: true });++ await expect(buildApplication(appRoot, DEPLOYABLE_BUILD_OPTIONS)).rejects.toThrow(+ /"fixture-workspace-external\/extra" is listed in build\.externalDependencies and imported by the hosted bundle \(.+\), but the build output cannot resolve it\./,+ );+ }, 60_000);++ it("ships the imported subpath once the app declares the version that exports it", async () => {+ const { appRoot } = await writeWorkspaceExternalFixture({+ appDeclaresExternal: true,+ subpathImport: true,+ });+ await writeMountedExtensionDeclaringExternal(appRoot, { exportsPackageJson: true });++ const outputDir = await buildApplication(appRoot, DEPLOYABLE_BUILD_OPTIONS);++ await expect(+ importRelocatedWorkspaceExternal(outputDir, "fixture-workspace-external/extra"),+ ).resolves.toBe("workspace extra");+ }, 60_000);++ it("fails the build when Node selects a conditional export the output lacks", async () => {+ // Node's ESM loader selects `node-addons` by default; Nitro's tracer+ // copies only the `import` target. This used to build and then fail at+ // boot with ERR_MODULE_NOT_FOUND.+ const { appRoot } = await writeWorkspaceExternalFixture({+ appDeclaresExternal: true,+ exportCondition: "node-addons",+ });++ await expect(buildApplication(appRoot, DEPLOYABLE_BUILD_OPTIONS)).rejects.toThrow(+ /"fixture-workspace-external" is listed in build\.externalDependencies and imported by the hosted bundle \(.+\), but the build output cannot resolve it\./,+ );+ }, 60_000);++ it("ships the conditional export Node selects when the output contains it", async () => {+ const { appRoot } = await writeWorkspaceExternalFixture({+ appDeclaresExternal: true,+ exportCondition: "node",+ });++ const outputDir = await buildApplication(appRoot, DEPLOYABLE_BUILD_OPTIONS);++ await expect(importRelocatedWorkspaceExternal(outputDir)).resolves.toBe(+ "workspace external (node)",+ );+ }, 60_000);+it("rewrites framework tool executors into hosted Vercel output", async () => {vi.stubEnv("VERCEL", "1");vi.stubEnv("VERCEL_DEPLOYMENT_ID", "");