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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
use crate::map::{ExportsField, Field, ImportsField, PathTreeNode};
use crate::{AliasMap, RResult, Resolver};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;

#[derive(Clone, Debug)]
pub enum SideEffects {
    Bool(bool),
    Array(Vec<String>),
}

#[derive(Clone, Debug)]
pub struct PkgFileInfo {
    /// The path to the directory where the description file located.
    /// It not a property in package.json.
    pub abs_dir_path: PathBuf,
    pub name: Option<String>,
    pub version: Option<String>,
    pub alias_fields: HashMap<String, AliasMap>,
    pub exports_field_tree: Option<Arc<PathTreeNode>>,
    pub imports_field_tree: Option<Arc<PathTreeNode>>,
    pub side_effects: Option<SideEffects>,
    pub raw: serde_json::Value,
}

impl Resolver {
    #[tracing::instrument]
    fn parse_description_file(&self, dir: &Path, file_path: PathBuf) -> RResult<PkgFileInfo> {
        #[cfg(debug_assertions)]
        {
            // ensure that the same package.json is not parsed twice
            if self.dbg_read_map.contains_key(&file_path) {
                println!("{:?}", self.cache.file_dir_to_pkg_info);
                println!("{:?}", self.dbg_read_map);
                panic!(
                    "Had try to parse same package.json, {}",
                    file_path.display()
                )
            }
            self.dbg_read_map.insert(&file_path, true);
        }

        let str = tracing::debug_span!("read_to_string").in_scope(|| {
            self.fs
                .read_to_string(&file_path)
                .map_err(|_| format!("Open {} failed", file_path.display()))
        })?;
        let json: serde_json::Value =
            tracing::debug_span!("serde_json_from_str").in_scope(|| {
                serde_json::from_str(&str)
                    .map_err(|_| format!("Parse {} failed", file_path.display()))
            })?;

        let mut alias_fields = HashMap::new();

        if let Some(value) = json.get("browser") {
            if let Some(map) = value.as_object() {
                for (key, value) in map {
                    if let Some(b) = value.as_bool() {
                        assert!(!b);
                        alias_fields.insert(key.to_string(), AliasMap::Ignored);
                    } else if let Some(s) = value.as_str() {
                        alias_fields.insert(key.to_string(), AliasMap::Target(s.to_string()));
                    }
                }
            }
        }

        let exports_field_tree = if let Some(value) = json.get("exports") {
            let key = serde_json::to_string(&value).unwrap_or_else(|_| {
                panic!("Parse {}/exports to hash key failed", file_path.display())
            });
            if let Some(tree) = self.cache.exports_content_to_tree.get(&key) {
                Some(tree.clone())
            } else {
                let tree = Arc::new(ExportsField::build_field_path_tree(value)?);
                self.cache.exports_content_to_tree.insert(key, tree.clone());
                Some(tree)
            }
        } else {
            None
        };

        let imports_field_tree = if let Some(value) = json.get("imports") {
            let key = serde_json::to_string(&value).unwrap_or_else(|_| {
                panic!("Parse {}/imports to hash key failed", file_path.display())
            });
            if let Some(tree) = self.cache.imports_content_to_tree.get(&key) {
                Some(tree.clone())
            } else {
                let tree = Arc::new(ImportsField::build_field_path_tree(value)?);
                self.cache.exports_content_to_tree.insert(key, tree.clone());
                Some(tree)
            }
        } else {
            None
        };

        let name = json
            .get("name")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let side_effects: Option<SideEffects> =
            json.get("sideEffects").map_or(Ok(None), |value| {
                // TODO: should optimized
                if let Some(b) = value.as_bool() {
                    Ok(Some(SideEffects::Bool(b)))
                } else if let Some(vec) = value.as_array() {
                    let mut ans = vec![];
                    for value in vec {
                        if let Some(str) = value.as_str() {
                            ans.push(str.to_string());
                        } else {
                            return Err(format!(
                                "sideEffects in {} had unexpected value {}",
                                file_path.display(),
                                value
                            ));
                        }
                    }
                    Ok(Some(SideEffects::Array(ans)))
                } else {
                    Err(format!(
                        "sideEffects in {} had unexpected value {}",
                        file_path.display(),
                        value
                    ))
                }
            })?;

        let version = json
            .get("version")
            .and_then(|value| value.as_str())
            .map(|str| str.to_string());

        Ok(PkgFileInfo {
            name,
            version,
            abs_dir_path: dir.to_path_buf(),
            alias_fields,
            exports_field_tree,
            imports_field_tree,
            side_effects,
            raw: json,
        })
    }

    pub fn load_side_effects(
        &self,
        path: &Path,
    ) -> RResult<Option<(PathBuf, Option<SideEffects>)>> {
        Ok(self.load_pkg_file(path)?.map(|pkg_info| {
            (
                pkg_info
                    .abs_dir_path
                    .join(self.options.description_file.as_ref().unwrap()),
                pkg_info.side_effects.clone(),
            )
        }))
    }

    #[tracing::instrument]
    pub(crate) fn load_pkg_file(&self, path: &Path) -> RResult<Option<Arc<PkgFileInfo>>> {
        if self.options.description_file.is_none() {
            return Ok(None);
        }
        // Because the key in `self.cache.file_dir_to_pkg_info` represents directory.
        // So this step is ensure `path` pointed to directory.
        if !path.is_dir() {
            return match path.parent() {
                Some(dir) => self.load_pkg_file(dir),
                None => Err(Resolver::raise_tag()),
            };
        }

        let description_file_name = self.options.description_file.as_ref().unwrap();
        let description_file_path = path.join(description_file_name);
        let need_find_up = if let Some(r#ref) = self.cache.file_dir_to_pkg_info.get(path) {
            // if pkg_info_cache contain this key
            if !self.fs.need_update(&description_file_path)? {
                // and not modified, then return
                return Ok(r#ref.clone());
            } else {
                #[cfg(debug_assertions)]
                {
                    self.dbg_read_map.remove(&description_file_path);
                }

                false
            }
        } else {
            !description_file_path.is_file()
        };

        // pkg_info_cache do **not** contain this key
        // or this file had modified
        if need_find_up {
            // find the closest directory witch contains description file
            if let Some(target_dir) = Self::find_up(path, description_file_name) {
                return self.load_pkg_file(&target_dir);
            } else {
                // it means all paths during from the `path` to root pointed None.
                // cache it
                let mut path = path;
                loop {
                    if path.is_dir() {
                        self.cache
                            .file_dir_to_pkg_info
                            .insert(path.to_path_buf(), None);
                        match path.parent() {
                            Some(parent) => path = parent,
                            None => return Ok(None),
                        }
                    }
                }
            }
        }

        let pkg_info = Some(Arc::new(
            self.parse_description_file(path, description_file_path)?,
        ));

        self.cache
            .file_dir_to_pkg_info
            .insert(path.to_path_buf(), pkg_info.clone());

        Ok(pkg_info)
    }
}