use super::EntityId;
use unicode_normalization::UnicodeNormalization;
pub const ENTITY_ID_MAX_LEN: usize = 200;
#[derive(Debug, thiserror::Error)]
pub enum SlugError {
#[error(
"entity id \"{input}\" is {length} characters (max {max}); the id is `<mem>--<slug>`, so the title budget shrinks as the mem name grows — shorten the title"
)]
IdTooLong {
input: String,
length: usize,
max: usize,
},
#[error("title is empty or contains no slug-meaningful characters")]
TitleEmpty { input: String },
#[error(
"title {input:?} contains control character(s) {control_chars:?} that would split the stored heading — \
retry with a single-line title (proposed slug: \"{proposed_slug}\")"
)]
TitleHasControlChars {
input: String,
control_chars: Vec<char>,
proposed_slug: String,
},
}
impl SlugError {
pub fn reason(&self) -> &'static str {
match self {
SlugError::IdTooLong { .. } => "id_too_long",
SlugError::TitleEmpty { .. } => "empty",
SlugError::TitleHasControlChars { .. } => "control_chars",
}
}
}
pub fn build_id(mem: &str, title: &str) -> Result<EntityId, SlugError> {
let slug = title_to_slug(title)?;
let id = EntityId::new(mem, &slug);
enforce_id_length(id.as_ref())?;
Ok(id)
}
pub fn enforce_id_length(id: &str) -> Result<(), SlugError> {
if id.chars().count() > ENTITY_ID_MAX_LEN {
return Err(SlugError::IdTooLong {
input: id.to_string(),
length: id.chars().count(),
max: ENTITY_ID_MAX_LEN,
});
}
Ok(())
}
pub fn title_to_slug(title: &str) -> Result<String, SlugError> {
let normalized: String = title.nfc().collect();
let slug: String = normalized
.chars()
.flat_map(|c| c.to_lowercase())
.map(|c| if c.is_whitespace() { '-' } else { c })
.filter(|c| c.is_alphanumeric() || *c == '-')
.collect::<String>()
.split('-')
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join("-");
if slug.is_empty() {
return Ok(format!("entity-{}", short_hash(title)));
}
Ok(slug)
}
pub const TITLE_GRAMMAR_RULE: &str = "Titles accept any single-line text (control characters such as tab/newline are rejected); the title is stored verbatim as display text, while characters outside Unicode alphanumerics, whitespace, and hyphen are dropped from the derived slug — warning TITLE_CHARS_DROPPED_FROM_SLUG names them";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SlugDerivation {
pub slug: String,
pub dropped_chars: Vec<char>,
}
pub fn validate_and_derive_slug(title: &str) -> Result<SlugDerivation, SlugError> {
let normalized: String = title.nfc().collect();
let case_folded: String = normalized.chars().flat_map(|c| c.to_lowercase()).collect();
let mut control_chars: Vec<char> = Vec::new();
for c in case_folded.chars() {
if c.is_control() && !control_chars.contains(&c) {
control_chars.push(c);
}
}
if !control_chars.is_empty() {
let proposed = title_to_slug(title).unwrap_or_default();
return Err(SlugError::TitleHasControlChars {
input: title.to_string(),
control_chars,
proposed_slug: proposed,
});
}
let mut dropped_chars: Vec<char> = Vec::new();
for c in case_folded.chars() {
if c.is_whitespace() || c == '-' || c.is_alphanumeric() {
continue;
}
if !dropped_chars.contains(&c) {
dropped_chars.push(c);
}
}
let slug: String = case_folded
.chars()
.filter(|c| c.is_whitespace() || *c == '-' || c.is_alphanumeric())
.map(|c| if c.is_whitespace() { '-' } else { c })
.collect::<String>()
.split('-')
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join("-");
if slug.is_empty() {
return Err(SlugError::TitleEmpty {
input: title.to_string(),
});
}
Ok(SlugDerivation {
slug,
dropped_chars,
})
}
fn short_hash(input: &str) -> String {
use sha2::{Digest, Sha256};
let digest = Sha256::digest(input.as_bytes());
format!(
"{:02x}{:02x}{:02x}{:02x}",
digest[0], digest[1], digest[2], digest[3]
)
}
pub fn file_path_to_id(path: &str, mem: &str) -> EntityId {
let stripped = path.strip_suffix(".md").unwrap_or(path);
EntityId::new(mem, stripped)
}
#[derive(Debug, thiserror::Error, Clone)]
pub enum WikiLinkError {
#[error("mem prefix '{raw}' is not a valid mem name: {reason}")]
InvalidMemName { raw: String, reason: String },
#[error("wiki-link target '{raw}' is not slug-form: {reason}")]
InvalidTarget {
raw: String,
suggested: Option<String>,
reason: String,
},
}
fn wiki_link_suggestion(raw: &str) -> Option<String> {
let derived = title_to_slug(raw).ok()?;
if derived.is_empty() || derived.starts_with("entity-") {
return None;
}
validate_id_path_grammar(&derived)
.is_ok()
.then_some(derived)
}
pub fn wiki_link_to_id(link: &str, current_mem: &str) -> Result<EntityId, WikiLinkError> {
let stripped = strip_wiki_link_decorations(link);
if !stripped.contains("::")
&& let Some(colon_idx) = stripped.find(':')
{
let (prefix, rest) = stripped.split_at(colon_idx);
let slug_part = &rest[1..];
if !prefix.is_empty() && !slug_part.is_empty() {
if let Err(reason) = validate_mem_name_grammar(prefix) {
return Err(WikiLinkError::InvalidMemName {
raw: prefix.to_string(),
reason,
});
}
if let Err(reason) = validate_id_path_grammar(slug_part) {
let suggested = wiki_link_suggestion(slug_part).map(|s| format!("{prefix}:{s}"));
return Err(WikiLinkError::InvalidTarget {
raw: stripped.to_string(),
suggested,
reason,
});
}
return Ok(EntityId::new(prefix, slug_part));
}
}
if let Some(dash_idx) = stripped.find("--") {
let prefix = &stripped[..dash_idx];
let suffix = &stripped[dash_idx + 2..];
if !prefix.is_empty()
&& !suffix.is_empty()
&& !prefix.contains('/')
&& validate_mem_name_grammar(prefix).is_ok()
&& validate_id_path_grammar(suffix).is_ok()
{
return Ok(EntityId::new(prefix, suffix));
}
}
let slug = if !current_mem.is_empty() {
let self_prefix = format!("{current_mem}--");
stripped
.strip_prefix(self_prefix.as_str())
.unwrap_or(&stripped)
} else {
&stripped
};
if let Some(dash_idx) = slug.find("--")
&& slug[..dash_idx].contains('/')
{
let prefix = &slug[..dash_idx];
let suffix = &slug[dash_idx + 2..];
let cross_mem_form = format!("{prefix}:{suffix}");
let same_mem_form = if current_mem.is_empty() {
format!("<current-mem>:{slug}")
} else {
format!("{current_mem}:{slug}")
};
return Err(WikiLinkError::InvalidTarget {
raw: stripped.to_string(),
suggested: Some(cross_mem_form),
reason: format!(
"wiki-link target contains both '/' and '--', which is ambiguous \
between a cross-mem reference into a hierarchical mem and a \
same-mem entity at a hierarchical slug; use the colon form \
'[[{prefix}:{suffix}]]' for a cross-mem reference, or \
'[[{same_mem_form}]]' for a same-mem entity whose slug \
contains '--'"
),
});
}
if let Err(reason) = validate_id_path_grammar(slug) {
return Err(WikiLinkError::InvalidTarget {
raw: stripped.to_string(),
suggested: wiki_link_suggestion(slug),
reason,
});
}
Ok(EntityId::new(current_mem, slug))
}
pub fn wiki_link_to_id_lenient(link: &str, current_mem: &str) -> EntityId {
let mut stripped = strip_wiki_link_decorations(link);
loop {
let next = strip_wiki_link_decorations(stripped.trim_end());
if next == stripped {
break;
}
stripped = next;
}
let stripped = stripped.trim_end();
if !stripped.contains("::")
&& let Some(colon_idx) = stripped.find(':')
{
let (prefix, rest) = stripped.split_at(colon_idx);
let slug_part = &rest[1..];
if !prefix.is_empty() && !slug_part.is_empty() {
return EntityId::new(prefix, slug_part);
}
}
if let Some(dash_idx) = stripped.find("--") {
let prefix = &stripped[..dash_idx];
let suffix = &stripped[dash_idx + 2..];
if !prefix.is_empty()
&& !suffix.is_empty()
&& !prefix.contains('/')
&& validate_mem_name_grammar(prefix).is_ok()
&& validate_id_path_grammar(suffix).is_ok()
{
return EntityId::new(prefix, suffix);
}
}
let slug = if !current_mem.is_empty() {
let self_prefix = format!("{current_mem}--");
stripped
.strip_prefix(self_prefix.as_str())
.unwrap_or(stripped)
} else {
stripped
};
EntityId::new(current_mem, slug)
}
pub(crate) fn strip_wiki_link_decorations(link: &str) -> String {
let cleaned = link.trim_start_matches("[[").trim_end_matches("]]").trim();
let target = match cleaned.find('|') {
Some(i) => &cleaned[..i],
None => cleaned,
};
let target_no_anchor = match target.find('#') {
Some(i) => &target[..i],
None => target,
};
let target_no_dotdot = target_no_anchor.trim_start_matches("../");
target_no_dotdot
.strip_suffix(".md")
.unwrap_or(target_no_dotdot)
.to_string()
}
pub fn id_to_file_path(id: &EntityId) -> String {
format!("{}.md", id.path())
}
pub fn validate_id_path_grammar(path: &str) -> Result<&str, String> {
use std::sync::OnceLock;
static RE: OnceLock<regex::Regex> = OnceLock::new();
let re = RE.get_or_init(|| {
regex::Regex::new(
r"^[\p{Ll}\p{Lo}\p{Lm}\p{Mn}\p{Mc}\p{N}-]+(/[\p{Ll}\p{Lo}\p{Lm}\p{Mn}\p{Mc}\p{N}-]+)*$",
)
.unwrap()
});
if re.is_match(path) {
Ok(path)
} else {
Err(format!(
"id path '{path}' does not match the wiki-link grammar — \
entity slugs must be lowercase Unicode letters / digits / \
hyphens, with path segments separated by '/'"
))
}
}
pub fn validate_mem_name_grammar(mem: &str) -> Result<&str, String> {
use std::sync::OnceLock;
static RE: OnceLock<regex::Regex> = OnceLock::new();
let re = RE.get_or_init(|| regex::Regex::new(r"^[a-z0-9-]+(/[a-z0-9-]+)*$").unwrap());
if re.is_match(mem) {
Ok(mem)
} else {
Err(format!(
"mem name '{mem}' must match ^[a-z0-9-]+(/[a-z0-9-]+)*$ \
(lowercase ASCII / digits / hyphens, optionally segmented \
by '/' for hierarchical layouts; no leading, trailing, or \
double slashes)"
))
}
}
pub fn validate_rel_type(rel_type: &str) -> Result<String, String> {
let cleaned = rel_type.to_uppercase();
if cleaned.chars().all(|c| c.is_ascii_uppercase() || c == '_') && !cleaned.is_empty() {
Ok(cleaned)
} else {
Err(format!(
"Invalid relationship type: \"{rel_type}\". Only ASCII letters and underscores allowed (input is canonicalised to uppercase)."
))
}
}
#[cfg(test)]
mod tests;