Skip to main content

compmd_host/registry/
options.rs

1//! What a host sets for its resolutions: its registries, its size cap, and the packs its policy denies.
2
3use std::collections::BTreeMap;
4
5use compmd_pack::PackName;
6use serde::{Deserialize, Serialize};
7
8/// The size cap when the host sets none: Mermaid 12's module as one file is 7 MB, with its layout engines.
9pub const DEFAULT_MAX_PACK_SIZE: u64 = 10_000_000;
10
11/// A pack the host's policy denies, all versions or those in `version`, as its configuration's `deny` writes it.
12#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
13pub struct Denied {
14    /// The pack.
15    pub pack: PackName,
16    /// The range denied, read as an import's is; all versions when absent.
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub version: Option<String>,
19}
20
21/// A host's settings for resolving.
22#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "camelCase")]
24pub struct Options {
25    /// The registries by scope, `@kit`, with `*` for every other scope, each a URL ending in `/`.
26    pub registries: BTreeMap<String, String>,
27    /// The largest unpacked size of a pack, in bytes.
28    #[serde(default = "default_max_pack_size")]
29    pub max_pack_size: u64,
30    /// The packs the host's policy denies: a denied version is downloaded for nothing, so it never is.
31    #[serde(default)]
32    pub deny: Vec<Denied>,
33}
34
35/// The size cap when the host sets none.
36const fn default_max_pack_size() -> u64 {
37    DEFAULT_MAX_PACK_SIZE
38}
39
40impl Options {
41    /// The options with `registries`, the default size cap and no pack denied.
42    #[must_use]
43    pub fn new(registries: BTreeMap<String, String>) -> Self {
44        Self {
45            registries,
46            max_pack_size: DEFAULT_MAX_PACK_SIZE,
47            deny: Vec::new(),
48        }
49    }
50
51    /// The registry of `pack`: its scope's, else `*`'s; `None` when no registry is set for it.
52    #[must_use]
53    pub fn registry_of(&self, pack: &PackName) -> Option<&str> {
54        self.registry_of_scope(&format!("@{}", pack.scope()))
55    }
56
57    /// The registry of the packs of `scope` (`@kit`): its own, else `*`'s; `None` when no registry is set for it.
58    #[must_use]
59    pub fn registry_of_scope(&self, scope: &str) -> Option<&str> {
60        self.registries
61            .get(scope)
62            .or_else(|| self.registries.get("*"))
63            .map(String::as_str)
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70
71    #[test]
72    fn a_pack_gets_its_scopes_registry_else_every_other_scopes() {
73        let mut options = Options::new(BTreeMap::from([
74            ("@kit".to_owned(), "https://npm.kit.example/".to_owned()),
75            ("*".to_owned(), "https://registry.npmjs.org/".to_owned()),
76        ]));
77        let pack = |name: &str| name.parse::<PackName>().expect("a name");
78        assert_eq!(
79            options.registry_of(&pack("@kit/mermaid")),
80            Some("https://npm.kit.example/")
81        );
82        assert_eq!(
83            options.registry_of(&pack("@acme/maps")),
84            Some("https://registry.npmjs.org/")
85        );
86        assert_eq!(
87            options.registry_of_scope("@kit"),
88            Some("https://npm.kit.example/")
89        );
90        options.registries.remove("*");
91        assert_eq!(options.registry_of(&pack("@acme/maps")), None);
92        assert_eq!(options.registry_of_scope("@acme"), None);
93        assert_eq!(options.max_pack_size, DEFAULT_MAX_PACK_SIZE);
94        let read: Options = serde_json::from_str(r#"{"registries": {}}"#).expect("options");
95        assert_eq!(
96            (read.max_pack_size, read.deny),
97            (DEFAULT_MAX_PACK_SIZE, Vec::new())
98        );
99    }
100}