Files
Donny/강동윤andGitHub 42638f9e47 fix(es/modules): resolve relative symlinked inputs from cwd (#11883)
**Description:**

Fixes a `jsc.paths` + `jsc.preserveSymlinks` path rewriting bug when SWC
is invoked with a relative input filename. Relative source filenames
should be interpreted from the current process directory, while
path-mapped targets should continue to resolve from `jsc.baseUrl`.

The bug showed up in Bazel-style symlink layouts where the relative
input path was accidentally re-rooted under `jsc.baseUrl`, producing too
many `../` segments in emitted CommonJS `require()` paths.

This PR also adds a regression test for issue 11880 using a Bazel-like
symlinked layout and verifies that `#/apis/auth` rewrites to
`../../apis/auth`.

**Related issue:**

Fixes #11880

**Validation:**

- `git submodule update --init --recursive`
- `cargo test -p swc_ecma_transforms_module issue_11880`
- `cargo test -p swc_ecma_transforms_module`
- `cargo fmt --all`
- `cargo clippy --all --all-targets -- -D warnings`
2026-06-29 13:17:09 +09:00

343 lines
9.6 KiB
Rust

use std::{
fs::{create_dir_all, write},
path::{Path, PathBuf},
sync::Arc,
};
use indexmap::IndexMap;
use serde::Deserialize;
use swc_common::FileName;
use swc_ecma_loader::resolvers::{node::NodeModulesResolver, tsc::TsConfigResolver};
use swc_ecma_parser::Syntax;
use swc_ecma_transforms_module::{
path::{ImportResolver, NodeImportResolver},
rewriter::import_rewriter,
};
use swc_ecma_transforms_testing::{test_fixture, FixtureTestConfig};
use tempfile::tempdir;
use testing::run_test2;
type TestProvider = NodeImportResolver<NodeModulesResolver>;
#[test]
fn node_modules() {
let provider = TestProvider::default();
run_test2(false, |cm, _| {
let fm = cm.new_source_file(FileName::Real("foo".into()).into(), "");
let resolved = provider
.resolve_import(&fm.name, "core-js")
.expect("should success");
assert_eq!(&*resolved, "core-js");
Ok(())
})
.unwrap();
}
#[test]
fn issue_4730() {
let dir = Path::new("tests/fixture-manual/issue-4730")
.canonicalize()
.unwrap();
let input_dir = dir.join("input");
let output_dir = dir.join("output");
test_fixture(
Syntax::default(),
&|_| {
let mut paths = IndexMap::new();
paths.insert(
"@print/a".into(),
vec![dir
.join("input")
.join("packages")
.join("a")
.join("src")
.join("index.js")
.display()
.to_string()],
);
paths.insert(
"@print/b".into(),
vec![dir
.join("input")
.join("packages")
.join("b")
.join("src")
.join("index.js")
.display()
.to_string()],
);
let rules = paths.into_iter().collect();
let resolver = paths_resolver(&input_dir, rules, true);
import_rewriter(
FileName::Real(input_dir.join("src").join("index.js")),
Arc::new(resolver),
)
},
&input_dir.join("src").join("index.js"),
&output_dir.join("index.js"),
FixtureTestConfig {
module: Some(true),
..Default::default()
},
);
}
type JscPathsProvider = NodeImportResolver<TsConfigResolver<NodeModulesResolver>>;
fn paths_resolver(
base_dir: &Path,
rules: Vec<(String, Vec<String>)>,
resolve_fully: bool,
) -> JscPathsProvider {
paths_resolver_with_options(base_dir, rules, resolve_fully, false)
}
fn paths_resolver_with_options(
base_dir: &Path,
rules: Vec<(String, Vec<String>)>,
resolve_fully: bool,
preserve_symlinks: bool,
) -> JscPathsProvider {
let base_dir = base_dir
.to_path_buf()
.canonicalize()
.expect("failed to canonicalize");
dbg!(&base_dir);
let resolver = TsConfigResolver::new(
NodeModulesResolver::new(swc_ecma_loader::TargetEnv::Node, Default::default(), true),
base_dir.clone(),
rules,
);
let config = swc_ecma_transforms_module::path::Config {
base_dir: Some(base_dir),
resolve_fully,
file_extension: swc_ecma_transforms_module::util::Config::default_js_ext(),
};
if preserve_symlinks {
NodeImportResolver::with_config_preserving_symlinks(resolver, config)
} else {
NodeImportResolver::with_config(resolver, config)
}
}
#[test]
fn symlink_paths_are_preserved_only_when_opted_in() {
let sandbox = tempdir().unwrap();
let root = sandbox.path();
create_dir_all(root.join("src")).unwrap();
create_dir_all(root.join("shared")).unwrap();
create_dir_all(root.join("server")).unwrap();
write(root.join("src/index.ts"), "import \"../server/source\";\n").unwrap();
write(root.join("shared/source.ts"), "export const value = 1;\n").unwrap();
create_symlink(
&root.join("shared/source.ts"),
&root.join("server/source.ts"),
);
let base = FileName::Real(root.join("src/index.ts").canonicalize().unwrap());
// Keep the original extensionless specifier so the assertion focuses on
// symlink preservation instead of extension rewriting.
let default_resolver = paths_resolver_with_options(root, Vec::new(), false, false);
let preserve_symlinks_resolver = paths_resolver_with_options(root, Vec::new(), false, true);
let default_resolved = default_resolver
.resolve_import(&base, "../server/source")
.unwrap();
let preserve_symlinks_resolved = preserve_symlinks_resolver
.resolve_import(&base, "../server/source")
.unwrap();
assert_eq!(&*default_resolved, "../shared/source");
assert_eq!(&*preserve_symlinks_resolved, "../server/source");
}
#[test]
fn issue_11880_preserve_symlinks_uses_cwd_for_relative_input_filename() {
let cwd = std::env::current_dir().unwrap();
let sandbox = tempfile::tempdir_in(&cwd).unwrap();
let root = sandbox.path();
create_dir_all(root.join("apis")).unwrap();
create_dir_all(root.join("bazel-out/apis")).unwrap();
create_dir_all(root.join("foo-app/src")).unwrap();
create_dir_all(root.join("bazel-out/foo-app/src")).unwrap();
write(
root.join("apis/auth.ts"),
"export const hello = () => 'hello';\n",
)
.unwrap();
write(
root.join("foo-app/src/app.ts"),
"import { hello } from '#/apis/auth';\nexport const greet = () => hello();\n",
)
.unwrap();
create_symlink(
&root.join("apis/auth.ts"),
&root.join("bazel-out/apis/auth.ts"),
);
create_symlink(
&root.join("foo-app/src/app.ts"),
&root.join("bazel-out/foo-app/src/app.ts"),
);
let resolver = paths_resolver_with_options(
&root.join("bazel-out/foo-app"),
vec![("#/apis/*".into(), vec!["../apis/*".into()])],
false,
true,
);
let relative_input = root
.join("bazel-out/foo-app/src/app.ts")
.strip_prefix(&cwd)
.unwrap()
.to_path_buf();
let resolved = resolver
.resolve_import(&FileName::Real(relative_input), "#/apis/auth")
.unwrap();
assert_eq!(&*resolved, "../../apis/auth");
}
#[test]
fn mixed_relative_target_cleans_absolute_base_path() {
let cwd = std::env::current_dir().unwrap();
let sandbox = tempfile::tempdir_in(&cwd).unwrap();
let root = sandbox.path();
create_dir_all(root.join("bazel-out/foo-app/src")).unwrap();
write(
root.join("bazel-out/foo-app/src/app.ts"),
"import { hello } from '#/apis/auth';\n",
)
.unwrap();
let resolver = paths_resolver_with_options(
&root.join("bazel-out/foo-app"),
vec![("#/apis/*".into(), vec!["../apis/*".into()])],
false,
true,
);
let base = root.join("bazel-out/foo-app/src/../src/app.ts");
let resolved = resolver
.resolve_import(&FileName::Real(base), "#/apis/auth")
.unwrap();
assert_eq!(&*resolved, "../../apis/auth");
}
#[test]
fn mixed_absolute_target_cleans_target_path() {
let cwd = std::env::current_dir().unwrap();
let sandbox = tempfile::tempdir_in(&cwd).unwrap();
let root = sandbox.path();
create_dir_all(root.join("bazel-out/foo-app/src")).unwrap();
write(
root.join("bazel-out/foo-app/src/app.ts"),
"import { hello } from '#/apis/auth';\n",
)
.unwrap();
let target = root.join("bazel-out/apis/../apis/*").display().to_string();
let resolver = paths_resolver_with_options(
&root.join("bazel-out/foo-app"),
vec![("#/apis/*".into(), vec![target])],
false,
true,
);
let relative_input = root
.join("bazel-out/foo-app/src/app.ts")
.strip_prefix(&cwd)
.unwrap()
.to_path_buf();
let resolved = resolver
.resolve_import(&FileName::Real(relative_input), "#/apis/auth")
.unwrap();
assert_eq!(&*resolved, "../../apis/auth");
}
fn create_symlink(a: &Path, b: &Path) {
#[cfg(unix)]
{
std::os::unix::fs::symlink(a, b).unwrap();
}
#[cfg(windows)]
{
std::os::windows::fs::symlink_file(a, b).unwrap();
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct TestConfig {
#[serde(default)]
base_url: Option<PathBuf>,
#[serde(default)]
input_file: Option<String>,
#[serde(default)]
paths: IndexMap<String, Vec<String>>,
#[serde(default = "default_resolve_fully")]
resolve_fully: bool,
}
fn default_resolve_fully() -> bool {
true
}
#[testing::fixture("tests/paths/**/input")]
fn fixture(input_dir: PathBuf) {
let output_dir = input_dir.parent().unwrap().join("output");
let paths_json_path = input_dir.join("config.json");
let paths_json = std::fs::read_to_string(paths_json_path).unwrap();
let config = serde_json::from_str::<TestConfig>(&paths_json).unwrap();
let index_path = input_dir.join(config.input_file.as_deref().unwrap_or("index.ts"));
dbg!(&index_path);
let base_dir = input_dir
.join(config.base_url.clone().unwrap_or(input_dir.clone()))
.canonicalize()
.unwrap();
dbg!(&base_dir);
test_fixture(
Syntax::default(),
&|_| {
let rules = config.paths.clone().into_iter().collect();
let resolver = paths_resolver(&base_dir, rules, config.resolve_fully);
import_rewriter(FileName::Real(index_path.clone()), Arc::new(resolver))
},
&index_path,
&output_dir.join("index.ts"),
FixtureTestConfig {
module: Some(true),
..Default::default()
},
);
}