1use std::cell::RefCell;
4use crate::utils::fx::HashMap;
5
6pub fn match_url(url: &str) -> bool {
8 url.starts_with("//") || url.starts_with("http://") || url.starts_with("https://")
9}
10
11fn windows_prefix(path: &str) -> usize {
13 let b = path.as_bytes();
14 let start = if b.first() == Some(&b'/') { 1 } else { 0 };
15 if b.len() > start + 1 && b[start].is_ascii_alphabetic() && b[start + 1] == b':' {
16 start + 2
17 } else {
18 0
19 }
20}
21
22pub fn dirname(path: &str) -> String {
24 if path.is_empty() {
25 return String::new();
26 }
27 if path.starts_with("data:") {
28 return path.to_string();
29 }
30 let mut parts: Vec<&str> = path.split('/').collect();
31 parts.pop();
32 parts.join("/")
33}
34
35fn split_path(result: &str) -> Vec<String> {
36 if result.is_empty() {
37 return Vec::new();
38 }
39 let mut parts: Vec<String> = if result == "/" { Vec::new() } else { vec![String::new()] };
40 for c in result.chars() {
41 if c == '/' {
42 parts.push(String::new());
43 } else {
44 if parts.is_empty() {
45 parts.push(String::new());
47 }
48 parts.last_mut().unwrap().push(c);
49 }
50 }
51 parts
52}
53
54thread_local! {
55 static NORMALIZED: RefCell<HashMap<String, String>> = RefCell::new(HashMap::default());
56 static RESOLVED: RefCell<HashMap<(String, String, String), ResolvedPath>> = RefCell::new(HashMap::default());
57}
58
59pub fn normalize(path: &str) -> String {
61 if let Some(n) = NORMALIZED.with(|c| c.borrow().get(path).cloned()) {
62 return n;
63 }
64 let mut p = path.replace('\\', "/");
65 let w = windows_prefix(&p);
66 if w > 0 {
67 p = p[w..].to_string();
68 }
69 let mut parts: Vec<String> = Vec::new();
70 for c in p.chars() {
71 if c == '/' {
72 if parts.last().is_none_or(|l| !l.is_empty()) {
73 parts.push(String::new());
74 }
75 } else if c == '?' || c == '#' {
76 break;
77 } else {
78 if parts.is_empty() {
79 parts.push(String::new());
80 }
81 parts.last_mut().unwrap().push(c);
82 }
83 }
84 let mut k: isize = -1;
85 loop {
86 k += 1;
87 if k as usize >= parts.len() {
88 break;
89 }
90 if k > 0 && parts[k as usize] == ".." {
91 parts.drain((k - 1) as usize..(k + 1) as usize);
92 k -= 2;
93 }
94 }
95 let result = format!("{}{}", if p.starts_with('/') { "/" } else { "" }, parts.join("/"));
96 NORMALIZED.with(|c| c.borrow_mut().insert(path.to_string(), result.clone()));
97 result
98}
99
100pub fn diff(path1: &str, path2: &str) -> String {
102 let mut parts = split_path(path1);
103 for p in split_path(path2) {
104 if parts.first() == Some(&p) {
105 parts.remove(0);
106 } else {
107 parts.insert(0, "..".into());
108 }
109 }
110 parts.join("/")
111}
112
113#[derive(Clone, Debug, PartialEq, Eq)]
115pub struct ResolvedPath {
116 pub absolute: String,
117 pub relative: String,
118}
119
120pub fn resolve(url: &str, current_directory: &str, cwd: Option<&str>) -> ResolvedPath {
122 let key = (url.to_string(), current_directory.to_string(), cwd.unwrap_or("\u{0}undefined").to_string());
123 if let Some(r) = RESOLVED.with(|c| c.borrow().get(&key).cloned()) {
124 return r;
125 }
126 let result = resolve_uncached(url, current_directory, cwd.unwrap_or(""));
127 RESOLVED.with(|c| c.borrow_mut().insert(key, result.clone()));
128 result
129}
130
131fn resolve_uncached(url: &str, current_directory: &str, cwd: &str) -> ResolvedPath {
132 if match_url(url) {
133 return ResolvedPath { absolute: url.to_string(), relative: url.to_string() };
134 }
135 let url = normalize(url);
136 let cwd = if cwd.is_empty() { String::new() } else { normalize(cwd) };
137 let current_directory = if current_directory.is_empty() { String::new() } else { normalize(current_directory) };
138 let mut dir = if cwd.is_empty() { current_directory } else { cwd };
139 let w = windows_prefix(&dir);
140 if w > 0 {
141 dir = dir[w..].to_string();
142 }
143 let absolute = if dir.is_empty() || url.starts_with('/') || url.starts_with(&dir) || windows_prefix(&url) > 0 {
144 resolve_path(&[&url])
145 } else {
146 resolve_path(&[&dir, &url])
147 };
148 let relative = if dir.is_empty() { absolute.clone() } else { diff(&absolute, &dir) };
149 ResolvedPath { absolute, relative }
150}
151
152fn resolve_path(parts: &[&str]) -> String {
153 let path = parts.iter().filter(|p| !p.is_empty()).copied().collect::<Vec<_>>().join("/");
154 let is_absolute = path.starts_with('/') || path.starts_with('\\');
155 let mut resolved: Vec<&str> = Vec::new();
156 for segment in path.split(['/', '\\']) {
157 if segment.is_empty() || segment == "." {
158 continue;
159 }
160 if segment == ".." {
161 if !resolved.is_empty() && *resolved.last().unwrap() != ".." {
162 resolved.pop();
163 } else if !is_absolute {
164 resolved.push("..");
165 }
166 } else {
167 resolved.push(segment);
168 }
169 }
170 let mut result = resolved.join("/");
171 if is_absolute {
172 result = format!("/{}", result);
173 }
174 if result.is_empty() {
175 if is_absolute { "/".into() } else { ".".into() }
176 } else {
177 result
178 }
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 #[test]
187 fn resolve_parity() {
188 let cases: [(&str, &str, Option<&str>, &str, &str, &str); 8] = [
189 ("a.css", "/x/y", None, "/x/y/a.css", "a.css", ""),
190 ("../a.css", "/x/y", None, "/x/a.css", "../a.css", ".."),
191 ("/a/b.css", "/x", None, "/a/b.css", "../a/b.css", "/a"),
192 ("https://a.b/c.css", "x", None, "https://a.b/c.css", "https://a.b/c.css", "https://a.b"),
193 ("./a/../b.css", "", None, "b.css", "b.css", "./a/.."),
194 ("C:\\x\\y.css", "/z", None, "/x/y.css", "../x/y.css", ""),
195 ("a.css", "x/y", Some("/cwd"), "/cwd/a.css", "a.css", ""),
196 ("../../q.css?x#y", "a/b/c", None, "a/b/c/q.css", "q.css", "../.."),
197 ];
198 for (url, dir, cwd, absolute, relative, dn) in cases {
199 let r = resolve(url, dir, cwd);
200 assert_eq!((r.absolute.as_str(), r.relative.as_str()), (absolute, relative), "{}", url);
201 assert_eq!(dirname(url), dn, "{}", url);
202 }
203 }
204}