rquickjs_core/loader/
builtin_resolver.rs1use crate::{loader::Resolver, Ctx, Error, Result};
2use relative_path::RelativePath;
3use std::collections::HashSet;
4
5#[derive(Debug, Default)]
9pub struct BuiltinResolver {
10 modules: HashSet<String>,
11}
12
13impl BuiltinResolver {
14 pub fn add_module<P: Into<String>>(&mut self, path: P) -> &mut Self {
16 self.modules.insert(path.into());
17 self
18 }
19
20 #[must_use]
22 pub fn with_module<P: Into<String>>(mut self, path: P) -> Self {
23 self.add_module(path);
24 self
25 }
26}
27
28impl Resolver for BuiltinResolver {
29 fn resolve<'js>(&mut self, _ctx: &Ctx<'js>, base: &str, name: &str) -> Result<String> {
30 let full = if !name.starts_with('.') {
31 name.to_string()
32 } else {
33 let base = RelativePath::new(base);
34 if let Some(dir) = base.parent() {
35 dir.join_normalized(name).to_string()
36 } else {
37 name.to_string()
38 }
39 };
40
41 if self.modules.contains(&full) {
42 Ok(full)
43 } else {
44 Err(Error::new_resolving(base, name))
45 }
46 }
47}