1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
use std::{
fs::File,
io::BufReader,
path::{Path, PathBuf},
};
use anyhow::{bail, Context, Error};
use path_clean::PathClean;
use serde::Deserialize;
use swc_common::FileName;
use swc_ecma_loader::resolve::Resolve;
static EXTENSIONS: &[&str] = &["tsx", "ts", "d.ts"];
#[derive(Deserialize)]
struct PackageJson {
#[serde(default)]
types: Option<String>,
}
#[derive(Default)]
pub struct NodeResolver;
impl NodeResolver {
pub fn new() -> Self {
Self
}
fn wrap(&self, path: PathBuf) -> Result<FileName, Error> {
let path = path.clean();
Ok(FileName::Real(path))
}
pub fn resolve_as_file(&self, path: &Path) -> Result<PathBuf, Error> {
if path.is_file() {
return Ok(path.to_path_buf());
}
for ext in EXTENSIONS {
let ext_path = path.with_extension(ext);
if ext_path.is_file() {
return Ok(ext_path);
}
}
bail!("file not found: {}", path.display())
}
pub fn resolve_as_directory(&self, path: &Path) -> Result<PathBuf, Error> {
let pkg_path = path.join("package.json");
if pkg_path.is_file() {
let main = self.resolve_using_package_json(&pkg_path);
if main.is_ok() {
return main;
}
}
self.resolve_index(path)
}
fn resolve_using_package_json(&self, pkg_path: &PathBuf) -> Result<PathBuf, Error> {
let root = PathBuf::from("/");
let pkg_dir = pkg_path.parent().unwrap_or(&root);
let file = File::open(pkg_path)?;
let reader = BufReader::new(file);
let pkg: PackageJson = serde_json::from_reader(reader).context("failed to deserialize package.json")?;
if let Some(target) = &pkg.types {
let path = pkg_dir.join(target);
return self.resolve_as_file(&path).or_else(|_| self.resolve_as_directory(&path));
}
bail!("package.json does not contain a \"main\" string")
}
fn resolve_index(&self, path: &Path) -> Result<PathBuf, Error> {
for ext in EXTENSIONS {
let ext_path = path.join(format!("index.{}", ext));
if ext_path.is_file() {
return Ok(ext_path);
}
}
bail!("index not found: {}", path.display())
}
fn try_package(&self, pkg_dir: &Path) -> Result<PathBuf, Error> {
self.resolve_as_file(pkg_dir).or_else(|_| self.resolve_as_directory(pkg_dir))
}
fn resolve_node_modules(&self, base_dir: &Path, target: &str) -> Result<PathBuf, Error> {
let node_modules = base_dir.join("node_modules");
if node_modules.is_dir() {
let path = node_modules.join(target);
let result = self.try_package(&path);
if result.is_ok() {
return result;
}
{
let types = node_modules.join("@types").join(target);
if types.is_dir() {
let result = self.try_package(&types);
if result.is_ok() {
return result;
}
}
}
}
match base_dir.parent() {
Some(parent) => self.resolve_node_modules(parent, target),
None => bail!("failed to find {target} from {}", base_dir.display()),
}
}
}
impl Resolve for NodeResolver {
fn resolve(&self, base: &FileName, target: &str) -> Result<FileName, Error> {
let base = match base {
FileName::Real(base) => &**base,
_ => {
unreachable!("base = {:?}; target = {:?}", base, target)
}
};
if target.starts_with('/') {
let base_dir = &Path::new("/");
let path = base_dir.join(target);
return self
.resolve_as_file(&path)
.or_else(|_| self.resolve_as_directory(&path))
.and_then(|p| self.wrap(p));
}
let cwd = &Path::new(".");
let base_dir = base.parent().unwrap_or(cwd);
if target.starts_with("./") || target.starts_with("../") {
let path = base_dir.join(target);
return self
.resolve_as_file(&path)
.with_context(|| format!("failed to resolve `{}` as a file dependency from `{}`", target, base.display()))
.or_else(|_| {
self.resolve_as_directory(&path)
.with_context(|| format!("failed to resolve `{}` as a directory dependency from `{}`", target, base.display()))
})
.and_then(|p| self.wrap(p));
}
self.resolve_node_modules(base_dir, target)
.with_context(|| format!("failed to resolve `{}` as a node module from `{}`", target, base.display()))
.and_then(|p| self.wrap(p))
}
}