nostralink 0.2.1

Linked data library for nostr
Documentation
//! Custom JSON-LD filesystem loader
#![doc(hidden)]

use std::path::PathBuf;

use sophia_jsonld::{
    loader::{FsLoader, StaticLoader},
    vocabulary::ArcIri,
};

use crate::niri::nl_base_iri;
use json_syntax::{Parse, Value};
use locspan::{Location, Span};
use rust_embed::Embed;

#[derive(Embed)]
#[folder = "$OUT_DIR/contexts-build/nostralink"]
pub struct Contexts;

/// Creates a FsLoader to load JSON-LD contexts from local files
pub fn fs_loader(path: PathBuf) -> FsLoader {
    let _iri_nostra_g =
        ArcIri::new_unchecked("https://nostralink.gitlab.io/".into());
    let iri_nostra = ArcIri::new_unchecked("http://nostralink.org/".into());
    let _iri_loc_schema_org =
        ArcIri::new_unchecked("http://local.schema.org/".into());
    let _iri_schema_org = ArcIri::new_unchecked("http://schema.org".into());
    let _iri_https_schema_org =
        ArcIri::new_unchecked("https://schema.org".into());

    let mut loader = FsLoader::default();
    loader.mount(iri_nostra, path.join("nostralink"));
    loader
}

/// Generates an in-memory [`StaticLoader`] that contains every JSON-LD
/// context found in the rust-embed Contexts structure
pub fn static_contexts_loader() -> StaticLoader<ArcIri, Span> {
    let mut loader = StaticLoader::default();
    let base = nl_base_iri();

    for ctx in Contexts::iter() {
        let name = ctx.as_ref();

        let Some(asset) = Contexts::get(name) else {
            continue;
        };

        let iri = ArcIri::new_unchecked(
            base.resolve_unchecked(name).to_string().into(),
        );

        let Ok(content) = std::str::from_utf8(asset.data.as_ref()) else {
            continue;
        };

        if let Ok(value) =
            Value::parse_str(content, |span| Location::new(iri.clone(), span))
        {
            loader = loader.with(iri.clone(), value);
        }
    }

    loader
}