The Open Framework for Building Agents
fix(eve): build - bound authored module resolver probes (#1132)
Andrew Barba4803dbef8c69
diff --git a/.changeset/quick-resolvers-rest.md b/.changeset/quick-resolvers-rest.mdnew file mode 100644index 000000000..c9e8eaadf--- /dev/null+++ b/.changeset/quick-resolvers-rest.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Scope authored resolver hooks to relevant import specifiers and reuse filesystem probes for one build. Repeated extensionless misses now perform at most 19 stats once per plugin instance instead of on every resolution.diff --git a/packages/eve/src/internal/authored-module-loader.ts b/packages/eve/src/internal/authored-module-loader.tsindex 9dfb17ae4..7bd85af55 100644--- a/packages/eve/src/internal/authored-module-loader.ts+++ b/packages/eve/src/internal/authored-module-loader.ts@@ -1,6 +1,6 @@import { createHash } from "node:crypto";-import { existsSync, mkdirSync, realpathSync, statSync, writeFileSync } from "node:fs";-import { dirname, isAbsolute, join, resolve } from "node:path";+import { existsSync, mkdirSync, writeFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";import type { CompiledAgentManifest } from "#compiler/manifest.js";import { createCompiledModuleMapSource } from "#compiler/module-map.js";@@ -9,6 +9,7 @@ import { assertNoWorkflowDirectivePrologue } from "#internal/authored-directive-import { createAuthoredModuleBundleError } from "#internal/authored-module-bundle.js";import { createAuthoredModuleEvaluationError } from "#internal/authored-module-evaluation-error.js";import { createAuthoredPackageTsConfigPathsPlugin } from "#internal/authored-package-tsconfig-paths.js";+import { createAuthoredRelativeExtensionResolverPlugin } from "#internal/authored-relative-extension-resolver.js";import {createExtensionScopePlugin,createFixedNamespaceScopePlugin,@@ -20,7 +21,6 @@ import {createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,- isPathImport,normalizeExternalDependencies,type RolldownResolveContext,} from "#internal/authored-package-boundary.js";@@ -480,50 +480,6 @@ async function loadBundledAuthoredModule(}}-function createAuthoredRelativeExtensionResolverPlugin(input: {- readonly extensions: readonly string[];-}): Record<string, unknown> {- return {- name: "eve-authored-relative-extension-resolver",- resolveId(source: string, importer: string | undefined) {- if (- importer === undefined ||- importer.startsWith("\0") ||- importer.startsWith(CACHED_CHANNEL_PREFIX) ||- !isPathImport(source)- ) {- return undefined;- }-- const candidate = isAbsolute(source) ? source : resolve(dirname(importer), source);- const resolvedPath = resolveExistingImportPath(candidate, input.extensions);-- if (resolvedPath === undefined) {- return undefined;- }-- // Standard resolvers realpath resolved modules, so a module reached- // through a node_modules symlink resolves its own dependencies from its- // real location — with pnpm's store layout they are store siblings that- // only exist there. Path imports probed here (the compiled module map- // reaches store-installed extension source through the consumer's- // node_modules symlink) must get the same treatment, and it keeps one- // canonical module identity per real file.- return {- id: isNodeModulesPath(resolvedPath) ? toRealModulePath(resolvedPath) : resolvedPath,- };- },- };-}--function toRealModulePath(path: string): string {- try {- return realpathSync(path);- } catch {- return path;- }-}-function createInFlightModuleLoadKey(modulePath: string,options: AuthoredModuleLoadOptions,@@ -533,41 +489,6 @@ function createInFlightModuleLoadKey(return `${modulePath}\0${externalDependencies.join("\0")}\0${options.extensionScopeNamespace ?? ""}`;}-function resolveExistingImportPath(- path: string,- extensions: readonly string[],-): string | undefined {- if (isFile(path)) {- return path;- }-- for (const extension of extensions) {- const candidate = `${path}${extension}`;-- if (isFile(candidate)) {- return candidate;- }- }-- for (const extension of extensions) {- const candidate = join(path, `index${extension}`);-- if (isFile(candidate)) {- return candidate;- }- }-- return undefined;-}--function isFile(path: string): boolean {- try {- return statSync(path).isFile();- } catch {- return false;- }-}-function resolveAuthoredTsConfigPath(packageRoot: string): string | false {for (const fileName of ["tsconfig.json", "jsconfig.json"]) {const path = join(packageRoot, fileName);diff --git a/packages/eve/src/internal/authored-package-tsconfig-paths.test.ts b/packages/eve/src/internal/authored-package-tsconfig-paths.test.tsnew file mode 100644index 000000000..31fb17a07--- /dev/null+++ b/packages/eve/src/internal/authored-package-tsconfig-paths.test.ts@@ -0,0 +1,119 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import { createAuthoredPackageTsConfigPathsPlugin } from "#internal/authored-package-tsconfig-paths.js";++const fsMocks = vi.hoisted(() => ({+ readFile: vi.fn(),+ stat: vi.fn(),+}));++vi.mock("node:fs/promises", () => fsMocks);++type ResolveIdHook = {+ readonly filter: {+ readonly id: {+ readonly exclude: RegExp;+ };+ };+ handler(+ this: {+ resolve(+ source: string,+ importer: string | undefined,+ options: { kind: string; skipSelf: boolean },+ ): Promise<{ readonly id: string } | null>;+ },+ source: string,+ importer: string | undefined,+ options: { kind: string },+ ): Promise<{ readonly id: string } | undefined>;+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe("authored package tsconfig paths resolver", () => {+ it("filters path and protocol imports before the resolver hook runs", () => {+ const hook = getResolveIdHook();++ for (const source of [+ ".hidden",+ "./local",+ "../parent",+ "/absolute",+ "C:\\absolute",+ "node:fs",+ "data:text/plain,hi",+ "file:///x",+ ]) {+ expect(hook.filter.id.exclude.test(source), source).toBe(true);+ }++ for (const source of ["zod", "@scope/package", "#package-import"]) {+ expect(hook.filter.id.exclude.test(source), source).toBe(false);+ }+ });++ it("reuses stat probes within one plugin and refreshes them for the next", async () => {+ const packageRoot = "/workspace/issue-848/package";+ const importer = `${packageRoot}/src/entry.ts`;+ const typescriptTarget = `${packageRoot}/src/value.ts`;+ const tsxTarget = `${packageRoot}/src/value.tsx`;+ const files = new Set([`${packageRoot}/package.json`, typescriptTarget]);+ fsMocks.readFile.mockResolvedValue(+ JSON.stringify({+ compilerOptions: {+ baseUrl: ".",+ paths: {+ "@package/*": ["src/*"],+ },+ },+ }),+ );+ fsMocks.stat.mockImplementation(async (path) => {+ if (files.has(String(path))) {+ return { isFile: () => true };+ }++ throw Object.assign(new Error("not found"), { code: "ENOENT" });+ });+ const context = {+ resolve: vi.fn(async () => null),+ };+ const firstHook = getResolveIdHook();++ await expect(+ firstHook.handler.call(context, "@package/value", importer, {+ kind: "import-statement",+ }),+ ).resolves.toEqual({ id: typescriptTarget });+ expect(fsMocks.stat).toHaveBeenCalledTimes(4);++ files.delete(typescriptTarget);+ files.add(tsxTarget);++ await expect(+ firstHook.handler.call(context, "@package/value", importer, {+ kind: "import-statement",+ }),+ ).resolves.toEqual({ id: typescriptTarget });+ expect(fsMocks.stat).toHaveBeenCalledTimes(4);++ const nextHook = getResolveIdHook();+ await expect(+ nextHook.handler.call(context, "@package/value", importer, {+ kind: "import-statement",+ }),+ ).resolves.toEqual({ id: tsxTarget });+ expect(fsMocks.stat).toHaveBeenCalledTimes(7);+ });+});++function getResolveIdHook(): ResolveIdHook {+ const plugin = createAuthoredPackageTsConfigPathsPlugin({+ appPackageRoot: "/app",+ extensions: [".ts", ".tsx"],+ });+ return plugin.resolveId as ResolveIdHook;+}diff --git a/packages/eve/src/internal/authored-package-tsconfig-paths.ts b/packages/eve/src/internal/authored-package-tsconfig-paths.tsindex 53d175148..8cde604f4 100644--- a/packages/eve/src/internal/authored-package-tsconfig-paths.ts+++ b/packages/eve/src/internal/authored-package-tsconfig-paths.ts@@ -22,6 +22,13 @@ type PackageTsConfigPaths = {}[];};+type FileStat = {+ isFile(): boolean;+};++type CachedStatProbe = (path: string) => Promise<FileStat | undefined>;++const NON_PACKAGE_IMPORT_FILTER = /^(?:\.|\/|[A-Za-z]:[\\/]|node:|data:|file:)/;const packageTsConfigPathsCache = new Map<string, Promise<PackageTsConfigPaths | undefined>>();const nearestPackageRootCache = new Map<string, Promise<string | undefined>>();@@ -34,54 +41,63 @@ export function createAuthoredPackageTsConfigPathsPlugin(input: {appPackageRoot: string;extensions: readonly string[];}): Record<string, unknown> {+ const probeStat = createCachedStatProbe();+return {name: "eve-package-tsconfig-paths",- async resolveId(- this: RolldownResolveContext,- source: string,- importer: string | undefined,- options: { kind: string },- ) {- if (importer === undefined || !isPackageImport(source)) {- return undefined;- }+ resolveId: {+ filter: {+ id: {+ exclude: NON_PACKAGE_IMPORT_FILTER,+ },+ },+ async handler(+ this: RolldownResolveContext,+ source: string,+ importer: string | undefined,+ options: { kind: string },+ ) {+ if (importer === undefined || !isPackageImport(source)) {+ return undefined;+ }- const importerPath = resolve(importer);+ const importerPath = resolve(importer);- if (isPathInsideOrEqual(importerPath, input.appPackageRoot)) {- return undefined;- }+ if (isPathInsideOrEqual(importerPath, input.appPackageRoot)) {+ return undefined;+ }- const packageRoot = await resolveNearestPackageRoot(importerPath);+ const packageRoot = await resolveNearestPackageRoot(importerPath, probeStat);- if (packageRoot === undefined || isPathInsideOrEqual(packageRoot, input.appPackageRoot)) {- return undefined;- }+ if (packageRoot === undefined || isPathInsideOrEqual(packageRoot, input.appPackageRoot)) {+ return undefined;+ }- const config = await loadPackageTsConfigPaths(packageRoot);+ const config = await loadPackageTsConfigPaths(packageRoot);- if (config === undefined) {- return undefined;- }+ if (config === undefined) {+ return undefined;+ }- for (const candidate of createTsConfigPathCandidates(source, config)) {- const resolved = await this.resolve(candidate, importer, {- kind: options.kind,- skipSelf: true,- });+ for (const candidate of createTsConfigPathCandidates(source, config)) {+ const resolved = await this.resolve(candidate, importer, {+ kind: options.kind,+ skipSelf: true,+ });- if (resolved !== null) {- return resolved;- }+ if (resolved !== null) {+ return resolved;+ }- const existingPath = await resolveExistingPath(candidate, input.extensions);+ const existingPath = await resolveExistingPath(candidate, input.extensions, probeStat);- if (existingPath !== undefined) {- return { id: existingPath };+ if (existingPath !== undefined) {+ return { id: existingPath };+ }}- }- return undefined;+ return undefined;+ },},};}@@ -204,15 +220,16 @@ function matchTsConfigPathPattern(source: string, pattern: string): string | undasync function resolveExistingPath(path: string,extensions: readonly string[],+ probeStat: CachedStatProbe,): Promise<string | undefined> {- if (await existsAsFile(path)) {+ if (await existsAsFile(path, probeStat)) {return path;}for (const extension of extensions) {const candidate = `${path}${extension}`;- if (await existsAsFile(candidate)) {+ if (await existsAsFile(candidate, probeStat)) {return candidate;}}@@ -220,7 +237,7 @@ async function resolveExistingPath(for (const extension of extensions) {const candidate = join(path, `index${extension}`);- if (await existsAsFile(candidate)) {+ if (await existsAsFile(candidate, probeStat)) {return candidate;}}@@ -228,15 +245,14 @@ async function resolveExistingPath(return undefined;}-async function existsAsFile(path: string): Promise<boolean> {- try {- return (await stat(path)).isFile();- } catch {- return false;- }+async function existsAsFile(path: string, probeStat: CachedStatProbe): Promise<boolean> {+ return (await probeStat(path))?.isFile() ?? false;}-function resolveNearestPackageRoot(path: string): Promise<string | undefined> {+function resolveNearestPackageRoot(+ path: string,+ probeStat: CachedStatProbe,+): Promise<string | undefined> {const startDirectory = dirname(path);const cached = nearestPackageRootCache.get(startDirectory);@@ -244,16 +260,19 @@ function resolveNearestPackageRoot(path: string): Promise<string | undefined> {return cached;}- const promise = findNearestPackageRoot(startDirectory);+ const promise = findNearestPackageRoot(startDirectory, probeStat);nearestPackageRootCache.set(startDirectory, promise);return promise;}-async function findNearestPackageRoot(startDirectory: string): Promise<string | undefined> {+async function findNearestPackageRoot(+ startDirectory: string,+ probeStat: CachedStatProbe,+): Promise<string | undefined> {let currentDirectory = startDirectory;while (true) {- if (await pathExists(join(currentDirectory, "package.json"))) {+ if (await pathExists(join(currentDirectory, "package.json"), probeStat)) {return currentDirectory;}@@ -267,13 +286,24 @@ async function findNearestPackageRoot(startDirectory: string): Promise<string |}}-async function pathExists(path: string): Promise<boolean> {- try {- await stat(path);- return true;- } catch {- return false;- }+async function pathExists(path: string, probeStat: CachedStatProbe): Promise<boolean> {+ return (await probeStat(path)) !== undefined;+}++function createCachedStatProbe(): CachedStatProbe {+ const cache = new Map<string, Promise<FileStat | undefined>>();++ return (path) => {+ const cached = cache.get(path);++ if (cached !== undefined) {+ return cached;+ }++ const result = stat(path).catch(() => undefined);+ cache.set(path, result);+ return result;+ };}function isPathNotFoundError(error: unknown): boolean {diff --git a/packages/eve/src/internal/authored-relative-extension-resolver.test.ts b/packages/eve/src/internal/authored-relative-extension-resolver.test.tsnew file mode 100644index 000000000..5c4e53e0b--- /dev/null+++ b/packages/eve/src/internal/authored-relative-extension-resolver.test.ts@@ -0,0 +1,89 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import { RESOLVE_EXTENSIONS } from "#internal/authored-package-boundary.js";+import { createAuthoredRelativeExtensionResolverPlugin } from "#internal/authored-relative-extension-resolver.js";++const fsMocks = vi.hoisted(() => ({+ realpathSync: vi.fn((path: string) => path),+ statSync: vi.fn(),+}));++vi.mock("node:fs", async (importOriginal) => ({+ ...(await importOriginal<typeof import("node:fs")>()),+ ...fsMocks,+}));++type ResolveIdHook = {+ readonly filter: {+ readonly id: RegExp;+ };+ handler(source: string, importer: string | undefined): { readonly id: string } | undefined;+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe("authored relative extension resolver", () => {+ it("filters non-path imports before the resolver hook runs", () => {+ const hook = getResolveIdHook();++ for (const source of [".hidden", "./local", "../parent", "/absolute", "C:\\absolute"]) {+ expect(hook.filter.id.test(source), source).toBe(true);+ }++ for (const source of ["zod", "@scope/package", "node:fs", "data:text/plain,hi", "file:///x"]) {+ expect(hook.filter.id.test(source), source).toBe(false);+ }+ });++ it("bounds an extensionless miss to 19 stat probes and reuses them", () => {+ fsMocks.statSync.mockImplementation(() => {+ throw Object.assign(new Error("not found"), { code: "ENOENT" });+ });+ const hook = getResolveIdHook();++ expect(hook.handler("./missing", "/workspace/src/entry.ts")).toBeUndefined();+ expect(fsMocks.statSync).toHaveBeenCalledTimes(1 + RESOLVE_EXTENSIONS.length * 2);++ expect(hook.handler("./missing", "/workspace/src/other.ts")).toBeUndefined();+ expect(fsMocks.statSync).toHaveBeenCalledTimes(19);+ });++ it("discards probe results with the plugin instance", () => {+ const files = new Set(["/workspace/src/value.ts"]);+ fsMocks.statSync.mockImplementation((path) => {+ if (files.has(String(path))) {+ return { isFile: () => true };+ }++ throw Object.assign(new Error("not found"), { code: "ENOENT" });+ });++ const firstHook = getResolveIdHook();+ expect(firstHook.handler("./value", "/workspace/src/entry.ts")).toEqual({+ id: "/workspace/src/value.ts",+ });++ files.delete("/workspace/src/value.ts");+ files.add("/workspace/src/value.tsx");++ expect(firstHook.handler("./value", "/workspace/src/entry.ts")).toEqual({+ id: "/workspace/src/value.ts",+ });+ const probesBeforeNextPlugin = fsMocks.statSync.mock.calls.length;++ const nextHook = getResolveIdHook();+ expect(nextHook.handler("./value", "/workspace/src/entry.ts")).toEqual({+ id: "/workspace/src/value.tsx",+ });+ expect(fsMocks.statSync.mock.calls.length).toBeGreaterThan(probesBeforeNextPlugin);+ });+});++function getResolveIdHook(): ResolveIdHook {+ const plugin = createAuthoredRelativeExtensionResolverPlugin({+ extensions: RESOLVE_EXTENSIONS,+ });+ return plugin.resolveId as ResolveIdHook;+}diff --git a/packages/eve/src/internal/authored-relative-extension-resolver.ts b/packages/eve/src/internal/authored-relative-extension-resolver.tsnew file mode 100644index 000000000..9930ae59d--- /dev/null+++ b/packages/eve/src/internal/authored-relative-extension-resolver.ts@@ -0,0 +1,115 @@+import { realpathSync, statSync } from "node:fs";+import { dirname, isAbsolute, join, resolve } from "node:path";++import {+ CACHED_CHANNEL_PREFIX,+ isNodeModulesPath,+ isPathImport,+} from "#internal/authored-package-boundary.js";++const PATH_IMPORT_FILTER = /^(?:\.|\/|[A-Za-z]:[\\/])/;++/**+ * Resolves extensionless path imports before Rolldown's default resolver.+ */+export function createAuthoredRelativeExtensionResolverPlugin(input: {+ readonly extensions: readonly string[];+}): Record<string, unknown> {+ const isFile = createCachedFileProbe();++ return {+ name: "eve-authored-relative-extension-resolver",+ resolveId: {+ filter: {+ id: PATH_IMPORT_FILTER,+ },+ handler(source: string, importer: string | undefined) {+ if (+ importer === undefined ||+ importer.startsWith("\0") ||+ importer.startsWith(CACHED_CHANNEL_PREFIX) ||+ !isPathImport(source)+ ) {+ return undefined;+ }++ const candidate = isAbsolute(source) ? source : resolve(dirname(importer), source);+ const resolvedPath = resolveExistingImportPath(candidate, input.extensions, isFile);++ if (resolvedPath === undefined) {+ return undefined;+ }++ // Standard resolvers realpath resolved modules, so a module reached+ // through a node_modules symlink resolves its own dependencies from its+ // real location — with pnpm's store layout they are store siblings that+ // only exist there. Path imports probed here (the compiled module map+ // reaches store-installed extension source through the consumer's+ // node_modules symlink) must get the same treatment, and it keeps one+ // canonical module identity per real file.+ return {+ id: isNodeModulesPath(resolvedPath) ? toRealModulePath(resolvedPath) : resolvedPath,+ };+ },+ },+ };+}++function createCachedFileProbe(): (path: string) => boolean {+ const cache = new Map<string, boolean>();++ return (path) => {+ const cached = cache.get(path);++ if (cached !== undefined) {+ return cached;+ }++ let result = false;++ try {+ result = statSync(path).isFile();+ } catch {+ // Missing and inaccessible paths both remain unresolved, as before.+ }++ cache.set(path, result);+ return result;+ };+}++function resolveExistingImportPath(+ path: string,+ extensions: readonly string[],+ isFile: (path: string) => boolean,+): string | undefined {+ if (isFile(path)) {+ return path;+ }++ for (const extension of extensions) {+ const candidate = `${path}${extension}`;++ if (isFile(candidate)) {+ return candidate;+ }+ }++ for (const extension of extensions) {+ const candidate = join(path, `index${extension}`);++ if (isFile(candidate)) {+ return candidate;+ }+ }++ return undefined;+}++function toRealModulePath(path: string): string {+ try {+ return realpathSync(path);+ } catch {+ return path;+ }+}