char/avril

(wip) why'd you have to go and make things so complicaaaaated?

git clone https://git.t4t.associates/char/avril

Charlotte Somsupport data urls1c8ffed

main
1.9 KiB57 linesraw
1use data_url::DataUrl;
2use oxc::span::SourceType;
3
4#[derive(Debug, thiserror::Error)]
5pub(crate) enum DataModuleError {
6    #[error("Invalid data module URL: {0}")]
7    Url(#[from] data_url::DataUrlError),
8    #[error("Unsupported data module MIME type: {0}")]
9    Mime(String),
10    #[error("Invalid base64 in data module: {0}")]
11    Base64(#[from] data_url::forgiving_base64::InvalidBase64),
12}
13
14impl From<DataModuleError> for avril_core::Error {
15    fn from(error: DataModuleError) -> Self {
16        Self::Module(error.to_string())
17    }
18}
19
20pub(crate) struct DataModule<'a> {
21    url: DataUrl<'a>,
22    pub source_type: SourceType,
23}
24
25impl<'a> DataModule<'a> {
26    pub fn parse(name: &'a str) -> Result<Self, DataModuleError> {
27        let url = DataUrl::process(name)?;
28        let mime = url.mime_type();
29        let source_type = match (mime.type_.as_str(), mime.subtype.as_str()) {
30            ("text" | "application", "typescript" | "x-typescript") => {
31                SourceType::ts().with_module(true)
32            }
33            (
34                "text" | "application",
35                "javascript" | "ecmascript" | "x-javascript" | "x-ecmascript",
36            )
37            | (
38                "text",
39                "javascript1.0" | "javascript1.1" | "javascript1.2" | "javascript1.3"
40                | "javascript1.4" | "javascript1.5" | "jscript" | "livescript",
41            ) => SourceType::mjs(),
42            _ => {
43                return Err(DataModuleError::Mime(format!(
44                    "{}/{}",
45                    mime.type_, mime.subtype
46                )));
47            }
48        };
49        Ok(Self { url, source_type })
50    }
51
52    pub fn source(&self) -> Result<String, DataModuleError> {
53        let (bytes, _) = self.url.decode_to_vec()?;
54        // Module scripts are UTF-8 regardless of the MIME charset parameter.
55        Ok(String::from_utf8_lossy(&bytes).into_owned())
56    }
57}