diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 0c6c7618f556..7b5287a51e04 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -376,6 +376,7 @@ pub struct Bufs { pub dir_info_uncached_path: PathBuffer, pub tsconfig_base_url: PathBuffer, pub relative_abs_path: PathBuffer, + pub custom_dir_path_abs: PathBuffer, pub load_as_file_or_directory_via_tsconfig_base_path: PathBuffer, pub node_modules_check: PathBuffer, pub field_abs_path: PathBuffer, @@ -2097,12 +2098,16 @@ impl<'a> Resolver<'a> { bun_core::hint::cold(); for custom_path in custom_paths { let custom_utf8 = custom_path.to_utf8_without_ref(); - match self.check_package_path( - custom_utf8.slice(), - import_path, - kind, - global_cache, - ) { + // `require.resolve` `paths` entries are user-provided and may be + // relative; Node resolves them against the current directory. + let Some(abs_custom_path) = self + .fs_ref() + .abs_buf_checked(&[custom_utf8.slice()], bufs!(custom_dir_path_abs)) + else { + continue; + }; + match self.check_package_path(abs_custom_path, import_path, kind, global_cache) + { ResultUnion::Success(res) => return ResultUnion::Success(res), ResultUnion::Pending(p) => return ResultUnion::Pending(p), ResultUnion::Failure(p) => return ResultUnion::Failure(p), diff --git a/test/js/node/module/node-module-module.test.js b/test/js/node/module/node-module-module.test.js index af16e04632d0..2a72de1d802d 100644 --- a/test/js/node/module/node-module-module.test.js +++ b/test/js/node/module/node-module-module.test.js @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, ospath } from "harness"; +import { bunEnv, bunExe, ospath, tempDir } from "harness"; import Module, { _nodeModulePaths, builtinModules, createRequire, isBuiltin, wrap } from "module"; import path from "path"; @@ -233,6 +233,26 @@ describe.concurrent("node-module-module", () => { expect(require("./esm_to_cjs_interop.mjs")).toEqual(Symbol.for("meow")); }); + test("require.resolve options.paths resolves relative entries against the working directory", async () => { + using dir = tempDir("resolve-paths-relative", { + "sub/node_modules/paths-rel-pkg/package.json": JSON.stringify({ name: "paths-rel-pkg", main: "index.js" }), + "sub/node_modules/paths-rel-pkg/index.js": `module.exports = "from-sub";`, + "main.cjs": `console.log(require(require.resolve("paths-rel-pkg", { paths: ["sub"] })));`, + }); + + await using proc = Bun.spawn({ + cmd: [bunExe(), "main.cjs"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stdout.trim()).toBe("from-sub"); + expect(exitCode).toBe(0); + }); + test("Module.runMain", async () => { await using proc = Bun.spawn({ cmd: [