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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
use std::{borrow::Cow, path::Path};
use compact_str::CompactString;
use crate::{
Alias, AliasValue, CachedPath, FileSystem, ResolveError, ResolverGeneric, TsConfig,
context::ResolveContext as Ctx,
path::{PathUtil, SLASH_START},
};
pub type CompiledAlias = Vec<CompiledAliasEntry>;
#[derive(Clone)]
pub struct CompiledAliasEntry {
key: CompactString,
match_kind: AliasMatchKind,
specifiers: Vec<AliasValue>,
/// First byte of the key (or wildcard prefix), cached so the alias loop can fast-reject
/// non-matching entries without dispatching into the match-kind branch. `None` means an
/// empty key/prefix — which can match any specifier (e.g. a `*` wildcard) — so the entry
/// is always evaluated.
match_first_byte: Option<u8>,
}
#[derive(Clone)]
pub enum AliasMatchKind {
Exact,
Prefix,
Wildcard { prefix: CompactString, suffix: CompactString },
}
pub fn compile_alias(aliases: &Alias) -> CompiledAlias {
aliases
.iter()
.map(|(key, specifiers)| {
let (key, match_kind) = key.strip_suffix('$').map_or_else(
|| {
if let Some((prefix, suffix)) = key.split_once('*') {
(
CompactString::new(key),
AliasMatchKind::Wildcard {
prefix: CompactString::new(prefix),
suffix: CompactString::new(suffix),
},
)
} else {
(CompactString::new(key), AliasMatchKind::Prefix)
}
},
|stripped_key| (CompactString::new(stripped_key), AliasMatchKind::Exact),
);
let match_first_byte = match &match_kind {
AliasMatchKind::Exact | AliasMatchKind::Prefix => key.as_bytes().first().copied(),
AliasMatchKind::Wildcard { prefix, .. } => prefix.as_bytes().first().copied(),
};
CompiledAliasEntry { key, match_kind, specifiers: specifiers.clone(), match_first_byte }
})
.collect()
}
impl<Fs: FileSystem> ResolverGeneric<Fs> {
pub(super) fn load_alias_by_options(
&self,
cached_path: &CachedPath,
specifier: &str,
aliases: &Alias,
tsconfig: Option<&TsConfig>,
ctx: &mut Ctx,
) -> Result<Option<CachedPath>, ResolveError> {
let compiled_aliases = compile_alias(aliases);
self.load_alias(cached_path, specifier, &compiled_aliases, tsconfig, ctx)
}
/// enhanced-resolve: AliasPlugin for [crate::ResolveOptions::alias] and [crate::ResolveOptions::fallback].
pub(super) fn load_alias(
&self,
cached_path: &CachedPath,
specifier: &str,
aliases: &CompiledAlias,
tsconfig: Option<&TsConfig>,
ctx: &mut Ctx,
) -> Result<Option<CachedPath>, ResolveError> {
for alias in aliases {
// Fast-reject entries whose required first byte doesn't match the specifier.
// `match_first_byte == None` means the entry can match any specifier (e.g. an
// empty wildcard prefix), so it always proceeds. The first-byte load is inlined
// so it is skipped entirely when `aliases` is empty (the default config) or when
// every iteration short-circuits on a `None` `match_first_byte`.
if let Some(required) = alias.match_first_byte
&& Some(required) != specifier.as_bytes().first().copied()
{
continue;
}
let alias_key = alias.key.as_str();
match &alias.match_kind {
AliasMatchKind::Exact => {
if alias_key != specifier {
continue;
}
}
AliasMatchKind::Wildcard { .. } => {}
AliasMatchKind::Prefix => {
if Self::strip_package_name(specifier, alias_key).is_none() {
continue;
}
}
}
// It should stop resolving when all of the tried alias values
// failed to resolve.
// <https://github.com/webpack/enhanced-resolve/blob/570337b969eee46120a18b62b72809a3246147da/lib/AliasPlugin.js#L65>
let mut should_stop = false;
for r in &alias.specifiers {
match r {
AliasValue::Path(alias_value) => {
if let Some(path) = self.load_alias_value(
cached_path,
alias_key,
&alias.match_kind,
alias_value,
specifier,
tsconfig,
ctx,
&mut should_stop,
)? {
return Ok(Some(path));
}
}
AliasValue::Ignore => {
let cached_path = cached_path.normalize_with(alias_key, &self.cache);
return Err(ResolveError::Ignored(cached_path.to_path_buf()));
}
}
}
if should_stop {
return Err(ResolveError::MatchedAliasNotFound(
specifier.to_string(),
alias_key.to_string(),
));
}
}
Ok(None)
}
fn load_alias_value(
&self,
cached_path: &CachedPath,
alias_key: &str,
alias_match_kind: &AliasMatchKind,
alias_value: &str,
request: &str,
tsconfig: Option<&TsConfig>,
ctx: &mut Ctx,
should_stop: &mut bool,
) -> Result<Option<CachedPath>, ResolveError> {
if request != alias_value
&& !request.strip_prefix(alias_value).is_some_and(|prefix| prefix.starts_with('/'))
{
let new_specifier = match alias_match_kind {
AliasMatchKind::Wildcard { prefix, suffix } => {
// Resolve wildcard, e.g. `@/*` -> `./src/*`
let Some(alias_key) = request
.strip_prefix(prefix.as_str())
.and_then(|specifier| specifier.strip_suffix(suffix.as_str()))
else {
return Ok(None);
};
if alias_value.contains('*') {
Cow::Owned(alias_value.replacen('*', alias_key, 1))
} else {
Cow::Borrowed(alias_value)
}
}
AliasMatchKind::Exact | AliasMatchKind::Prefix => {
let tail = &request[alias_key.len()..];
if tail.is_empty() {
Cow::Borrowed(alias_value)
} else {
let alias_path = Path::new(alias_value).normalize();
// Must not append anything to alias_value if it is a file.
let cached_alias_path = self.cache.value(&alias_path);
if self.cache.is_file(&cached_alias_path, ctx) {
return Ok(None);
}
// Remove the leading slash so the final path is concatenated.
let tail = tail.trim_start_matches(SLASH_START);
if tail.is_empty() {
Cow::Borrowed(alias_value)
} else {
let normalized = alias_path.normalize_with(tail);
Cow::Owned(normalized.to_string_lossy().to_string())
}
}
}
};
*should_stop = true;
ctx.with_fully_specified(false);
return match self.require(cached_path, new_specifier.as_ref(), tsconfig, ctx) {
Err(ResolveError::NotFound(_) | ResolveError::MatchedAliasNotFound(_, _)) => {
Ok(None)
}
Ok(path) => Ok(Some(path)),
Err(err) => Err(err),
};
}
Ok(None)
}
}