flow-toolkit 0.1.0-rc.5

Ordinary typed Rust functions and exact native data for Flow Tools, served from a Rust library's one launcher.
Documentation
//! `flow_toolkit::Url` is `url.Url` and `flow_toolkit::MediaType` is
//! `media.MediaType` (`abi.md`, *Extracting a contract* and *Toolkits*).
//!
//! Each is made only by its `parse` and written as its normal text, and
//! reading accepts only that text.
#![expect(
    missing_docs,
    reason = "the test binary's tool fixtures are public by the derive's rule"
)]
mod common;

use flow_abi_testing::crossing::{bytes, crossed, read};
use flow_toolkit::{Flow, MediaType, Url, tool};

/// A fetched resource.
#[derive(Flow, Clone, Debug, PartialEq)]
pub struct Fetched {
    pub url: Url,
    pub media_type: Option<MediaType>,
}

#[tool]
pub fn fetched(url: Url, media_type: MediaType) -> Fetched {
    Fetched {
        url,
        media_type: Some(media_type),
    }
}

/// A page, whose field is named like std's `url`.
#[derive(Flow, Clone, Debug, PartialEq)]
pub struct Page {
    pub url: Url,
}

/// What a link names, in a payload whose field is named like std's `media`.
#[derive(Flow, Clone, Debug, PartialEq)]
pub enum Named {
    Typed { media: MediaType },
}

#[tool]
pub fn page(page: Page) -> Page {
    page
}

#[tool]
pub fn named(named: Named) -> Named {
    named
}

/// A Tool whose name is std's module name `url`.
#[tool]
pub fn url(to: Url) -> Url {
    to
}

#[tool]
pub fn std_url(url: Url) -> Url {
    url
}

/// The `use` lines of the contract the Tools `placed` give.
fn imports(placed: Vec<flow_toolkit::__bridge::Function>) -> Vec<String> {
    let placed: Vec<_> = placed
        .into_iter()
        .map(|function| flow_toolkit::__bridge::at("", "tests/std_urls.rs", 1, function))
        .collect();
    common::extract("std_urls", None, &placed)
        .expect("the contract is written")
        .into_values()
        .flat_map(|text| {
            text.lines()
                .filter(|line| line.starts_with("use "))
                .map(str::to_owned)
                .collect::<Vec<_>>()
        })
        .collect()
}

#[test]
fn a_field_or_payload_name_leaves_the_import_alone() {
    // A field never collides with an import (`modules.md`).
    assert_eq!(imports(vec![__flow_tool_page()]), [r#"use "std@v1/url""#]);
    assert_eq!(
        imports(vec![__flow_tool_named()]),
        [r#"use "std@v1/media""#]
    );
}

#[test]
fn a_tool_named_like_an_imported_std_module_is_refused() {
    for functions in [
        vec![__flow_tool_url()],
        vec![__flow_tool_url(), __flow_tool_std_url()],
    ] {
        let placed: Vec<_> = functions
            .into_iter()
            .map(|function| flow_toolkit::__bridge::at("", "tests/std_urls.rs", 1, function))
            .collect();
        let refusal = common::extract("std_urls", None, &placed)
            .expect_err("the Tool collides with the std import");
        assert_eq!(
            refusal.to_string(),
            "tests/std_urls.rs:1:1: Tool `url` conflicts with import `std@v1/url`; give the Tool a different public name"
        );
    }
}

#[test]
fn a_parameter_named_like_a_std_module_leaves_its_import_alone() {
    // `std_url`'s parameter `url` hides the module only inside the Tool.
    assert_eq!(
        imports(vec![__flow_tool_std_url()]),
        [r#"use "std@v1/url""#]
    );
}

fn contracts() -> std::collections::BTreeMap<flow_types::Segments, String> {
    let placed = [__flow_tool_fetched()]
        .map(|function| flow_toolkit::__bridge::at("", "tests/std_urls.rs", 1, function));
    common::extract("std_urls", None, &placed).expect("the contract is written")
}

fn parsed(text: &str) -> Url {
    Url::parse(text).expect("a URL")
}

#[test]
fn a_url_and_a_media_type_are_the_std_types_with_their_modules_imported() {
    // The Tool's parameter `url` hides the module only inside the Tool, and
    // a type names the module, so std's `url` is imported under its name.
    let source = contracts().into_values().collect::<Vec<_>>().join("\n");
    for line in [
        "use \"std@v1/media\"\n",
        "use \"std@v1/url\"\n",
        "pub flow fetched(url: url.Url, media_type: media.MediaType) -> Fetched\n",
        "    pub url: url.Url,\n",
        "    pub media_type: Option<media.MediaType>,\n",
    ] {
        assert!(source.contains(line), "{line:?} in {source}");
    }
}

#[test]
fn the_generated_contract_is_one_the_checker_accepts() {
    let listed = common::listed(&contracts(), &common::referring(&["lib.fetched"]));
    assert!(common::tool_names(&listed).contains(&"fetched"));
    assert!(common::names_std(&listed, "url", "Url"));
    assert!(common::names_std(&listed, "media", "MediaType"));
}

#[test]
fn each_is_written_as_its_normal_text() {
    let cases = [
        (bytes(&parsed("HTTP://Example.COM")), "http://example.com/"),
        (
            bytes(&MediaType::parse("Text/HTML ; Charset=\"utf-8\"").unwrap()),
            "text/html;charset=utf-8",
        ),
        (bytes(&parsed("http://a/b/../c")), "http://a/c"),
    ];
    for (written, normal) in cases {
        assert_eq!(written, bytes(&normal.to_owned()), "{normal}");
    }
}

/// Whether the runtime refuses `bytes` as a value of `T`'s Flow type.
fn refused<T: flow_toolkit::Shaped>(bytes: &[u8]) -> bool {
    let (catalog, ty) = flow_abi::wire::project(T::FORM, &flow_abi_testing::catalog::std_catalog())
        .expect("a Flow type");
    flow_abi::decode_bytes(
        &catalog,
        &ty,
        bytes,
        flow_abi::Mode::Rebuild,
        &flow_abi::Limits::default(),
    )
    .is_err()
}

#[test]
fn binary_reading_accepts_only_the_normal_text() {
    assert_eq!(
        read::<Url>(&bytes(&"http://example.com/".to_owned())),
        parsed("http://example.com/")
    );
    for loose in ["HTTP://Example.COM", "not a url"] {
        assert!(refused::<Url>(&bytes(&loose.to_owned())), "{loose}");
    }
    assert!(refused::<MediaType>(&bytes(&"Text/Plain".to_owned())));
}

#[test]
fn a_record_crosses_as_its_fields_normal_text() {
    let value = Fetched {
        url: parsed("https://Example.com:443/a/./b"),
        media_type: None,
    };
    let (crossed, _) = crossed(&value);
    assert_eq!(crossed, value);
    assert_eq!(crossed.url.to_string(), "https://example.com:443/a/b");
}