subspace-contracts 0.1.0

Subspace Framework: typed, versioned board-to-board contracts. Internal crate; apps depend on `subspace-framework`.
Documentation
//! Issue links: app-relative and same-origin NETT links and Linear links.

use std::ops::Range;
use url::Url;

use super::reference::{ReferenceRecognizer, valid_identifier};

mod parse;
use parse::{authority, linear_identifier, relative_address};

/// One profile's current app origin, organisation and selected reference keys.
/// Reuse the same recogniser for plain text and links. Pass an empty recogniser
/// while signed out or without an organisation.
pub struct IssueLinkContext<'a> {
    app_origin: &'a str,
    organisation_id: &'a str,
    references: &'a ReferenceRecognizer,
    linear_workspace: Option<&'a str>,
}

impl<'a> IssueLinkContext<'a> {
    pub fn new(
        app_origin: &'a str,
        organisation_id: &'a str,
        references: &'a ReferenceRecognizer,
    ) -> Self {
        Self {
            app_origin,
            organisation_id,
            references,
            linear_workspace: None,
        }
    }

    /// Also recognise Linear issue links of `workspace`, the first path
    /// segment of its links (`https://linear.app/<workspace>/issue/…`).
    /// Without one, no Linear link is recognised.
    // qual:api (the app supplies its Linear workspace)
    pub fn with_linear_workspace(mut self, workspace: &'a str) -> Self {
        self.linear_workspace = (!workspace.is_empty()).then_some(workspace);
        self
    }

    /// Whether `url` is a link into the NETT app that is not an issue of
    /// this organisation, which NETT Markdown shows as its label alone.
    // qual:api
    pub fn flattens(&self, url: &str) -> bool {
        nett_path(url, self.app_origin).is_some_and(|path| {
            !app_identifier(&path).is_some_and(valid_identifier)
                || organisation_matches(url, self.organisation_id)
        })
    }
}

/// Returns an identifier using the same grammar as plain text references:
/// a recognised 2–5 character team key and ASCII digits without a leading zero.
/// The context uses the same selected keys as plain text, including fallback.
/// Every decoded `orgId` on a NETT link must match the context organisation
/// case-insensitively. Linear links are recognised only for the context's
/// Linear workspace and do not use the organisation query.
/// This does not scan prose or code.
// qual:api
pub fn issue_link_identifier(url: &str, context: &IssueLinkContext<'_>) -> Option<String> {
    let identifier = link_identifier(url, context)?;
    context
        .references
        .recognises(&identifier)
        .then_some(identifier)
}

/// Finds bare app-relative candidates with byte ranges and trimmed punctuation.
/// Call only on plain-text segments, excluding code and link destinations, then
/// validate each candidate with [`issue_link_identifier`].
// qual:api
pub fn relative_issue_addresses(text: &str) -> Vec<(Range<usize>, &str)> {
    text.match_indices("/issues/")
        .filter_map(|(start, _)| relative_address(text, start))
        .collect()
}

// Also used by `flattens` for other same-app links without duplicating
// origin or path handling. It deliberately does not validate issue identifiers.
fn nett_path(url: &str, app_origin: &str) -> Option<String> {
    if url.starts_with('/') && !url.starts_with("//") {
        return Some(url.split(['?', '#']).next().unwrap_or_default().into());
    }
    let authority = authority(url)?;
    let target = Url::parse(url).ok()?;
    let app = Url::parse(app_origin).ok()?;
    (matches!(target.scheme(), "http" | "https")
        && target.origin() == app.origin()
        && !authority.contains('@')
        && target.username().is_empty()
        && target.password().is_none())
    .then(|| target.path().to_owned())
}

fn link_identifier(url: &str, context: &IssueLinkContext<'_>) -> Option<String> {
    if let Some(path) = nett_path(url, context.app_origin) {
        let identifier = app_identifier(&path)?;
        return organisation_matches(url, context.organisation_id).then(|| identifier.to_owned());
    }
    linear_identifier(url, context.linear_workspace?)
}

fn app_identifier(path: &str) -> Option<&str> {
    let identifier = path.strip_prefix("/issues/")?;
    let identifier = identifier.strip_suffix('/').unwrap_or(identifier);
    (!identifier.contains('/')).then_some(identifier)
}

fn organisation_matches(url: &str, organisation_id: &str) -> bool {
    let before_fragment = url.split('#').next().unwrap_or_default();
    let query = before_fragment
        .split_once('?')
        .map_or("", |(_, query)| query);
    url::form_urlencoded::parse(query.as_bytes())
        .filter(|(name, _)| name == "orgId")
        .all(|(_, value)| value.eq_ignore_ascii_case(organisation_id))
}