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
use std::{io, path::PathBuf, sync::Arc};
use thiserror::Error;

/// All resolution errors
///
/// `thiserror` is used to display meaningful error messages.
#[derive(Debug, Clone, PartialEq, Error)]
pub enum ResolveError {
    /// Ignored path
    ///
    /// Derived from ignored path (false value) from browser field in package.json
    /// ```json
    /// {
    ///     "browser": {
    ///         "./module": false
    ///     }
    /// }
    /// ```
    /// See <https://github.com/defunctzombie/package-browser-field-spec#ignore-a-module>
    #[error("Path is ignored {0}")]
    Ignored(PathBuf),

    /// Module not found
    #[error("Cannot find module '{0}'")]
    NotFound(/* specifier */ String),

    /// Tsconfig not found
    #[error("Tsconfig not found {0}")]
    TsconfigNotFound(PathBuf),

    #[error("{0}")]
    IOError(IOError),

    /// Node.js builtin modules
    ///
    /// This is an error due to not being a Node.js runtime.
    /// The `alias` option can be used to resolve a builtin module to a polyfill.
    #[error("Builtin module {0}")]
    Builtin(String),

    /// All of the aliased extension are not found
    #[error("All of the aliased extension are not found")]
    ExtensionAlias,

    /// The provided path specifier cannot be parsed
    #[error("{0}")]
    Specifier(SpecifierError),

    /// JSON parse error
    #[error("{0:?}")]
    JSON(JSONError),

    /// Restricted by `ResolveOptions::restrictions`
    #[error(r#"Path "{0}" restricted by {0}"#)]
    Restriction(PathBuf, PathBuf),

    #[error(r#"Invalid module "{0}" specifier is not a valid subpath for the "exports" resolution of {1}"#)]
    InvalidModuleSpecifier(String, PathBuf),

    #[error(r#"Invalid "exports" target "{0}" defined for '{1}' in the package config {2}"#)]
    InvalidPackageTarget(String, String, PathBuf),

    #[error(r#"Package subpath '{0}' is not defined by "exports" in {1}"#)]
    PackagePathNotExported(String, PathBuf),

    #[error(r#"Invalid package config "{0}", "exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only."#)]
    InvalidPackageConfig(PathBuf),

    #[error(r#"Default condition should be last one in "{0}""#)]
    InvalidPackageConfigDefault(PathBuf),

    #[error(r#"Expecting folder to folder mapping. "{0}" should end with "/"#)]
    InvalidPackageConfigDirectory(PathBuf),

    #[error(r#"Package import specifier "{0}" is not defined in package {1}"#)]
    PackageImportNotDefined(String, PathBuf),

    #[error("{0} is unimplemented")]
    Unimplemented(&'static str),

    /// Occurs when alias paths reference each other.
    #[error("Recursion in resolving")]
    Recursion,
}

impl ResolveError {
    pub fn is_ignore(&self) -> bool {
        matches!(self, Self::Ignored(_))
    }

    pub(crate) fn from_serde_json_error(path: PathBuf, error: &serde_json::Error) -> Self {
        Self::JSON(JSONError {
            path,
            message: error.to_string(),
            line: error.line(),
            column: error.column(),
        })
    }
}

/// Error for [ResolveError::Specifier]
#[derive(Debug, Clone, Eq, PartialEq, Error)]
pub enum SpecifierError {
    #[error("The specifiers must be a non-empty string. Received ''")]
    Empty,
}

/// JSON error from [serde_json::Error]
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct JSONError {
    pub path: PathBuf,
    pub message: String,
    pub line: usize,
    pub column: usize,
}

#[derive(Debug, Clone, Error)]
#[error("{0}")]
pub struct IOError(Arc<io::Error>);

impl PartialEq for IOError {
    fn eq(&self, other: &Self) -> bool {
        self.0.kind() == other.0.kind()
    }
}

impl From<IOError> for std::io::Error {
    fn from(error: IOError) -> Self {
        let io_error = error.0.as_ref();
        Self::new(io_error.kind(), io_error.to_string())
    }
}

impl From<io::Error> for ResolveError {
    fn from(err: io::Error) -> Self {
        Self::IOError(IOError(Arc::new(err)))
    }
}