Skip to main content

compmd_host/
manifest.rs

1//! `manifest.json`, the bundle's one description ([hosting], decision 3), which `@compmd/vite` writes and every host
2//! reads, in Rust here and in JavaScript.
3//!
4//! [hosting]: https://github.com/comp-markdown/compmd/blob/main/docs/hosting.md
5
6use std::collections::BTreeMap;
7
8use compmd_pack::{FilePath, Integrity, PackName, ReleaseId};
9use semver::Version;
10use serde::{Deserialize, Serialize};
11
12use crate::frames_hash::FramesHash;
13use crate::manifest_error::ManifestError;
14
15/// The manifest's format this crate reads; a bundle of another is refused, with what to upgrade.
16pub const FORMAT: u32 = 1;
17
18/// A bundle's manifest.
19#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
20pub struct Manifest {
21    /// The format it is written in, [`FORMAT`].
22    pub format: u32,
23    /// The frames' build.
24    pub frames: Frames,
25    /// Where the frames' policies say they are served, when that is a custom scheme (`compmd://localhost/`), whose
26    /// `'self'` `WebKit` reads as nothing in a sandboxed frame; none for http and https origins.
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub source: Option<String>,
29    /// The packs the bundle holds, under `packs/<name>@<version>/`.
30    #[serde(default, skip_serializing_if = "Vec::is_empty")]
31    pub packs: Vec<BundledPack>,
32    /// The libraries the frames offer component code, besides the runtimes.
33    #[serde(default, skip_serializing_if = "Vec::is_empty")]
34    pub libraries: Vec<Library>,
35    /// The processor's policy the configuration made (`policyOf`), as JSON: what a host that processes in Rust gives
36    /// the processor.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub policy: Option<serde_json::Value>,
39    /// The packs every document gets without importing them.
40    #[serde(default, skip_serializing_if = "Vec::is_empty")]
41    pub ambient: Vec<PackName>,
42}
43
44/// The frames' build: its folder, `frames/<hash>/`.
45#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
46pub struct Frames {
47    /// The build's hash.
48    pub hash: FramesHash,
49}
50
51/// A pack the bundle holds. In JSON its release is flat: `{"pack", "version", "integrity", "trust", "modules"}`.
52#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
53pub struct BundledPack {
54    /// The release.
55    #[serde(flatten)]
56    pub release: ReleaseId,
57    /// The integrity the registry publishes for it (`sha512-…`), from the app's lock file; none when the lock file
58    /// gave none.
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub integrity: Option<Integrity>,
61    /// The trust the configuration gives it.
62    #[serde(default)]
63    pub trust: Trust,
64    /// Its built modules, by their path in the pack, with their integrity (`sha384-…`), which a frame checks.
65    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
66    pub modules: BTreeMap<FilePath, Integrity>,
67}
68
69/// The trust a configuration gives a pack (spec §15).
70#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
71#[serde(rename_all = "lowercase")]
72pub enum Trust {
73    /// In a strict sandbox: the default.
74    #[default]
75    Strict,
76    /// In a permissive sandbox, with the network to its listed origins.
77    Permissive,
78    /// In the host's page: a folder pack built with the app only.
79    Trusted,
80}
81
82/// A library the frames offer: an npm package the app installs, which needn't be scoped (`d3`).
83#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
84pub struct Library {
85    /// Its npm name.
86    pub name: String,
87    /// The version the bundle holds.
88    pub version: Version,
89}
90
91impl Manifest {
92    /// The manifest in `text`.
93    ///
94    /// # Errors
95    ///
96    /// [`ManifestError`] when it isn't a manifest, is of another format, or names a frames' hash, a pack, a path or
97    /// an integrity that isn't one.
98    pub fn parse(text: &str) -> Result<Self, ManifestError> {
99        #[derive(Deserialize)]
100        struct Format {
101            format: u32,
102        }
103        let json = |error: serde_json::Error| ManifestError::Json(error.to_string());
104        let format: Format = serde_json::from_str(text).map_err(json)?;
105        if format.format != FORMAT {
106            return Err(ManifestError::UnknownFormat {
107                found: format.format,
108                known: FORMAT,
109            });
110        }
111        serde_json::from_str(text).map_err(json)
112    }
113
114    /// The custom scheme the bundle was built for, from its `source` (`compmd://localhost/` is `compmd`); none when
115    /// it was built for an http or https origin.
116    #[must_use]
117    pub fn scheme(&self) -> Option<&str> {
118        let scheme = self.source.as_deref()?.split_once("://")?.0;
119        (scheme != "http" && scheme != "https").then_some(scheme)
120    }
121
122    /// The pack at `release`, when the bundle holds it.
123    #[must_use]
124    pub fn pack(&self, release: &ReleaseId) -> Option<&BundledPack> {
125        self.packs.iter().find(|pack| pack.release == *release)
126    }
127}
128
129#[cfg(test)]
130mod tests;