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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
use serde::{Deserialize, Serialize};

/// Parsed representation of a WebC package source.
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, schemars::JsonSchema, Hash)]
pub struct WebcIdent {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repository: Option<url::Url>,
    pub namespace: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tag: Option<String>,
}

impl WebcIdent {
    /// Build the ident for a package.
    ///
    /// Format: NAMESPACE/NAME[@version|hash]
    ///
    /// If prefer_hash is true, the ident will use the signature hash instead of
    /// the version if both are available.
    pub fn build_identifier(&self) -> String {
        let mut ident = format!("{}/{}", self.namespace, self.name);

        if let Some(tag) = &self.tag {
            ident.push('@');
            ident.push_str(tag);
        }
        ident
    }

    /// The the url where the webc package can be downloaded.
    ///
    /// NOTE: returns [`Option::None`] if [`Self::repository`] is not set.
    ///
    /// Private packages will also require an auth token for downloading.
    pub fn build_download_url(&self) -> Option<url::Url> {
        let mut url = self.repository.as_ref()?.clone();
        let ident = self.build_identifier();
        let original_path = url.path().strip_suffix('/').unwrap_or(url.path());
        let final_path = format!("{original_path}/{ident}");

        url.set_path(&final_path);
        Some(url)
    }

    /// The the url where the webc package can be downloaded.
    ///
    /// Private packages will also require an auth token for downloading.
    pub fn build_download_url_with_default_registry(&self, default_reg: &url::Url) -> url::Url {
        let mut url = self
            .repository
            .as_ref()
            .cloned()
            .unwrap_or_else(|| default_reg.clone());
        let ident = self.build_identifier();
        let original_path = url.path().strip_suffix('/').unwrap_or(url.path());
        let final_path = format!("{original_path}/{ident}");

        url.set_path(&final_path);
        url
    }

    pub fn parse(value: &str) -> Result<Self, WebcParseError> {
        let (rest, tag_opt) = value
            .trim()
            .rsplit_once('@')
            .map(|(x, y)| (x, if y.is_empty() { None } else { Some(y) }))
            .unwrap_or((value, None));

        let mut parts = rest.rsplit('/');

        let name = parts
            .next()
            .map(|x| x.trim())
            .filter(|x| !x.is_empty())
            .ok_or_else(|| WebcParseError::new(value, "package name is required"))?;

        let namespace = parts
            .next()
            .map(|x| x.trim())
            .filter(|x| !x.is_empty())
            .ok_or_else(|| WebcParseError::new(value, "package namespace is required"))?;

        let rest = parts.rev().collect::<Vec<_>>().join("/");
        let repository = if rest.is_empty() {
            None
        } else {
            let registry = rest.trim();
            let full_registry =
                if registry.starts_with("http://") || registry.starts_with("https://") {
                    registry.to_string()
                } else {
                    format!("https://{}", registry)
                };

            let registry_url = url::Url::parse(&full_registry)
                .map_err(|e| WebcParseError::new(value, format!("invalid registry url: {}", e)))?;
            Some(registry_url)
        };

        Ok(Self {
            repository,
            namespace: namespace.to_string(),
            name: name.to_string(),
            tag: tag_opt.map(|x| x.to_string()),
        })
    }
}

impl std::fmt::Display for WebcIdent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(url) = self.build_download_url() {
            write!(f, "{}", url)
        } else {
            write!(f, "{}", self.build_identifier())
        }
    }
}

/// Wrapper around [`WebcPackageIdentifierV1`].
///
/// The inner value is serialized and deserialized as a [`String`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StringWebcIdent(pub WebcIdent);

impl StringWebcIdent {
    pub fn parse(value: &str) -> Result<Self, WebcParseError> {
        Ok(Self(WebcIdent::parse(value)?))
    }
}

impl std::fmt::Display for StringWebcIdent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl schemars::JsonSchema for StringWebcIdent {
    fn schema_name() -> String {
        "StringWebcPackageIdent".to_string()
    }

    fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
        schemars::schema::Schema::Object(schemars::schema::SchemaObject {
            instance_type: Some(schemars::schema::InstanceType::String.into()),
            ..Default::default()
        })
    }
}

impl From<StringWebcIdent> for WebcIdent {
    fn from(x: StringWebcIdent) -> Self {
        x.0
    }
}

impl From<WebcIdent> for StringWebcIdent {
    fn from(x: WebcIdent) -> Self {
        Self(x)
    }
}

impl serde::Serialize for StringWebcIdent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let val = self.0.to_string();
        serializer.serialize_str(&val)
    }
}

impl<'de> serde::Deserialize<'de> for StringWebcIdent {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let ident = WebcIdent::parse(&s).map_err(|e| serde::de::Error::custom(e.to_string()))?;
        Ok(Self(ident))
    }
}

impl std::str::FromStr for StringWebcIdent {
    type Err = WebcParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

#[derive(PartialEq, Eq, Debug)]
pub struct WebcParseError {
    value: String,
    message: String,
}

impl WebcParseError {
    fn new(value: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            message: message.into(),
        }
    }
}

impl std::fmt::Display for WebcParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "could not parse webc package specifier '{}': {}",
            self.value, self.message
        )
    }
}

impl std::error::Error for WebcParseError {}

#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, schemars::JsonSchema)]
pub struct WebcPackagePathV1 {
    /// Volume the file is contained in.
    /// (webc packages can have multiple file volumes)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub volume: Option<String>,
    pub path: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_webc_ident() {
        // Success cases.

        assert_eq!(
            WebcIdent::parse("ns/name").unwrap(),
            WebcIdent {
                repository: None,
                namespace: "ns".to_string(),
                name: "name".to_string(),
                tag: None,
            }
        );

        assert_eq!(
            WebcIdent::parse("ns/name@").unwrap(),
            WebcIdent {
                repository: None,
                namespace: "ns".to_string(),
                name: "name".to_string(),
                tag: None,
            },
            "empty tag should be parsed as None"
        );

        assert_eq!(
            WebcIdent::parse("ns/name@tag").unwrap(),
            WebcIdent {
                repository: None,
                namespace: "ns".to_string(),
                name: "name".to_string(),
                tag: Some("tag".to_string()),
            }
        );

        assert_eq!(
            WebcIdent::parse("reg.com/ns/name").unwrap(),
            WebcIdent {
                repository: Some(url::Url::parse("https://reg.com").unwrap()),
                namespace: "ns".to_string(),
                name: "name".to_string(),
                tag: None,
            }
        );

        assert_eq!(
            WebcIdent::parse("reg.com/ns/name@tag").unwrap(),
            WebcIdent {
                repository: Some(url::Url::parse("https://reg.com").unwrap()),
                namespace: "ns".to_string(),
                name: "name".to_string(),
                tag: Some("tag".to_string()),
            }
        );

        assert_eq!(
            WebcIdent::parse("https://reg.com/ns/name").unwrap(),
            WebcIdent {
                repository: Some(url::Url::parse("https://reg.com").unwrap()),
                namespace: "ns".to_string(),
                name: "name".to_string(),
                tag: None,
            }
        );

        assert_eq!(
            WebcIdent::parse("https://reg.com/ns/name@tag").unwrap(),
            WebcIdent {
                repository: Some(url::Url::parse("https://reg.com").unwrap()),
                namespace: "ns".to_string(),
                name: "name".to_string(),
                tag: Some("tag".to_string()),
            }
        );

        assert_eq!(
            WebcIdent::parse("http://reg.com/ns/name").unwrap(),
            WebcIdent {
                repository: Some(url::Url::parse("http://reg.com").unwrap()),
                namespace: "ns".to_string(),
                name: "name".to_string(),
                tag: None,
            }
        );

        assert_eq!(
            WebcIdent::parse("http://reg.com/ns/name@tag").unwrap(),
            WebcIdent {
                repository: Some(url::Url::parse("http://reg.com").unwrap()),
                namespace: "ns".to_string(),
                name: "name".to_string(),
                tag: Some("tag".to_string()),
            }
        );

        // Failure cases.

        assert_eq!(
            WebcIdent::parse("alpha"),
            Err(WebcParseError::new(
                "alpha",
                "package namespace is required"
            ))
        );

        assert_eq!(
            WebcIdent::parse(""),
            Err(WebcParseError::new("", "package name is required"))
        );
    }

    #[test]
    fn test_serde_serialize_webc_str_ident_with_repo() {
        // Serialize
        let ident = StringWebcIdent(WebcIdent {
            repository: Some(url::Url::parse("https://wapm.io").unwrap()),
            namespace: "ns".to_string(),
            name: "name".to_string(),
            tag: None,
        });

        let raw = serde_json::to_string(&ident).unwrap();
        assert_eq!(raw, "\"https://wapm.io/ns/name\"");

        let ident2 = serde_json::from_str::<StringWebcIdent>(&raw).unwrap();
        assert_eq!(ident, ident2);
    }

    #[test]
    fn test_serde_serialize_webc_str_ident_without_repo() {
        // Serialize
        let ident = StringWebcIdent(WebcIdent {
            repository: None,
            namespace: "ns".to_string(),
            name: "name".to_string(),
            tag: None,
        });

        let raw = serde_json::to_string(&ident).unwrap();
        assert_eq!(raw, "\"ns/name\"");

        let ident2 = serde_json::from_str::<StringWebcIdent>(&raw).unwrap();
        assert_eq!(ident, ident2);
    }
}