spinne_core/traverse/
resolver.rs

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
use std::path::PathBuf;

use oxc_resolver::{Resolution, ResolveOptions, Resolver, TsconfigOptions, TsconfigReferences};

pub struct ProjectResolver {
    tsconfig_path: Option<PathBuf>,
}

impl ProjectResolver {
    pub fn new(tsconfig_path: Option<PathBuf>) -> Self {
        Self { tsconfig_path }
    }

    /// resolve a relative file path to an absolute file path
    ///
    /// dir: is the directory of the file that has the import statement
    /// specifier: is the relative file path that the import statement is importing
    /// tsconfig: is the path to the tsconfig.json file that contains the tsconfig options and tsconfigPaths
    ///
    /// # Example
    ///
    /// ```
    /// use std::path::PathBuf;
    /// use spinne_core::ProjectResolver;
    ///
    /// let dir = PathBuf::from("/Users/tim/projects/spinne/src/index.ts");
    /// let resolver = ProjectResolver::new(None);
    /// let resolution = resolver.resolve(&dir, "./components/Button");
    /// ```
    pub fn resolve(&self, dir: &PathBuf, specifier: &str) -> Result<Resolution, String> {
        let options = ResolveOptions {
            tsconfig: self.tsconfig_path.as_ref().map(|tsconfig| TsconfigOptions {
                config_file: tsconfig.to_path_buf(),
                references: TsconfigReferences::Auto,
            }),
            condition_names: vec!["node".to_string(), "import".to_string()],
            extensions: vec![
                ".ts".to_string(),
                ".tsx".to_string(),
                ".js".to_string(),
                ".jsx".to_string(),
            ],
            extension_alias: vec![(
                ".js".to_string(),
                vec![".ts".to_string(), ".js".to_string()],
            )],
            ..ResolveOptions::default()
        };

        match Resolver::new(options).resolve(dir, &specifier) {
            Ok(resolved_path) => Ok(resolved_path),
            Err(e) => Err(e.to_string()),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use tempfile::TempDir;

    use super::*;

    #[test]
    fn test_resolve_file_path() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();

        let src_dir = root.join("src");
        let components_dir = src_dir.join("components");
        fs::create_dir_all(&src_dir).unwrap();
        fs::create_dir_all(&components_dir).unwrap();

        let button_file = components_dir.join("Button.tsx");
        let index_file = components_dir.join("index.ts");
        fs::write(
            &button_file,
            "export function Button() { return <div>Button</div>; }",
        )
        .unwrap();
        fs::write(&index_file, "import { Button } from './Button';").unwrap();

        let specifier = "./components/Button";
        let resolver = ProjectResolver::new(None);
        let resolution = resolver.resolve(&src_dir, &specifier);

        assert!(resolution.is_ok());
        assert_eq!(
            resolution.unwrap().path(),
            components_dir.join("Button.tsx")
        );
    }

    #[test]
    fn test_resolve_file_path_with_tsconfig_paths() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();

        let src_dir = root.join("src");
        let components_dir = src_dir.join("components");
        fs::create_dir_all(&src_dir).unwrap();
        fs::create_dir_all(&components_dir).unwrap();

        let button_file = components_dir.join("Button.tsx");
        let index_file = components_dir.join("index.ts");
        fs::write(
            &button_file,
            "export function Button() { return <div>Button</div>; }",
        )
        .unwrap();
        fs::write(&index_file, "import { Button } from './Button';").unwrap();

        let tsconfig_path = root.join("tsconfig.json");
        fs::write(
            &tsconfig_path,
            r#"{
        "compilerOptions": {
          "baseUrl": ".",
          "paths": {
            "@components/*": ["./src/components/*"]
          }
        }
      }"#,
        )
        .unwrap();
        let specifier = "@components/Button";
        let resolver = ProjectResolver::new(Some(tsconfig_path));
        let resolution = resolver.resolve(&src_dir, &specifier);

        assert!(resolution.is_ok());
        assert_eq!(
            resolution.unwrap().path(),
            components_dir.join("Button.tsx")
        );
    }

    #[test]
    fn test_resolve_file_path_with_node_modules() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();

        let src_dir = root.join("src");
        let node_modules_dir = root.join("node_modules");
        fs::create_dir_all(&src_dir).unwrap();
        fs::create_dir_all(&node_modules_dir).unwrap();

        let framer_motion_dir = node_modules_dir.join("framer-motion");
        fs::create_dir_all(&framer_motion_dir).unwrap();
        fs::write(
            &framer_motion_dir.join("index.js"),
            "module.exports = { motion: () => <div>Framer Motion</div> };",
        )
        .unwrap();

        let specifier = "framer-motion";
        let resolver = ProjectResolver::new(None);
        let resolution = resolver.resolve(&src_dir, &specifier);

        assert!(resolution.is_ok());
        assert_eq!(
            resolution.unwrap().path(),
            node_modules_dir.join("framer-motion").join("index.js")
        );
    }
}