Skip to main content

compmd/
host.rs

1//! What a host provides. The processor does no I/O: it reads the document's files, the packs, remote and `host:` data
2//! and the time zones through these traits, each on its own, so a stage takes only the ones it uses and a host can
3//! reuse an implementation, such as a pack store or a time zone database, in another host. `()` implements each as
4//! "none", and maps implement the data traits for what a host holds in memory: `HashMap<String, String>` for files,
5//! `HashMap<String, Vec<LoadedRelease>>` for packs, `HashMap<String, Fetched>` for remote data by URL and
6//! `HashMap<String, Json>` for host data by source.
7//!
8//! ```
9//! use compmd::host::{Packs, Release};
10//! use compmd::pack::{PackName, Place};
11//! use semver::Version;
12//!
13//! /// One pack, `@acme/kit@1.0.0`, with its manifest alone.
14//! struct Kit;
15//!
16//! impl Packs for Kit {
17//!     fn releases(&self, pack: &PackName) -> Vec<Release> {
18//!         let kit = Release { version: Version::new(1, 0, 0), integrity: None, broken: None };
19//!         if *pack == "@acme/kit" { vec![kit] } else { Vec::new() }
20//!     }
21//!
22//!     fn pack_file(&self, place: &Place) -> Option<String> {
23//!         let found = place.to_string() == "@acme/kit@1.0.0/package.json";
24//!         found.then(|| r#"{"name": "@acme/kit", "version": "1.0.0"}"#.to_string())
25//!     }
26//! }
27//! ```
28
29use compmd_pack::{Integrity, PackName, Place};
30use semver::Version;
31use serde::{Deserialize, Serialize};
32use serde_json::Value as Json;
33use std::collections::{HashMap, HashSet};
34use std::hash::BuildHasher;
35use std::rc::Rc;
36
37/// The files of the document's root folder.
38pub trait Files {
39    /// The file at `path` under the document's root folder, which relative paths can't leave (spec §8.6), or `None`
40    /// when there is none. `path` is `/`-separated.
41    fn file(&self, path: &str) -> Option<String>;
42}
43
44/// The packs a document can import (spec §6.4): npm packages with a `package.json` and a CompMD document.
45pub trait Packs {
46    /// Every release of `pack`, in any order.
47    fn releases(&self, pack: &PackName) -> Vec<Release>;
48
49    /// The file at `place`, in a release of a pack: `package.json`, the pack's document, or a file it imports.
50    fn pack_file(&self, place: &Place) -> Option<String>;
51
52    /// Whether the host is still getting `pack` (spec §6.4): an import of it that no release matches is pending, not
53    /// F026, and its names' uses render their fallbacks marked as pending. None is, by default.
54    fn pending(&self, _pack: &PackName) -> bool {
55        false
56    }
57}
58
59/// Remote data (the `remote data` feature, spec §8.6).
60pub trait Fetch {
61    /// What the host fetched for `url`, or `None` when it couldn't. Only `https:` URLs of origins the host allows
62    /// reach this; the host fetches without credentials, and decides how long a copy is kept (`cache`).
63    fn fetch(&self, url: &str) -> Option<Fetched>;
64
65    /// Whether the host is still getting `url` (spec §8.6): when it can't give it yet, the import loads its
66    /// `fallback` or `null`, without F026. None is, by default.
67    fn pending(&self, _url: &str) -> bool {
68        false
69    }
70}
71
72/// Data a host provides (spec §8.6).
73pub trait Data {
74    /// The data `source` names, as JSON, or `None` when the host doesn't provide it. `source` is what follows
75    /// `host:` in a `from`, such as `tasks?status=open`.
76    fn data(&self, source: &str) -> Option<Json>;
77
78    /// Whether the host is still getting `source`, as [`Fetch::pending`] for a URL. None is, by default.
79    fn pending(&self, _source: &str) -> bool {
80        false
81    }
82}
83
84/// The time zones the host knows: the browser's `Intl`, an app's own zone data. The crate carries none.
85pub trait Time {
86    /// The offset of `zone` from UTC at `at`, in seconds east of UTC, or `None` when the zone is unknown. `zone` is
87    /// `md.tz`: an IANA name such as `Europe/Berlin`, or `UTC`; `at` is in seconds since 1970-01-01T00:00:00Z.
88    fn offset(&self, zone: &str, at: i64) -> Option<i32>;
89}
90
91/// A release of a pack, as a registry lists it.
92#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
93pub struct Release {
94    /// Its version.
95    pub version: Version,
96    /// The integrity hash the registry publishes for it (`sha512-…`), which an import's `integrity` must equal.
97    #[serde(default)]
98    pub integrity: Option<Integrity>,
99    /// Why its files can't be used, when the host found they don't match its integrity: an import that resolves to
100    /// it is F035 with this reason.
101    #[serde(default)]
102    pub broken: Option<String>,
103}
104
105/// A release of a pack with all its files, as an in-memory host holds it: `HashMap<String, Vec<LoadedRelease>>` is a
106/// registry of packs by name.
107#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
108pub struct LoadedRelease {
109    /// The release.
110    #[serde(flatten)]
111    pub release: Release,
112    /// Its files by path: `package.json`, the pack's document, and what it imports.
113    pub files: HashMap<String, String>,
114}
115
116/// What a render needs that the host hasn't given, for it to get before it processes or loads: each once, in the
117/// order they are first written.
118#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
119pub struct Needed {
120    /// The `https:` URLs [`Fetch`] will be asked for, their values filled in.
121    pub remote: Vec<String>,
122    /// The sources [`Data`] will be asked for, without `host:`.
123    pub host: Vec<String>,
124    /// The `https:` URLs not fetched because their origin isn't one the host allows (F028), their values filled in:
125    /// for a host that asks the reader about new origins before it fetches (spec §8.6), then validates again with the
126    /// ones allowed.
127    pub disallowed: Vec<String>,
128    /// The packs imported, by the document or by a pack it loaded, that no release in [`Packs`] matches, for a host
129    /// that gets packs from a registry (spec §6.4) to fetch before it resolves again; then the library packs those
130    /// packs name in `peerDependencies` that none matches (companion, section 5). Packs the host's policy refuses
131    /// aren't listed, nor are imports that name no pack.
132    pub packs: Vec<NeededPack>,
133}
134
135/// What a render treated as pending (spec §6.4, §8.6): of what it needed, what the host said it was still getting,
136/// for a host's UI ("loading 1 pack"). Each once, in the order they are first written.
137#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
138pub struct Pending {
139    /// The packs.
140    pub packs: Vec<PackName>,
141    /// The `https:` URLs, their values filled in.
142    pub remote: Vec<String>,
143    /// The `host:` sources, without `host:`.
144    pub host: Vec<String>,
145}
146
147/// What a host keys its cached copy of a data import's source by (spec §8.6): the source's final URL or path, its
148/// inputs filled in, so a copy is reused only for the same values.
149#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
150pub struct CacheKey {
151    /// The import's name, its `as`: `sales` for `md.data.sales`.
152    #[serde(rename = "as")]
153    pub name: String,
154    /// An `https:` URL, a `host:` source with `host:`, or a file's path: in the root folder (`data/sales.csv`) or in
155    /// a pack (`@acme/kit@1.4.2/icons.json`).
156    pub key: String,
157}
158
159/// A pack import, or a library a pack names, that [`Packs`] has no release for.
160#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
161pub struct NeededPack {
162    /// The pack, `@acme/kit`.
163    pub pack: PackName,
164    /// The version or range after the name, as written (`1`, `^1.4.2`, `1.4.2`); `*` when none is. For a library,
165    /// the range in `peerDependencies`.
166    pub range: String,
167    /// The import's `integrity`, when it pins one with an exact version: the release's tarball must have this hash.
168    #[serde(skip_serializing_if = "Option::is_none")]
169    pub integrity: Option<Integrity>,
170    /// Whether it is a library pack a pack names, of which the processor takes the newest release that matches every
171    /// range asked for it: a host that fetches one fetches that version when the registry has it.
172    #[serde(skip_serializing_if = "std::ops::Not::not")]
173    pub library: bool,
174}
175
176/// The newest of `versions` that `range` takes, as the processor reads the version or range after a pack's name in
177/// an import's `from` (spec §6.1): `1.4.2` is exactly that version, `1` and `^1.4` ranges, `*` any. `None` when none
178/// matches, or `range` isn't one. A host that fetches the packs [`Needed`] lists picks a version with this, so the
179/// processor takes the release it was given.
180///
181/// ```
182/// use compmd::host::newest_matching;
183/// use semver::Version;
184///
185/// let versions = ["1.4.2", "1.5.0", "2.0.0"].map(|v| Version::parse(v).unwrap());
186/// assert_eq!(newest_matching("1", &versions), Some(&versions[1]));
187/// assert_eq!(newest_matching("1.4.2", &versions), Some(&versions[0]));
188/// assert_eq!(newest_matching("^3", &versions), None);
189/// ```
190#[must_use]
191pub fn newest_matching<'v>(range: &str, versions: &'v [Version]) -> Option<&'v Version> {
192    let (range, _) = crate::resolve::range(range)?;
193    versions
194        .iter()
195        .filter(|version| range.matches(version))
196        .max()
197}
198
199/// What a remote source gave.
200#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
201#[serde(rename_all = "camelCase")]
202pub struct Fetched {
203    /// The body, as text.
204    pub text: String,
205    /// The `Content-Type` header, which decides the format; without one, the URL's extension does.
206    pub content_type: Option<String>,
207}
208
209/// No files.
210impl Files for () {
211    fn file(&self, _path: &str) -> Option<String> {
212        None
213    }
214}
215
216/// Files held in memory, as a browser hands them over.
217impl<S: BuildHasher> Files for HashMap<String, String, S> {
218    fn file(&self, path: &str) -> Option<String> {
219        self.get(path).cloned()
220    }
221}
222
223/// No packs.
224impl Packs for () {
225    fn releases(&self, _pack: &PackName) -> Vec<Release> {
226        Vec::new()
227    }
228
229    fn pack_file(&self, _place: &Place) -> Option<String> {
230        None
231    }
232}
233
234/// Packs held in memory, by name.
235impl<S: BuildHasher> Packs for HashMap<String, Vec<LoadedRelease>, S> {
236    fn releases(&self, pack: &PackName) -> Vec<Release> {
237        self.get(pack.as_str())
238            .into_iter()
239            .flatten()
240            .map(|loaded| loaded.release.clone())
241            .collect()
242    }
243
244    fn pack_file(&self, place: &Place) -> Option<String> {
245        self.get(place.release.pack.as_str())?
246            .iter()
247            .find(|loaded| loaded.release.version == place.release.version)?
248            .files
249            .get(place.path.as_str())
250            .cloned()
251    }
252}
253
254/// No remote data: every URL fails, so data imports from URLs load their fallback.
255impl Fetch for () {
256    fn fetch(&self, _url: &str) -> Option<Fetched> {
257        None
258    }
259}
260
261/// Remote data fetched beforehand, by URL.
262impl<S: BuildHasher> Fetch for HashMap<String, Fetched, S> {
263    fn fetch(&self, url: &str) -> Option<Fetched> {
264        self.get(url).cloned()
265    }
266}
267
268/// No host data: every `host:` source is missing.
269impl Data for () {
270    fn data(&self, _source: &str) -> Option<Json> {
271        None
272    }
273}
274
275/// Host data held in memory, by source without `host:`.
276impl<S: BuildHasher> Data for HashMap<String, Json, S> {
277    fn data(&self, source: &str) -> Option<Json> {
278        self.get(source).cloned()
279    }
280}
281
282/// Files a host shares with the processor and keeps a handle to.
283impl<T: Files + ?Sized> Files for Rc<T> {
284    fn file(&self, path: &str) -> Option<String> {
285        (**self).file(path)
286    }
287}
288
289/// Packs a host shares with the processor.
290impl<T: Packs + ?Sized> Packs for Rc<T> {
291    fn releases(&self, pack: &PackName) -> Vec<Release> {
292        (**self).releases(pack)
293    }
294
295    fn pack_file(&self, place: &Place) -> Option<String> {
296        (**self).pack_file(place)
297    }
298
299    fn pending(&self, pack: &PackName) -> bool {
300        (**self).pending(pack)
301    }
302}
303
304/// Remote data a host shares with the processor.
305impl<T: Fetch + ?Sized> Fetch for Rc<T> {
306    fn fetch(&self, url: &str) -> Option<Fetched> {
307        (**self).fetch(url)
308    }
309
310    fn pending(&self, url: &str) -> bool {
311        (**self).pending(url)
312    }
313}
314
315/// Host data a host shares with the processor.
316impl<T: Data + ?Sized> Data for Rc<T> {
317    fn data(&self, source: &str) -> Option<Json> {
318        (**self).data(source)
319    }
320
321    fn pending(&self, source: &str) -> bool {
322        (**self).pending(source)
323    }
324}
325
326/// A host's packs, remote data or host data, `held`, with the sources it is still getting, `pending` (spec §6.4,
327/// §8.6): pack names, URLs, or `host:` sources without `host:`.
328///
329/// ```
330/// use compmd::host::{Packs, WithPending};
331/// use std::collections::HashSet;
332///
333/// let packs = WithPending { held: (), pending: HashSet::from(["@kit/mermaid".to_string()]) };
334/// assert!(packs.pending(&"@kit/mermaid".parse()?));
335/// assert!(!packs.pending(&"@kit/charts".parse()?));
336/// # Ok::<(), compmd::pack::Invalid>(())
337/// ```
338#[derive(Clone, Debug, Default, PartialEq, Eq)]
339pub struct WithPending<T> {
340    /// What the host holds.
341    pub held: T,
342    /// What it is still getting.
343    pub pending: HashSet<String>,
344}
345
346impl<T: Packs> Packs for WithPending<T> {
347    fn releases(&self, pack: &PackName) -> Vec<Release> {
348        self.held.releases(pack)
349    }
350
351    fn pack_file(&self, place: &Place) -> Option<String> {
352        self.held.pack_file(place)
353    }
354
355    fn pending(&self, pack: &PackName) -> bool {
356        self.pending.contains(pack.as_str())
357    }
358}
359
360impl<T: Fetch> Fetch for WithPending<T> {
361    fn fetch(&self, url: &str) -> Option<Fetched> {
362        self.held.fetch(url)
363    }
364
365    fn pending(&self, url: &str) -> bool {
366        self.pending.contains(url)
367    }
368}
369
370impl<T: Data> Data for WithPending<T> {
371    fn data(&self, source: &str) -> Option<Json> {
372        self.held.data(source)
373    }
374
375    fn pending(&self, source: &str) -> bool {
376        self.pending.contains(source)
377    }
378}
379
380/// No time zone data: only `UTC` is known.
381impl Time for () {
382    fn offset(&self, zone: &str, _at: i64) -> Option<i32> {
383        (zone == "UTC").then_some(0)
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390    use serde_json::json;
391
392    fn name(text: &str) -> PackName {
393        text.parse().expect("a pack's name")
394    }
395
396    fn place(text: &str) -> Place {
397        text.parse().expect("a place")
398    }
399
400    #[test]
401    fn the_unit_host_has_nothing_but_utc() {
402        assert_eq!(().file("a.comp.md"), None);
403        assert_eq!(().releases(&name("@acme/kit")), Vec::new());
404        assert_eq!(().pack_file(&place("@acme/kit@1.0.0/a")), None);
405        assert_eq!(().fetch("https://a.org/x.json"), None);
406        assert_eq!(().data("tasks"), None);
407        assert_eq!(().offset("UTC", 0), Some(0));
408        assert_eq!(().offset("Europe/Berlin", 0), None);
409    }
410
411    #[test]
412    fn packs_in_memory_serve_their_releases() {
413        let packs: HashMap<String, Vec<LoadedRelease>> = serde_json::from_value(json!({
414            "@acme/charts": [
415                { "version": "1.4.2", "integrity": "sha512-x", "files": { "package.json": "{}" } },
416                { "version": "1.5.0", "files": {} }
417            ]
418        }))
419        .expect("packs");
420        let releases = packs.releases(&name("@acme/charts"));
421        assert_eq!(releases.len(), 2);
422        assert_eq!(
423            releases[0].integrity,
424            Some("sha512-x".parse().expect("an integrity"))
425        );
426        assert_eq!(
427            packs.pack_file(&place("@acme/charts@1.4.2/package.json")),
428            Some("{}".to_string())
429        );
430        assert_eq!(packs.pack_file(&place("@acme/charts@2.0.0/a")), None);
431        assert_eq!(packs.releases(&name("@acme/maps")), Vec::new());
432    }
433
434    #[test]
435    fn the_newest_matching_version_is_the_processors_choice() {
436        let versions =
437            ["1.0.0", "1.2.0", "2.0.0-beta.1"].map(|v| Version::parse(v).expect("a version"));
438        assert_eq!(
439            newest_matching("*", &versions),
440            Some(&versions[1]),
441            "not a prerelease"
442        );
443        assert_eq!(newest_matching("~1.0", &versions), Some(&versions[0]));
444        assert_eq!(newest_matching("soon", &versions), None);
445        assert_eq!(newest_matching("1", &[]), None);
446    }
447
448    #[test]
449    fn data_in_memory_is_served_by_url_and_source() {
450        let fetched = Fetched {
451            text: "{}".to_string(),
452            content_type: Some("application/json".to_string()),
453        };
454        let remote = HashMap::from([("https://a.org/x.json".to_string(), fetched.clone())]);
455        assert_eq!(remote.fetch("https://a.org/x.json"), Some(fetched));
456        assert_eq!(remote.fetch("https://a.org/y.json"), None);
457        let host = HashMap::from([("tasks".to_string(), json!([1]))]);
458        assert_eq!(host.data("tasks"), Some(json!([1])));
459        assert_eq!(host.data("notes"), None);
460    }
461
462    #[test]
463    fn a_shared_host_serves_what_it_holds() {
464        let files = Rc::new(HashMap::from([("a".to_string(), "A".to_string())]));
465        assert_eq!(files.file("a"), Some("A".to_string()));
466        let none = Rc::new(());
467        assert_eq!(none.releases(&name("@acme/kit")), Vec::new());
468        assert_eq!(none.pack_file(&place("@acme/kit@1.0.0/a")), None);
469        assert_eq!(none.fetch("https://a.org/x.json"), None);
470        assert_eq!(none.data("tasks"), None);
471    }
472}