The Open Framework for Building Agents
fix: resolve dotted extensionless imports (#182)
JJ Kasper27a97015b666
diff --git a/.changeset/dotted-basename-imports.md b/.changeset/dotted-basename-imports.mdnew file mode 100644index 000000000..160e9dc7c--- /dev/null+++ b/.changeset/dotted-basename-imports.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Resolve extensionless relative imports whose target basename contains dots when bundling authored modules. Local files such as `./mock-registry.schemas` and dependency requires such as `./Reflect.getPrototypeOf` now probe Eve's configured `.ts` and `.js` extensions before being treated as asset imports.diff --git a/packages/eve/src/internal/authored-module-loader.scenario.test.ts b/packages/eve/src/internal/authored-module-loader.scenario.test.tsindex ba664e91c..a7b163f05 100644--- a/packages/eve/src/internal/authored-module-loader.scenario.test.ts+++ b/packages/eve/src/internal/authored-module-loader.scenario.test.ts@@ -1,4 +1,4 @@-import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";@@ -12,6 +12,176 @@ import { useScenarioApp } from "#internal/testing/scenario-app.js";describe("loadAuthoredModuleNamespace", () => {const scenarioApp = useScenarioApp();+ it("preserves cached channel identity for relative channel imports", async () => {+ const app = await scenarioApp({+ files: {+ "agent/channels/support.ts": [+ 'export default { marker: "source-channel-instance" };',+ "",+ ].join("\n"),+ "agent/tools/use_support_channel.ts": [+ 'import supportChannel from "../channels/support";',+ "",+ "export const result = supportChannel.marker;",+ "",+ ].join("\n"),+ },+ name: "cached-relative-channel-import",+ });+ const cache = new Map<string, unknown>();+ const cacheKey = "__eveChannelModuleCache__";+ const globals = globalThis as Record<string, unknown>;+ const previousCache = globals[cacheKey];++ try {+ const supportChannelPath = await realpath(+ join(app.appRoot, "agent", "channels", "support.ts"),+ );+ cache.set(supportChannelPath, { marker: "cached-channel-instance" });+ globals[cacheKey] = cache;++ const moduleNamespace = await loadAuthoredModuleNamespace(+ join(app.appRoot, "agent", "tools", "use_support_channel.ts"),+ );++ expect(moduleNamespace.result).toBe("cached-channel-instance");+ } finally {+ if (previousCache === undefined) {+ delete globals[cacheKey];+ } else {+ globals[cacheKey] = previousCache;+ }+ }+ });++ it("resolves extensionless relative imports with dotted TypeScript basenames", async () => {+ const app = await scenarioApp({+ files: {+ "agent/tools/use_schema.ts": [+ 'import { schemaValue } from "./mock-registry.schemas";',+ "",+ "export const result = schemaValue;",+ "",+ ].join("\n"),+ "agent/tools/mock-registry.schemas.ts": [+ 'export const schemaValue = "local-dotted-basename";',+ "",+ ].join("\n"),+ },+ name: "local-dotted-basename-import",+ });++ const moduleNamespace = await loadAuthoredModuleNamespace(+ join(app.appRoot, "agent", "tools", "use_schema.ts"),+ );++ expect(moduleNamespace.result).toBe("local-dotted-basename");+ });++ it("resolves extensionless relative directory imports to index modules", async () => {+ const app = await scenarioApp({+ files: {+ "agent/tools/use_helpers.ts": [+ 'import { helperValue } from "./helpers";',+ "",+ "export const result = helperValue;",+ "",+ ].join("\n"),+ "agent/tools/helpers/index.ts": ['export const helperValue = "directory-index";', ""].join(+ "\n",+ ),+ },+ name: "directory-index-import",+ });++ const moduleNamespace = await loadAuthoredModuleNamespace(+ join(app.appRoot, "agent", "tools", "use_helpers.ts"),+ );++ expect(moduleNamespace.result).toBe("directory-index");+ });++ it("resolves extensionless CommonJS requires with dotted JavaScript basenames", async () => {+ const app = await scenarioApp({+ files: {+ "agent/channels/api/contact-sales/webhook.ts": [+ 'import { readDottedValue } from "@repo/enrichment/dotted";',+ "",+ "export const result = readDottedValue();",+ "",+ ].join("\n"),+ },+ name: "dependency-dotted-basename-require",+ });+ const workspaceRoot = await mkdtemp(join(tmpdir(), "eve-dependency-dotted-basename-"));++ try {+ const packageRoot = join(workspaceRoot, "packages", "enrichment");+ const packageNodeModules = join(packageRoot, "node_modules", "fixture-dotted-cjs-dep");+ await mkdir(join(packageRoot, "src"), { recursive: true });+ await mkdir(packageNodeModules, { recursive: true });+ await writeFile(+ join(packageRoot, "package.json"),+ JSON.stringify(+ {+ exports: {+ "./dotted": "./src/dotted.ts",+ },+ name: "@repo/enrichment",+ type: "module",+ },+ null,+ 2,+ ),+ );+ await writeFile(+ join(packageRoot, "src", "dotted.ts"),+ [+ 'import dottedDependency from "fixture-dotted-cjs-dep";',+ "",+ "export function readDottedValue() {",+ " return dottedDependency.value;",+ "}",+ "",+ ].join("\n"),+ );+ await writeFile(+ join(packageNodeModules, "package.json"),+ JSON.stringify(+ {+ main: "index.cjs",+ name: "fixture-dotted-cjs-dep",+ },+ null,+ 2,+ ),+ );+ await writeFile(+ join(packageNodeModules, "index.cjs"),+ 'module.exports = require("./Reflect.getPrototypeOf");\n',+ );+ await writeFile(+ join(packageNodeModules, "Reflect.getPrototypeOf.js"),+ 'module.exports = { value: "cjs-dotted-basename" };\n',+ );++ await mkdir(join(app.appRoot, "node_modules", "@repo"), { recursive: true });+ await symlink(+ packageRoot,+ join(app.appRoot, "node_modules", "@repo", "enrichment"),+ "junction",+ );++ const moduleNamespace = await loadAuthoredModuleNamespace(+ join(app.appRoot, "agent", "channels", "api", "contact-sales", "webhook.ts"),+ );++ expect(moduleNamespace.result).toBe("cjs-dotted-basename");+ } finally {+ await rm(workspaceRoot, { force: true, recursive: true });+ }+ });+it("bundles symlinked workspace packages that export TypeScript source", async () => {const app = await scenarioApp({files: {@@ -727,15 +897,18 @@ describe("loadAuthoredModuleNamespace", () => {const app = await scenarioApp({files: {"agent/assets/logo.bin": "logo-bytes",+ "agent/assets/logo.png": "png-bytes","agent/assets/message.txt": "asset text","agent/tools/use_assets.ts": ['import logoUrl from "../assets/logo.bin";',+ 'import imageUrl from "../assets/logo.png";','import rawText from "../assets/message.txt?raw";',"","export default {",' description: "Use asset imports.",'," async execute() {"," return {",+ " imageUrl,"," logoUrl,"," rawText,"," };",@@ -752,12 +925,14 @@ describe("loadAuthoredModuleNamespace", () => {);const tool = moduleNamespace.default as {execute(): Promise<{+ imageUrl: string;logoUrl: string;rawText: string;}>;};await expect(tool.execute()).resolves.toEqual({+ imageUrl: "data:image/png;base64,cG5nLWJ5dGVz",logoUrl: "data:application/octet-stream;base64,bG9nby1ieXRlcw==",rawText: "asset text",});diff --git a/packages/eve/src/internal/authored-module-loader.ts b/packages/eve/src/internal/authored-module-loader.tsindex 42efbe06a..6ebcb3157 100644--- a/packages/eve/src/internal/authored-module-loader.ts+++ b/packages/eve/src/internal/authored-module-loader.ts@@ -1,7 +1,7 @@import { createHash } from "node:crypto";-import { existsSync, mkdirSync, realpathSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, realpathSync, statSync, writeFileSync } from "node:fs";import { createRequire } from "node:module";-import { dirname, join, resolve, sep } from "node:path";+import { dirname, isAbsolute, join, resolve, sep } from "node:path";import { createAuthoredAssetImportPlugin } from "#internal/authored-asset-import-plugin.js";import { createAuthoredModuleBundleError } from "#internal/authored-module-bundle.js";@@ -195,6 +195,8 @@ async function loadBundledAuthoredModule(}: null;const plugins = [+ channelIdentityPlugin,+ createAuthoredRelativeExtensionResolverPlugin({ extensions: RESOLVE_EXTENSIONS }),createAuthoredAssetImportPlugin(),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot: packageRoot,@@ -202,7 +204,6 @@ async function loadBundledAuthoredModule(}),createNodeEsmCompatBannerPlugin({ includeRequire: true }),createPackageBoundaryPlugin(packageRoot, externalDependencies),- channelIdentityPlugin,].filter((plugin) => plugin !== null);let outputFile: { readonly code: string };@@ -246,6 +247,33 @@ async function loadBundledAuthoredModule(return await import(`${createFileImportSpecifier(bundlePath)}?v=${bundleHash}`);}+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;+ }++ return { id: resolvedPath };+ },+ };+}+function createPackageBoundaryPlugin(packageRoot: string,externalDependencies: readonly string[],@@ -435,6 +463,41 @@ function resolveExistingExternalFilePath(id: string): string | undefined {return undefined;}+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 normalizeImporterPath(importer: string | undefined): string | undefined {if (importer === undefined ||@@ -448,7 +511,7 @@ function normalizeImporterPath(importer: string | undefined): string | undefined}function isPackageImport(source: string): boolean {- if (source.startsWith(".") || source.startsWith("/") || /^[A-Za-z]:[\\/]/.test(source)) {+ if (isPathImport(source)) {return false;}@@ -463,6 +526,10 @@ function isPackageImport(source: string): boolean {return !source.startsWith(CACHED_CHANNEL_PREFIX);}+function isPathImport(source: string): boolean {+ return source.startsWith(".") || source.startsWith("/") || /^[A-Za-z]:[\\/]/.test(source);+}+function isEveFrameworkImport(source: string): boolean {return source === "eve" || source.startsWith("eve/");}