You are a constitutional council ranking individual git commits for ownership allocation. Compare these two commits. Decide which contributed more lasting value to the project. Judge substance, not spectacle: - Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise. - Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one. - Do not favor a side merely because its patch is longer or noisier. - Weight what the change does for the project, not the contributor's name. Return ONLY a JSON object: {"winner": "A" or "B", "ratio": "N:M", "explanation": "..."} The explanation must cite concrete differences in the patches (1-3 sentences). Side A — contributor: tommy-mor Side A — commit message: [529cc941] Replace autocomplete parser with paste-and-go navigate. The keystroke transition graph was unreliable; a textarea plus Go button now parses pasted Reddit URLs and redirects to the subreddit ranking scope. Co-authored-by: Cursor Side A — unified diff (full patch): diff --git a/AGENTS.md b/AGENTS.md index 77f2e31d4e860a92a77255ca5106c8b6c4510ee7..36ee4c0ec700bffbe226ee775ba9cf59cf35c770 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,6 @@ Single Rust web app **`sorter2-server`**: pairwise voting, rank-centrality ranki - **Rust 1.88+** is required (some transitive crates need a recent Cargo). The image may ship older `/usr/local/cargo` (1.83); use **rustup** and `rustup default 1.88.0` before building. - **System packages** for builds: `pkg-config`, `libssl-dev` (for `reqwest` / OpenSSL in integration tests and release builds). - **Clojure CLI 1.12.0.1530** (optional but used in CI): install from https://clojure.org/guides/install_clojure — needed for `./scripts/clj-test.sh` / Kaocha tests. -- **Playwright browser** for the spel browser test (`test/parser_race.clj`): install once with `clojure -M -e "(com.microsoft.playwright.CLI/main (into-array String [\"install\" \"chromium\" \"--with-deps\"]))"`. The browser binary is cached under `~/.cache/ms-playwright`. ### Commands (see also `TEST.sh`) diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs index 1339048c955c0a3eb5120381aaf031424cbed540..c4ab9d65c7b3cd42a5b4d093ba429993c101e9a8 100644 --- a/server/src/api/ui_html.rs +++ b/server/src/api/ui_html.rs @@ -8,7 +8,7 @@ use std::collections::HashMap; use crate::{ html::{js_string_literal, ranking_panel, JsBuilder}, parser::parse_reddit_url, - parser_render::parser_panel_morph, + parser_render::navigate_panel, state::AppState, ui_action::{parse_html_ui_from_form, HtmlUiAction}, }; @@ -57,18 +57,23 @@ pub async fn post_ui_html( .morph_selector("#ranking-panel", panel) .into_response() } - HtmlUiAction::ParseQuery { query } => { - let action = parse_reddit_url(&query); - let panel = parser_panel_morph(&query, &action); - let mut js = JsBuilder::new().morph_selector("#parser-panel", panel); - if let Some(comp) = action.primary_completion() { - js = js.raw(&format!( - "var __pi=document.getElementById('parser-input'); if(__pi){{__pi.dataset.completion={};}}", - js_string_literal(comp) - )); + HtmlUiAction::ParseQuery { query } => match parse_reddit_url(&query) { + Ok(subreddit) => { + let dest = format!("/?sub={subreddit}"); + JsBuilder::new() + .raw(&format!( + "window.location.href={};", + js_string_literal(&dest) + )) + .into_response() } - js.into_response() - } + Err(message) => { + let panel = navigate_panel(&query, Some(&message)); + JsBuilder::new() + .morph_selector("#parser-panel", panel) + .into_response() + } + }, } } diff --git a/server/src/html/mod.rs b/server/src/html/mod.rs index 94a5cfb561d1c8464bd2782f7ffd4e0965ccf95d..9650d333d29c4ac94ceb407aee3ee00399c7f40b 100644 --- a/server/src/html/mod.rs +++ b/server/src/html/mod.rs @@ -11,8 +11,7 @@ use serde::Deserialize; use crate::{ form_template::template_json_compact, - parser_action::ParserAction, - parser_render::parser_panel, + parser_render::navigate_panel, ranking::{top_bottom, RankedItem}, reducer::GroupState, state::{normalize_scope, AppState}, @@ -336,10 +335,9 @@ pub async fn home( let empty = GroupState::new(); let group = groups.get(&scope).unwrap_or(&empty); - let empty_action = ParserAction::suggest(String::new(), None); let body = html! { h1 { "sorter2" } - (parser_panel("", &empty_action)) + (navigate_panel("", None)) (vote_panel(&scope)) (ranking_panel(&scope, group)) }; diff --git a/server/src/lib.rs b/server/src/lib.rs index fa423640d598f4ba97a5885d228e78d7b97f7a22..de8bca48cbf689cad22337883e7791966e7c4919 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -4,7 +4,6 @@ pub mod events; pub mod form_template; pub mod html; pub mod parser; -pub mod parser_action; pub mod parser_render; pub mod path_types; pub mod ranking; diff --git a/server/src/parser.rs b/server/src/parser.rs index ea437c4434045b44cba04a2b3416df850db518e7..50571a59f0d3ece1e2538f88e00ef46ec40ea545 100644 --- a/server/src/parser.rs +++ b/server/src/parser.rs @@ -1,1811 +1,87 @@ -use std::collections::HashMap; -use std::sync::OnceLock; +//! Extract a subreddit name from a pasted Reddit URL or path. -use crate::parser_action::{GuideOption, ParserAction, ScrollingSuggestion, Suggestion}; - -// --- Core Abstractions --- - -/// Unique identifier for nodes in the graph -type NodeId = &'static str; - -/// Pattern matching for edges -#[derive(Debug, Clone)] -pub enum EdgePattern { - /// Matches exact literal string - Literal(&'static str), - - /// Matches any prefix of a string and suggests the full string - /// e.g., PrefixOf("reddit.com") matches "r", "re", "red", "reddit", "reddit.com" - PrefixOf(&'static str), - - /// Captures a variable segment (e.g., subreddit name, username) - Variable(&'static str), - - /// Matches any string (wildcard) - Any, -} - -impl EdgePattern { - /// Try to match this pattern against input, return (consumed_chars, captured_value) - fn matches(&self, input: &str) -> Option<(usize, Option)> { - match self { - EdgePattern::Literal(lit) => { - if input.starts_with(lit) { - Some((lit.len(), None)) - } else { - None - } - } - EdgePattern::PrefixOf(target) => { - // Check if input is a prefix of target - if target.starts_with(input) && !input.is_empty() { - // It's a valid prefix - Some((input.len(), None)) - } else if input.starts_with(target) { - // Full match - Some((target.len(), None)) - } else { - None - } - } - EdgePattern::Variable(var_name) => { - // Consume until next '/' or end of string - let end = input.find('/').unwrap_or(input.len()); - if end > 0 { - let captured = input[..end].to_string(); - // Validate based on variable type - if is_valid_variable(var_name, &captured) { - Some((end, Some(captured))) - } else { - None - } - } else { - None - } - } - EdgePattern::Any => { - // Match everything until next '/' or end - let end = input.find('/').unwrap_or(input.len()); - if end > 0 { - Some((end, Some(input[..end].to_string()))) - } else { - None - } - } - } - } - - /// Get the completion suggestion for this pattern - fn completion(&self, partial: &str) -> Option { - match self { - EdgePattern::PrefixOf(target) => { - if target.starts_with(partial) && partial != *target { - Some(target.to_string()) - } else { - None - } - } - _ => None, - } +pub fn parse_reddit_url(query: &str) -> Result { + let q = query.trim(); + if q.is_empty() { + return Err("Paste a Reddit URL or r/subreddit path".into()); } -} -/// Edge in the graph -pub struct Edge { - pattern: EdgePattern, - target: NodeId, - /// Optional description for autocomplete - description: Option<&'static str>, -} - -/// Handler function for generating UI actions (Send + Sync so the graph can live in `OnceLock`). -type Handler = Box) -> ParserAction + Send + Sync>; - -/// Node in the graph -pub struct Node { - #[allow(dead_code)] - id: NodeId, - edges: Vec, - handler: Option, -} - -/// The composable parser graph (immutable after `build`). -pub struct Graph { - nodes: HashMap, - root: NodeId, -} - -// --- Graph Builder (Fluent API) --- - -pub struct GraphBuilder { - nodes: HashMap, - current_node: Option, - root: NodeId, -} - -impl GraphBuilder { - pub fn new() -> Self { - let mut nodes = HashMap::new(); - nodes.insert( - "root", - Node { - id: "root", - edges: Vec::new(), - handler: None, - }, - ); - - GraphBuilder { - nodes, - current_node: Some("root"), - root: "root", - } + if let Some(sub) = subreddit_after_prefix(q, "r/") { + return Ok(sub); } - /// Select a node to add edges to - pub fn at(mut self, node_id: NodeId) -> Self { - self.nodes.entry(node_id).or_insert_with(|| Node { - id: node_id, - edges: Vec::new(), - handler: None, - }); - self.current_node = Some(node_id); - self + if let Some(sub) = subreddit_from_path_segment(q, "/r/") { + return Ok(sub); } - - /// Add an edge from the current node - pub fn edge(self, pattern: EdgePattern, target: NodeId) -> Self { - self.edge_with_desc(pattern, target, None) - } - - /// Add an edge with description - pub fn edge_with_desc( - mut self, - pattern: EdgePattern, - target: NodeId, - desc: Option<&'static str>, - ) -> Self { - let current = self.current_node.expect("No current node selected"); - - self.nodes.entry(target).or_insert_with(|| Node { - id: target, - edges: Vec::new(), - handler: None, - }); - - if let Some(node) = self.nodes.get_mut(current) { - node.edges.push(Edge { - pattern, - target, - description: desc, - }); - } - self - } - - /// Set handler for current node - pub fn handler(mut self, handler: F) -> Self - where - F: Fn(&str, &str, &HashMap) -> ParserAction + Send + Sync + 'static, - { - let current = self.current_node.expect("No current node selected"); - if let Some(node) = self.nodes.get_mut(current) { - node.handler = Some(Box::new(handler)); - } - self - } - - /// Build the final graph - pub fn build(self) -> Graph { - Graph { - nodes: self.nodes, - root: self.root, - } - } + Err("Could not find a subreddit in that URL".into()) } -// --- Parser Implementation --- - -impl Graph { - pub fn parse(&self, input: &str) -> ParserAction { - let normalized = input.trim().to_lowercase(); - let mut state = ParserState { - input: &normalized, - cursor: 0, - current_node_id: self.root, - context: HashMap::new(), - original_query: input.to_string(), - current_prefix: String::new(), - }; - - self.parse_recursive(&mut state) - } - - fn parse_recursive(&self, state: &mut ParserState) -> ParserAction { - let node = self - .nodes - .get(state.current_node_id) - .expect("Node not found in graph"); - - // If we've consumed all input, check for handler or suggestions - if state.cursor >= state.input.len() { - if let Some(handler) = &node.handler { - return handler(&state.original_query, &state.current_prefix, &state.context); - } - - // No handler, try to suggest based on available edges - return self.suggest_from_edges(node, state); - } - - let remaining = &state.input[state.cursor..]; - - // Try to match each edge - for edge in &node.edges { - if let Some((consumed, captured)) = edge.pattern.matches(remaining) { - // Save state for potential backtracking - let saved_cursor = state.cursor; - let saved_node = state.current_node_id; - let saved_prefix = state.current_prefix.clone(); - - // Update state - state.cursor += consumed; - state.current_node_id = edge.target; - state.current_prefix.push_str(&remaining[..consumed]); - - // Store captured variable if any - if let Some(value) = captured { - if let EdgePattern::Variable(var_name) = &edge.pattern { - state.context.insert(var_name.to_string(), value); - } - } - - // Check if this is a partial match that needs completion - if state.cursor == state.input.len() { - if let Some(completion_suffix) = edge.pattern.completion(remaining) { - // Use the current_prefix plus the completion suffix - let full_completion = format!("{}{}", - state.current_prefix, - completion_suffix.strip_prefix(remaining).unwrap_or(&completion_suffix) - ); - return ParserAction::suggest( - state.original_query.clone(), - Some(Suggestion { - text: full_completion.clone(), - completion: full_completion, - description: edge.description.map(|d| d.to_string()), - score: 1.0, - }) - ); - } - } - - // Continue parsing from the target node - let result = self.parse_recursive(state); - - // If we got a valid response, return it - if !matches!(result, ParserAction::ShowError(_)) { - return result; - } - - // Otherwise, restore state and try next edge - state.cursor = saved_cursor; - state.current_node_id = saved_node; - state.current_prefix = saved_prefix; - } - } - - // No edges matched - try to provide suggestions - self.suggest_from_edges(node, state) - } - - fn suggest_from_edges(&self, node: &Node, state: &ParserState) -> ParserAction { - let remaining = &state.input[state.cursor..]; - - // Find edges that could match with more input - for edge in &node.edges { - match &edge.pattern { - EdgePattern::PrefixOf(target) => { - if target.starts_with(remaining) && !remaining.is_empty() { - // Use current_prefix instead of rebuilding from input - let full_completion = format!("{}{}", state.current_prefix, target); - return ParserAction::suggest( - state.original_query.clone(), - Some(Suggestion { - text: full_completion.clone(), - completion: full_completion, - description: edge.description.map(|d| d.to_string()), - score: 1.0, - }) - ); - } - } - EdgePattern::Literal(lit) => { - if lit.starts_with(remaining) && !remaining.is_empty() { - let full_completion = format!("{}{}", state.current_prefix, lit); - return ParserAction::suggest( - state.original_query.clone(), - Some(Suggestion { - text: full_completion.clone(), - completion: full_completion, - description: edge.description.map(|d| d.to_string()), - score: 1.0, - }) - ); - } - } - _ => {} - } - } - - ParserAction::error( - "InvalidPath".to_string(), - format!("'{}' doesn't match any known pattern", state.original_query) - ) - } +fn subreddit_after_prefix(text: &str, prefix: &str) -> Option { + let rest = text.strip_prefix(prefix)?; + let sub = rest.split(['/', '?', '#']).next()?.trim(); + valid_subreddit(sub) } -struct ParserState<'a> { - input: &'a str, - cursor: usize, - current_node_id: NodeId, - context: HashMap, - original_query: String, - current_prefix: String, +fn subreddit_from_path_segment(text: &str, needle: &str) -> Option { + let idx = text.find(needle)?; + let rest = &text[idx + needle.len()..]; + let sub = rest.split(['/', '?', '#']).next()?.trim(); + valid_subreddit(sub) } -// --- Helper Functions --- - -fn is_valid_variable(var_name: &str, value: &str) -> bool { - match var_name { - "subreddit" => { - !value.is_empty() && - value.len() <= 21 && - value.chars().all(|c| c.is_alphanumeric() || c == '_') - } - "username" => { - !value.is_empty() && - value.len() <= 20 && - value.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-') - } - "post_id" => { - !value.is_empty() && - value.len() <= 10 && - value.chars().all(|c| c.is_alphanumeric()) - } - _ => true, // Allow any value for unknown variables +fn valid_subreddit(name: &str) -> Option { + if name.is_empty() { + return None; + } + if name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') + { + Some(name.to_ascii_lowercase()) + } else { + None } -} - -// --- Define the Reddit Graph --- - -pub fn build_reddit_graph() -> Graph { - GraphBuilder::new() - // === ROOT LEVEL: Direct aliases and domain/protocol patterns === - .at("root") - // Direct aliases to subreddit and user selection - .edge_with_desc( - EdgePattern::PrefixOf("r/"), - "subreddit_selection", - Some("Browse subreddits (e.g., r/programming)") - ) - .edge_with_desc( - EdgePattern::PrefixOf("u/"), - "user_selection", - Some("Browse users (e.g., u/spez)") - ) - - // Reddit shortcuts - one pattern handles ALL prefixes! - .edge_with_desc( - EdgePattern::PrefixOf("reddit.com"), - "reddit_domain", - Some("Go to Reddit") - ) - - // Protocol patterns - "h" can suggest "https://" - .edge_with_desc( - EdgePattern::PrefixOf("https://"), - "https_protocol", - Some("HTTPS protocol") - ) - .edge_with_desc( - EdgePattern::PrefixOf("http://"), - "http_protocol", - Some("HTTP protocol") - ) - .edge_with_desc( - EdgePattern::PrefixOf("www."), - "www_prefix", - Some("World Wide Web") - ) - - - - // === HTTPS PROTOCOL: Can go to any domain === - .at("https_protocol") - .edge_with_desc( - EdgePattern::PrefixOf("reddit.com"), - "reddit_domain", - Some("Reddit (HTTPS)") - ) - .edge_with_desc( - EdgePattern::PrefixOf("www."), - "https_www", - Some("WWW prefix") - ) - - // === HTTP PROTOCOL: Similar to HTTPS === - .at("http_protocol") - .edge_with_desc( - EdgePattern::PrefixOf("reddit.com"), - "reddit_domain", - Some("Reddit (HTTP)") - ) - .edge_with_desc( - EdgePattern::PrefixOf("www."), - "http_www", - Some("WWW prefix") - ) - - // === HTTPS + WWW === - .at("https_www") - .edge_with_desc( - EdgePattern::PrefixOf("reddit.com"), - "reddit_domain", - Some("Reddit") - ) - - // === HTTP + WWW === - .at("http_www") - .edge_with_desc( - EdgePattern::PrefixOf("reddit.com"), - "reddit_domain", - Some("Reddit") - ) - - // === WWW PREFIX (without protocol) === - .at("www_prefix") - .edge_with_desc( - EdgePattern::PrefixOf("reddit.com"), - "reddit_domain", - Some("Reddit") - ) - - // === REDDIT DOMAIN: Expect "/" === - .at("reddit_domain") - .edge(EdgePattern::Literal("/"), "reddit_root") - .handler(|query, prefix, _ctx| { - // If someone just types "reddit.com" (or with protocol) without slash - // Suggest adding the slash using the current prefix - let completion = format!("{}/", prefix); - - ParserAction::suggest( - query.to_string(), - Some(Suggestion { - text: completion.clone(), - completion, - description: Some("Continue to Reddit homepage".to_string()), - score: 1.0, - }) - ) - }) - - // === REDDIT ROOT: The main Reddit navigation === - .at("reddit_root") - .edge(EdgePattern::Literal("r/"), "subreddit_selection") - .edge(EdgePattern::Literal("u/"), "user_selection") - .handler(|query, prefix, _ctx| { - ParserAction::multiple(vec![ - ParserAction::scrolling_suggestions( - query.to_string(), - vec![ - ScrollingSuggestion { - completion: format!("{}r/", prefix), - }, - ScrollingSuggestion { - completion: format!("{}u/", prefix), - }, - ], - 1400, // 1.4 second interval (slower) - true // loop through - ), - ParserAction::guide( - query.to_string(), - "Welcome to Sorter for Reddit".to_string(), - "Where would you like to start?".to_string(), - vec![ - GuideOption { - key: "r".to_string(), - label: "Sort a Subreddit".to_string(), - description: "Find the best posts in a community.".to_string(), - completion: format!("{}r/", prefix) - }, - GuideOption { - key: "u".to_string(), - label: "Sort User Content".to_string(), - description: "Explore and rank a user's posts and comments.".to_string(), - completion: format!("{}u/", prefix) - }, - ] - ), - ]) - }) - - - - // === SUBREDDIT SELECTION: THE UNIFIED NODE === - // This node is now reached from `r/` OR `reddit.com/r/` - .at("subreddit_selection") - .edge(EdgePattern::Variable("subreddit"), "subreddit_page") - .handler(|query, prefix, _ctx| { - ParserAction::multiple(vec![ - ParserAction::scrolling_suggestions( - query.to_string(), - vec![ - ScrollingSuggestion { - completion: format!("{}programming", prefix), - }, - ScrollingSuggestion { - completion: format!("{}askreddit", prefix), - }, - ScrollingSuggestion { - completion: format!("{}aww", prefix), - }, - ScrollingSuggestion { - completion: format!("{}rust", prefix), - }, - ScrollingSuggestion { - completion: format!("{}webdev", prefix), - }, - ], - 1600, // 1.6 second interval (slower) - true // loop through - ), - // Live DB-backed suggestions for subreddits as the user types - ParserAction::SuggestSubredditsFromDb { partial: query.to_string(), prefix: prefix.to_string() } - ]) - }) - - // === Specific subreddit page === - .at("subreddit_page") - .edge(EdgePattern::Literal("/"), "subreddit_slash") - .handler(|_query, prefix, ctx| { - // Use the new unified subreddit resolution logic - let subreddit = ctx.get("subreddit").cloned().unwrap_or_default(); - ParserAction::ResolveAndDisplaySubreddit { - subreddit, - prefix: prefix.to_string(), - } - }) - - .at("subreddit_slash") - .edge(EdgePattern::Literal("hot"), "subreddit_hot") - .edge(EdgePattern::Literal("top"), "subreddit_top") - .edge(EdgePattern::Literal("new"), "subreddit_new") - .edge(EdgePattern::Literal("comments"), "subreddit_comments") - .handler(|query, prefix, ctx| { - let subreddit = ctx.get("subreddit").cloned().unwrap_or_default(); - ParserAction::guide( - query.to_string(), - format!("What to sort in r/{}?", subreddit), - "Choose a category to begin sorting.".to_string(), - vec![ - GuideOption { - key: "hot".to_string(), - label: "Hot Posts".to_string(), - description: "Import and sort posts currently on the front page.".to_string(), - completion: format!("{}hot", prefix) - }, - GuideOption { - key: "top".to_string(), - label: "Top Posts".to_string(), - description: "Import and sort the highest-rated posts.".to_string(), - completion: format!("{}top", prefix) - }, - GuideOption { - key: "new".to_string(), - label: "New Posts".to_string(), - description: "Import and sort the newest posts.".to_string(), - completion: format!("{}new", prefix) - }, - GuideOption { - key: "comments".to_string(), - label: "All Comments".to_string(), - description: "Find the best comment across all imported threads.".to_string(), - completion: format!("{}comments/", prefix) - }, - ] - ) - }) - - - - .at("user_selection") - .edge(EdgePattern::Variable("username"), "user_profile") - .handler(|query, prefix, _ctx| { - ParserAction::guide( - query.to_string(), - "User Profile Sorting".to_string(), - "Enter a Reddit username to sort their content.".to_string(), - vec![ - GuideOption { - key: "popular".to_string(), - label: "Popular Users".to_string(), - description: "Browse well-known Reddit users.".to_string(), - completion: prefix.to_string(), - }, - ] - ) - }) - - // === Subreddit sort types === - .at("subreddit_hot") - .handler(|_query, _prefix, ctx| { - let subreddit = ctx.get("subreddit").cloned().unwrap_or_default(); - ParserAction::RenderEntityView { - ns: "reddit.subreddit".to_string(), - pk: subreddit, - } - }) - - .at("subreddit_top") - .handler(|_query, _prefix, ctx| { - let subreddit = ctx.get("subreddit").cloned().unwrap_or_default(); - ParserAction::RenderEntityView { - ns: "reddit.subreddit".to_string(), - pk: subreddit, - } - }) - - .at("subreddit_new") - .handler(|_query, _prefix, ctx| { - let subreddit = ctx.get("subreddit").cloned().unwrap_or_default(); - ParserAction::RenderEntityView { - ns: "reddit.subreddit".to_string(), - pk: subreddit, - } - }) - - .at("subreddit_comments") - .handler(|_query, _prefix, ctx| { - let subreddit = ctx.get("subreddit").cloned().unwrap_or_default(); - ParserAction::RenderEntityView { - ns: "reddit.subreddit".to_string(), - pk: subreddit, - } - }) - - // === User profile === - .at("user_profile") - .handler(|_query, _prefix, ctx| { - let username = ctx.get("username").cloned().unwrap_or_default(); - ParserAction::RenderEntityView { - ns: "reddit.user".to_string(), - pk: username, - } - }) - - // === Build the graph === - .build() -} - -// --- Public API --- - -static REDDIT_GRAPH: OnceLock = OnceLock::new(); - -fn reddit_graph() -> &'static Graph { - REDDIT_GRAPH.get_or_init(build_reddit_graph) -} - -/// Parse a query string and return a UI action -pub fn parse_reddit_url(query: &str) -> ParserAction { - reddit_graph().parse(query) } #[cfg(test)] mod tests { use super::*; - /// Represents a keystroke action - #[derive(Debug, Clone, PartialEq)] - enum KeyAction { - Type(String), // Type characters - Tab, // Press tab (accept completion) - - } - - /// Expected state after a keystroke - #[derive(Debug, Clone)] - enum ExpectedAction { - Suggestion { completion: String }, - ScrollingSuggestions { completions: Vec }, - Guide { title_contains: String }, - - RenderSubreddit { subreddit: String, sort: Option }, - RenderSubredditComments { subreddit: String }, - RenderUser { username: String }, - ResolveSubreddit { subreddit: String, prefix: String }, // New unified subreddit resolution - Error { error_type: String }, - Multiple { expected_actions: Vec }, // Multiple responses with specific expectations - MultipleAny, // Multiple responses (any sub-actions - legacy) - DbSuggestions { partial: String, prefix: String }, // Database-backed suggestions - - } - - impl ExpectedAction { - fn matches(&self, action: &ParserAction) -> bool { - match (self, action) { - (ExpectedAction::Suggestion { completion }, ParserAction::ShowSuggestions(data)) => { - data.suggestion.as_ref() - .map(|s| s.completion == *completion) - .unwrap_or(false) - } - (ExpectedAction::ScrollingSuggestions { completions }, ParserAction::ShowScrollingSuggestions { suggestions, .. }) => { - let actual_completions: Vec = suggestions.iter().map(|s| s.completion.clone()).collect(); - *completions == actual_completions - } - (ExpectedAction::Guide { title_contains }, ParserAction::ShowStaticGuide { title, .. }) => { - title.contains(title_contains) - } - (ExpectedAction::RenderSubreddit { subreddit, sort: _ }, - ParserAction::RenderEntityView { ns, pk }) => { - ns == "reddit.subreddit" && pk == subreddit - } - (ExpectedAction::RenderSubredditComments { subreddit }, - ParserAction::RenderEntityView { ns, pk }) => { - ns == "reddit.subreddit" && pk == subreddit - } - (ExpectedAction::RenderUser { username }, ParserAction::RenderEntityView { ns, pk }) => { - ns == "reddit.user" && pk == username - } - (ExpectedAction::ResolveSubreddit { subreddit, prefix }, - ParserAction::ResolveAndDisplaySubreddit { subreddit: s, prefix: p }) => { - s == subreddit && p == prefix - } - (ExpectedAction::Error { error_type }, ParserAction::ShowError(data)) => { - data.error_type == *error_type - } - (ExpectedAction::Multiple { expected_actions }, ParserAction::ShowMultiple { actions }) => { - // Check that all expected actions are present - if expected_actions.len() != actions.len() { - return false; - } - expected_actions.iter().zip(actions.iter()).all(|(expected, actual)| { - expected.matches(actual) - }) - } - (ExpectedAction::MultipleAny, ParserAction::ShowMultiple { .. }) => true, - (ExpectedAction::DbSuggestions { partial, prefix }, - ParserAction::SuggestSubredditsFromDb { partial: p, prefix: pr }) => { - p == partial && pr == prefix - } - - _ => false, - } - } - } - - /// Test helper to simulate a sequence of keystrokes - fn simulate_keystrokes(actions: Vec) -> Vec<(String, ParserAction)> { - let graph = build_reddit_graph(); - let mut current_text = String::new(); - let mut results = Vec::new(); - - for action in actions { - match action { - KeyAction::Type(text) => { - current_text.push_str(&text); - let result = graph.parse(¤t_text); - results.push((current_text.clone(), result)); - } - KeyAction::Tab => { - // Tab accepts the current suggestion if there is one - let result = graph.parse(¤t_text); - if let ParserAction::ShowSuggestions(ref data) = result { - if let Some(ref suggestion) = data.suggestion { - current_text = suggestion.completion.clone(); - let new_result = graph.parse(¤t_text); - results.push((current_text.clone(), new_result)); - } - } - } - - } - } - - results - } - - /// Test a flow using declarative (KeyAction, ExpectedAction) tuples - fn test_flow(name: &str, flow: Vec<(KeyAction, ExpectedAction)>) { - let graph = build_reddit_graph(); - let mut current_text = String::new(); - - println!("\n=== Flow: {} ===", name); - - for (i, (key_action, expected)) in flow.iter().enumerate() { - // Perform the keystroke - match key_action { - KeyAction::Type(text) => { - current_text.push_str(text); - } - KeyAction::Tab => { - // Tab accepts the current suggestion - let result = graph.parse(¤t_text); - if let ParserAction::ShowSuggestions(data) = result { - if let Some(suggestion) = &data.suggestion { - current_text = suggestion.completion.clone(); - } - } - } - } - - // Check the result - let actual_action = graph.parse(¤t_text); - - println!(" Step {}: {:?} -> '{}' -> {:?}", - i + 1, key_action, current_text, actual_action); - - assert!( - expected.matches(&actual_action), - "Flow '{}' failed at step {}\n Expected: {:?}\n Actual: {:?}\n Text: '{}'", - name, i + 1, expected, actual_action, current_text - ); - } - - println!("✓ Flow '{}' passed!", name); - } - - /// Legacy helper for backward compatibility (will be removed) - fn assert_flow( - name: &str, - actions: Vec, - expected_checks: Vec bool>>, - ) { - let results = simulate_keystrokes(actions); - - println!("\n=== Flow: {} ===", name); - for (i, (text, action)) in results.iter().enumerate() { - println!(" Step {}: '{}' -> {:?}", i + 1, text, action); - - if i < expected_checks.len() { - let check = &expected_checks[i]; - assert!( - check(text, action), - "Flow '{}' failed at step {} with text '{}' and action {:?}", - name, i + 1, text, action - ); - } - } - println!("✓ Flow '{}' passed!", name); - } - - #[test] - fn test_https_reddit_tab_flow() { - // Test: typing "https://reddit.com" and pressing tab should give "https://reddit.com/" - assert_flow( - "HTTPS Reddit with Tab", - vec![ - KeyAction::Type("https://reddit.com".to_string()), - KeyAction::Tab, - ], - vec![ - Box::new(|text, action| { - // After typing "https://reddit.com", should get a suggestion - text == "https://reddit.com" && matches!(action, ParserAction::ShowSuggestions(data) if - data.suggestion.as_ref().map(|s| s.completion == "https://reddit.com/").unwrap_or(false) - ) - }), - Box::new(|text, action| { - // After tab, should have "https://reddit.com/" and show guide - text == "https://reddit.com/" && matches!(action, ParserAction::ShowMultiple { .. }) - }), - ], - ); - } - - #[test] - fn test_quick_subreddit_flow() { - // Test: "r" -> TAB -> "rust" (direct alias flow) - assert_flow( - "Quick Subreddit Access", - vec![ - KeyAction::Type("r".to_string()), - KeyAction::Tab, - KeyAction::Type("rust".to_string()), - ], - vec![ - Box::new(|text, action| { - // "r" should suggest "r/" - text == "r" && matches!(action, ParserAction::ShowSuggestions(data) if - data.suggestion.as_ref().map(|s| s.completion == "r/").unwrap_or(false) - ) - }), - Box::new(|text, action| { - // After tab, should have "r/" and show subreddit selection - text == "r/" && matches!(action, ParserAction::ShowMultiple { .. }) - }), - Box::new(|text, action| { - // "r/rust" should resolve the subreddit - text == "r/rust" && matches!(action, ParserAction::ResolveAndDisplaySubreddit { subreddit, prefix } if subreddit == "rust" && prefix == "r/rust") - }), - ], - ); - } - - #[test] - fn test_progressive_completion_flow() { - // Test progressive typing: "r" -> "re" -> "red" -> "redd" -> "reddit" -> TAB - let progressive_actions = vec![ - KeyAction::Type("r".to_string()), - KeyAction::Type("e".to_string()), - KeyAction::Type("d".to_string()), - KeyAction::Type("d".to_string()), - KeyAction::Type("i".to_string()), - KeyAction::Type("t".to_string()), - KeyAction::Tab, - ]; - - let results = simulate_keystrokes(progressive_actions); - - println!("\n=== Progressive Completion Flow ==="); - for (i, (text, action)) in results.iter().enumerate() { - println!(" '{}' -> {:?}", text, action); - - // First step: "r" should suggest "r/" - if i == 0 && text == "r" { - match action { - ParserAction::ShowSuggestions(data) => { - assert_eq!( - data.suggestion.as_ref().unwrap().completion, - "r/", - "Should suggest r/ at 'r'" - ); - } - _ => panic!("Expected suggestion at 'r'"), - } - } - // Other steps before tab should suggest "reddit.com" - else if i > 0 && i < results.len() - 1 { - match action { - ParserAction::ShowSuggestions(data) => { - assert_eq!( - data.suggestion.as_ref().unwrap().completion, - "reddit.com", - "Should suggest reddit.com at '{}'", text - ); - } - _ => panic!("Expected suggestion at '{}'", text), - } - } - } - - // After tab, should have "reddit.com" - let (final_text, _) = results.last().unwrap(); - assert_eq!(final_text, "reddit.com"); - println!("✓ Progressive completion flow passed!"); - } - #[test] - fn test_subreddit_sort_flow() { - // Test navigating to a subreddit and choosing a sort option - assert_flow( - "Subreddit Sort Navigation", - vec![ - KeyAction::Type("reddit.com/r/programming/hot".to_string()), - ], - vec![ - Box::new(|text, action| { - text == "reddit.com/r/programming/hot" && - matches!(action, ParserAction::RenderEntityView { ns, pk } - if ns == "reddit.subreddit" && pk == "programming") - }), - ], - ); + fn parses_short_path() { + assert_eq!(parse_reddit_url("r/rust").unwrap(), "rust"); } #[test] - fn test_user_profile_flow() { - // Test navigating to a user profile - assert_flow( - "User Profile Navigation", - vec![ - KeyAction::Type("reddit.com/u/spez".to_string()), - ], - vec![ - Box::new(|text, action| { - text == "reddit.com/u/spez" && - matches!(action, ParserAction::RenderEntityView { ns, pk } if ns == "reddit.user" && pk == "spez") - }), - ], - ); + fn parses_path_with_trailing_slash() { + assert_eq!(parse_reddit_url("r/rust/").unwrap(), "rust"); } #[test] - fn test_alias_shortcut_flow() { - // Test using the "r/" shortcut - now correctly goes directly to subreddit - assert_flow( - "Alias Shortcut", - vec![ - KeyAction::Type("r/".to_string()), - KeyAction::Type("technology".to_string()), - ], - vec![ - Box::new(|text, action| { - text == "r/" && matches!(action, ParserAction::ShowMultiple { .. }) - }), - Box::new(|text, action| { - text == "r/technology" && - matches!(action, ParserAction::ResolveAndDisplaySubreddit { subreddit, prefix } if subreddit == "technology" && prefix == "r/technology") - }), - ], + fn parses_full_url() { + assert_eq!( + parse_reddit_url("https://www.reddit.com/r/programming/hot").unwrap(), + "programming" ); } #[test] - fn test_www_prefix_flow() { - // Test with www prefix - assert_flow( - "WWW Prefix", - vec![ - KeyAction::Type("www.reddit.com".to_string()), - KeyAction::Tab, - ], - vec![ - Box::new(|text, action| { - // Should suggest adding slash - text == "www.reddit.com" && matches!(action, ParserAction::ShowSuggestions(data) if - data.suggestion.as_ref().map(|s| s.completion == "www.reddit.com/").unwrap_or(false) - ) - }), - Box::new(|text, action| { - // After tab, should show guide - text == "www.reddit.com/" && matches!(action, ParserAction::ShowMultiple { .. }) - }), - ], + fn parses_url_without_scheme() { + assert_eq!( + parse_reddit_url("reddit.com/r/AskReddit").unwrap(), + "askreddit" ); } #[test] - fn test_invalid_path_handling() { - // Test that invalid paths show errors - assert_flow( - "Invalid Path", - vec![ - KeyAction::Type("reddit.com/invalid/path".to_string()), - ], - vec![ - Box::new(|text, action| { - text == "reddit.com/invalid/path" && - matches!(action, ParserAction::ShowError(_)) - }), - ], - ); - } - - #[test] - fn test_complete_user_journey() { - // Test a complete user journey: type partial URL, tab complete, navigate to subreddit - assert_flow( - "Complete User Journey", - vec![ - KeyAction::Type("http".to_string()), - KeyAction::Type("s://r".to_string()), - KeyAction::Tab, - KeyAction::Type("/".to_string()), - KeyAction::Type("r/".to_string()), - KeyAction::Type("programming".to_string()), - KeyAction::Type("/".to_string()), - KeyAction::Type("top".to_string()), - ], - vec![ - Box::new(|text, action| { - // "http" should suggest "https://" - text == "http" && matches!(action, ParserAction::ShowSuggestions(data) if - data.suggestion.as_ref().map(|s| s.completion == "https://").unwrap_or(false) - ) - }), - Box::new(|text, action| { - // "https://r" should suggest "https://reddit.com" - text == "https://r" && matches!(action, ParserAction::ShowSuggestions(data) if - data.suggestion.as_ref().map(|s| s.completion == "https://reddit.com").unwrap_or(false) - ) - }), - Box::new(|text, action| { - // After tab, should have "https://reddit.com" - text == "https://reddit.com" && matches!(action, ParserAction::ShowSuggestions(_)) - }), - Box::new(|text, action| { - // "https://reddit.com/" should show guide - text == "https://reddit.com/" && matches!(action, ParserAction::ShowMultiple { .. }) - }), - Box::new(|text, action| { - // "https://reddit.com/r/" should show subreddit selection - text == "https://reddit.com/r/" && matches!(action, ParserAction::ShowMultiple { .. }) - }), - Box::new(|text, action| { - // "https://reddit.com/r/programming" should resolve subreddit - text == "https://reddit.com/r/programming" && - matches!(action, ParserAction::ResolveAndDisplaySubreddit { subreddit, prefix } - if subreddit == "programming" && prefix == "https://reddit.com/r/programming") - }), - Box::new(|text, action| { - // "https://reddit.com/r/programming/" should show sort options - text == "https://reddit.com/r/programming/" && - matches!(action, ParserAction::ShowStaticGuide { .. }) - }), - Box::new(|text, action| { - // "https://reddit.com/r/programming/top" should render entity view - text == "https://reddit.com/r/programming/top" && - matches!(action, ParserAction::RenderEntityView { ns, pk } - if ns == "reddit.subreddit" && pk == "programming") - }), - ], - ); - } - - #[test] - fn test_multiple_tab_completions() { - // Test multiple tab completions in sequence - let actions = vec![ - KeyAction::Type("h".to_string()), - KeyAction::Tab, // Complete to "https://" - KeyAction::Type("r".to_string()), - KeyAction::Tab, // Complete to "https://reddit.com" - KeyAction::Type("/".to_string()), - ]; - - let results = simulate_keystrokes(actions); - - println!("\n=== Multiple Tab Completions ==="); - for (i, (text, _action)) in results.iter().enumerate() { - println!(" Step {}: '{}'", i + 1, text); - } - - // Verify the final state - assert_eq!(results[1].0, "https://"); // After first tab - assert_eq!(results[3].0, "https://reddit.com"); // After second tab - assert_eq!(results[4].0, "https://reddit.com/"); // After typing / - - println!("✓ Multiple tab completions work correctly!"); - } - - // === CONVENIENCE MACROS FOR CLEANER TESTS === - - macro_rules! flow { - ($(($key:expr, $expected:expr)),* $(,)?) => { - vec![$(($key, $expected)),*] - }; - } - - macro_rules! type_text { - ($text:expr) => { - KeyAction::Type($text.to_string()) - }; - } - - macro_rules! suggests { - ($completion:expr) => { - ExpectedAction::Suggestion { completion: $completion.to_string() } - }; - } - - macro_rules! renders_subreddit { - ($subreddit:expr) => { - ExpectedAction::RenderSubreddit { subreddit: $subreddit.to_string(), sort: None } - }; - ($subreddit:expr, $sort:expr) => { - ExpectedAction::RenderSubreddit { - subreddit: $subreddit.to_string(), - sort: Some($sort.to_string()) - } - }; - } - - macro_rules! renders_subreddit_comments { - ($subreddit:expr) => { - ExpectedAction::RenderSubredditComments { subreddit: $subreddit.to_string() } - }; - } - - macro_rules! resolves_subreddit { - ($subreddit:expr, $prefix:expr) => { - ExpectedAction::ResolveSubreddit { - subreddit: $subreddit.to_string(), - prefix: $prefix.to_string() - } - }; - } - - macro_rules! shows_guide { - ($title_contains:expr) => { - ExpectedAction::Guide { title_contains: $title_contains.to_string() } - }; - } - - macro_rules! multiple { - ($($action:expr),* $(,)?) => { - ExpectedAction::Multiple { expected_actions: vec![$($action),*] } - }; - } - - macro_rules! scrolling_suggestions { - ($($completion:expr),* $(,)?) => { - ExpectedAction::ScrollingSuggestions { completions: vec![$($completion.to_string()),*] } - }; - } - - macro_rules! db_suggestions { - ($partial:expr, $prefix:expr) => { - ExpectedAction::DbSuggestions { partial: $partial.to_string(), prefix: $prefix.to_string() } - }; - } - - // === NEW DECLARATIVE TESTS === - - #[test] - fn test_declarative_https_tab_flow() { - test_flow("HTTPS Tab Completion", vec![ - (KeyAction::Type("https://reddit.com".to_string()), - ExpectedAction::Suggestion { completion: "https://reddit.com/".to_string() }), - (KeyAction::Tab, - multiple![ - scrolling_suggestions!("https://reddit.com/r/", "https://reddit.com/u/"), - shows_guide!("Welcome to Sorter") - ]), - ]); - } - - #[test] - fn test_declarative_quick_subreddit_flow() { - test_flow("Quick Subreddit Flow", vec![ - (KeyAction::Type("r".to_string()), - ExpectedAction::Suggestion { completion: "r/".to_string() }), - (KeyAction::Tab, - ExpectedAction::MultipleAny), // r/ shows subreddit selection - (KeyAction::Type("rust".to_string()), - ExpectedAction::ResolveSubreddit { subreddit: "rust".to_string(), prefix: "r/rust".to_string() }), - ]); - } - - #[test] - fn test_declarative_complete_journey() { - test_flow("Complete User Journey", vec![ - (KeyAction::Type("http".to_string()), - ExpectedAction::Suggestion { completion: "https://".to_string() }), - (KeyAction::Type("s://r".to_string()), - ExpectedAction::Suggestion { completion: "https://reddit.com".to_string() }), - (KeyAction::Tab, - ExpectedAction::Suggestion { completion: "https://reddit.com/".to_string() }), - (KeyAction::Type("/r/programming/top".to_string()), - ExpectedAction::RenderSubreddit { - subreddit: "programming".to_string(), - sort: Some("top".to_string()) - }), - ]); - } - - #[test] - fn test_declarative_user_profile() { - test_flow("User Profile Navigation", vec![ - (KeyAction::Type("reddit.com/u/spez".to_string()), - ExpectedAction::RenderUser { username: "spez".to_string() }), - ]); - } - - #[test] - fn test_declarative_error_handling() { - test_flow("Error Handling", vec![ - (KeyAction::Type("reddit.com/invalid/path".to_string()), - ExpectedAction::Error { error_type: "InvalidPath".to_string() }), - ]); - } - - #[test] - fn test_declarative_progressive_completion() { - test_flow("Progressive Completion", vec![ - (KeyAction::Type("r".to_string()), - ExpectedAction::Suggestion { completion: "r/".to_string() }), - (KeyAction::Type("e".to_string()), - ExpectedAction::Suggestion { completion: "reddit.com".to_string() }), - (KeyAction::Type("d".to_string()), - ExpectedAction::Suggestion { completion: "reddit.com".to_string() }), - (KeyAction::Type("dit".to_string()), - ExpectedAction::Suggestion { completion: "reddit.com".to_string() }), - (KeyAction::Tab, - ExpectedAction::Suggestion { completion: "reddit.com/".to_string() }), - ]); - } - - #[test] - fn test_declarative_subreddit_guide() { - test_flow("Subreddit Guide", vec![ - (KeyAction::Type("reddit.com/r/programming/".to_string()), - ExpectedAction::Guide { title_contains: "What to sort".to_string() }), - ]); - } - - #[test] - fn test_clean_macro_example() { - // This is what the tests can look like with macros! - test_flow("Clean Macro Example", flow![ - (type_text!("r"), suggests!("r/")), - (KeyAction::Tab, ExpectedAction::MultipleAny), - (type_text!("rust/hot"), renders_subreddit!("rust", "hot")), - ]); - } - - #[test] - fn test_unified_subreddit_resolution_flow() { - // This test demonstrates the new unified behavior: - // - r/programming (exact) → tries exact match first - // - r/pro (partial) → tries exact match, then suggestions + TAB completion - - test_flow("Unified Resolution: Exact Match", flow![ - (type_text!("r/programming"), resolves_subreddit!("programming", "r/programming")), - ]); - - test_flow("Unified Resolution: Partial Match", flow![ - (type_text!("r/pro"), resolves_subreddit!("pro", "r/pro")), - ]); - - // Both go through the same action type, but dispatcher handles them differently: - // - If "programming" exists in DB → shows EntityView immediately - // - If "pro" doesn't exist in DB → shows Multiple with: - // 1. Suggestions (for TAB completion to best match) - // 2. Selection (for clickable options including import) - } - - #[test] - fn test_tab_completion_workflow_unified() { - // This demonstrates the desired TAB completion behavior: - // r/pro + TAB → r/programming (if "programming" is the best DB match) - - // Note: This test shows the PARSER behavior. The actual TAB completion - // happens in the frontend when it receives the Multiple response containing - // both Suggestions (for TAB) and Selection (for click options). - - let graph = build_reddit_graph(); - - // 1. Parser generates unified action for partial input - match graph.parse("r/pro") { - ParserAction::ResolveAndDisplaySubreddit { subreddit, prefix } => { - assert_eq!(subreddit, "pro"); - assert_eq!(prefix, "r/pro"); - println!("✓ Parser correctly identifies 'r/pro' as subreddit resolution"); - } - _ => panic!("Expected ResolveAndDisplaySubreddit for 'r/pro'"), - } - - // 2. When dispatcher runs (in real app), it will return Multiple response with: - // - Suggestions: { completion: "r/programming" } (for TAB) - // - Selection: [ "Import r/pro", "r/programming", ... ] (for clicks) - - println!("✓ TAB completion workflow: r/pro → ResolveAndDisplaySubreddit → Multiple(Suggestions + Selection)"); - } - - #[test] - fn test_ultra_clean_user_journey() { - test_flow("Ultra Clean User Journey", flow![ - (type_text!("h"), suggests!("https://")), - (type_text!("ttps://r"), suggests!("https://reddit.com")), - (KeyAction::Tab, suggests!("https://reddit.com/")), - (type_text!("/u/spez"), ExpectedAction::RenderUser { username: "spez".to_string() }), - ]); - } - - // === TESTS FROM parser.tdsl === - - #[test] - fn test_tdsl_basic_reddit_progression() { - // Tests from parser.tdsl: r -> r/, then re -> reddit.com with all intermediate steps - test_flow("TDSL Basic Reddit Progression", flow![ - (type_text!("r"), suggests!("r/")), - (type_text!("e"), suggests!("reddit.com")), - (type_text!("d"), suggests!("reddit.com")), - (type_text!("d"), suggests!("reddit.com")), - (type_text!("i"), suggests!("reddit.com")), - (type_text!("t"), suggests!("reddit.com")), - (type_text!("."), suggests!("reddit.com")), - (type_text!("c"), suggests!("reddit.com")), - (type_text!("o"), suggests!("reddit.com")), - (KeyAction::Tab, suggests!("reddit.com/")), - ]); - } - - #[test] - fn test_tdsl_reddit_com_slash_infographic() { - // reddit.com/ -> {show infographic explaining that u (sort user posts) and r (sort subreddit posts)} - test_flow("TDSL Reddit.com/ Infographic", flow![ - (type_text!("reddit.com/"), ExpectedAction::MultipleAny), - ]); - } - - #[test] - fn test_tdsl_subreddit_selection() { - // reddit.com/r/ -> reddit.com/r/{randomly chose sub from list} - test_flow("TDSL Subreddit Selection", flow![ - (type_text!("reddit.com/r/"), ExpectedAction::MultipleAny), - ]); - } - - #[test] - fn test_tdsl_subreddit_view() { - // reddit.com/r/{sub} -> {resolve subreddit (exact match or suggestions)} - test_flow("TDSL Subreddit View", flow![ - (type_text!("reddit.com/r/programming"), resolves_subreddit!("programming", "reddit.com/r/programming")), - ]); - } - - #[test] - fn test_tdsl_subreddit_slash_infographic() { - // reddit.com/r/{sub}/ -> {show infographic or something} - test_flow("TDSL Subreddit Slash Infographic", flow![ - (type_text!("reddit.com/r/programming/"), shows_guide!("What to sort")), - ]); - } - - #[test] - fn test_tdsl_subreddit_comments() { - // reddit.com/r/{sub}/comments/{randomly chose comment from sql} - test_flow("TDSL Subreddit Comments", flow![ - (type_text!("reddit.com/r/programming/comments"), renders_subreddit_comments!("programming")), - ]); - } - - #[test] - fn test_tdsl_h_to_https() { - // h->https:// (show supported domains) - test_flow("TDSL H to HTTPS", flow![ - (type_text!("h"), suggests!("https://")), - ]); - } - - #[test] - fn test_tdsl_composable_https_reddit() { - // https://r->https://reddit.com/ - test_flow("TDSL Composable HTTPS Reddit", flow![ - (type_text!("https://r"), suggests!("https://reddit.com")), - ]); - } - - #[test] - fn test_tdsl_composable_https_www() { - // https://w->https://www. - test_flow("TDSL Composable HTTPS WWW", flow![ - (type_text!("https://w"), suggests!("https://www.")), - ]); - } - - #[test] - fn test_tdsl_composable_https_www_reddit() { - // https://www.r->https://www.reddit.com/ - test_flow("TDSL Composable HTTPS WWW Reddit", flow![ - (type_text!("https://www.r"), suggests!("https://www.reddit.com")), - ]); - } - - #[test] - fn test_tdsl_full_composable_chain() { - // Complete chain showing composability: h -> https:// -> https://www.reddit.com - test_flow("TDSL Full Composable Chain Step 1", flow![ - (type_text!("h"), suggests!("https://")), - ]); - - test_flow("TDSL Full Composable Chain Step 2", flow![ - (type_text!("https://w"), suggests!("https://www.")), - ]); - - test_flow("TDSL Full Composable Chain Step 3", flow![ - (type_text!("https://www.r"), suggests!("https://www.reddit.com")), - ]); - } - - #[test] - fn test_tdsl_progressive_reddit_paths() { - // Test various reddit paths work as expected - test_flow("TDSL Progressive Reddit Paths", flow![ - (type_text!("reddit.com"), suggests!("reddit.com/")), - (KeyAction::Tab, ExpectedAction::MultipleAny), - ]); - } - - #[test] - fn test_tdsl_subreddit_sorting_options() { - // Test that subreddit sorting options work as described - test_flow("TDSL Subreddit Sorting", flow![ - (type_text!("reddit.com/r/rust/hot"), renders_subreddit!("rust", "hot")), - ]); - - test_flow("TDSL Subreddit Top", flow![ - (type_text!("reddit.com/r/rust/top"), renders_subreddit!("rust", "top")), - ]); - - test_flow("TDSL Subreddit New", flow![ - (type_text!("reddit.com/r/rust/new"), renders_subreddit!("rust", "new")), - ]); - } - - #[test] - fn test_tdsl_all_reddit_prefixes() { - // Test all the prefixes mentioned in parser.tdsl work - // "r" now suggests "r/", all others suggest "reddit.com" - let prefixes_to_reddit = vec!["re", "red", "redd", "reddi", "reddit", "reddit.", "reddit.c", "reddit.co"]; - - // Test "r" separately since it now suggests "r/" - test_flow("TDSL Prefix: r", flow![ - (type_text!("r"), suggests!("r/")), - ]); - - for prefix in prefixes_to_reddit { - test_flow(&format!("TDSL Prefix: {}", prefix), flow![ - (type_text!(prefix), suggests!("reddit.com")), - ]); - } - } - - #[test] - fn test_tdsl_protocol_combinations() { - // Test various protocol combinations from parser.tdsl - let test_cases = vec![ - ("http://r", "http://reddit.com"), - ("https://r", "https://reddit.com"), - ("www.r", "www.reddit.com"), - ("https://www.r", "https://www.reddit.com"), - ("http://www.r", "http://www.reddit.com"), - ]; - - for (input, expected) in test_cases { - test_flow(&format!("TDSL Protocol: {}", input), flow![ - (type_text!(input), suggests!(expected)), - ]); - } + fn rejects_empty() { + assert!(parse_reddit_url("").is_err()); + assert!(parse_reddit_url(" ").is_err()); } #[test] - fn test_tdsl_edge_case_completions() { - // Test edge cases mentioned in parser.tdsl - test_flow("TDSL Reddit.com completion", flow![ - (type_text!("reddit.com"), suggests!("reddit.com/")), - ]); - - // Test that typing full reddit.com suggests the slash - test_flow("TDSL Full domain completion", flow![ - (type_text!("reddit.com"), suggests!("reddit.com/")), - (KeyAction::Tab, ExpectedAction::MultipleAny), - ]); - } - - #[test] - fn test_real_user_trace_2025_08_07_fixed() { - // Based on actual WebSocket trace from 2025-08-07T01:35:46Z - // This test shows the CORRECT behavior after fixing the protocol preservation bug - test_flow("Real User Trace: Progressive Typing with Tab Completions (Fixed)", flow![ - // User started typing "h" - (type_text!("h"), suggests!("https://")), - - // User continued to "ht" - (type_text!("t"), suggests!("https://")), - - // User finished typing "https://" (trace shows full protocol) - (type_text!("tps://"), suggests!("https://")), - - // User started typing "r" after protocol - (type_text!("r"), suggests!("https://reddit.com")), - - // User continued typing "re" - (type_text!("e"), suggests!("https://reddit.com")), - - // User typed out or completed "https://reddit.com" - (type_text!("ddit.com"), suggests!("https://reddit.com/")), - - // User accepted completion to "https://reddit.com/" - // NOW suggestions should preserve the https:// protocol - (KeyAction::Tab, multiple![ - scrolling_suggestions!("https://reddit.com/r/", "https://reddit.com/u/"), // This is the key fix! - shows_guide!("Welcome to Sorter") - ]), - ]); - } - - #[test] - fn test_protocol_preservation_bug_fix() { - // This test specifically verifies the fix for the protocol preservation bug - test_flow("Protocol Preservation: HTTPS Reddit Homepage", flow![ - (type_text!("https://reddit.com/"), multiple![ - scrolling_suggestions!("https://reddit.com/r/", "https://reddit.com/u/"), // Should preserve https:// - shows_guide!("Welcome to Sorter") - ]), - ]); - - // Test that subreddit selection preserves protocol - test_flow("Protocol Preservation: HTTPS Subreddit Selection", flow![ - (type_text!("https://reddit.com/r/"), multiple![ - scrolling_suggestions!("https://reddit.com/r/programming", "https://reddit.com/r/askreddit", "https://reddit.com/r/aww", "https://reddit.com/r/rust", "https://reddit.com/r/webdev"), // Should preserve https:// - db_suggestions!("https://reddit.com/r/", "https://reddit.com/r/") - ]), - ]); - - // Test with different protocols - test_flow("Protocol Preservation: HTTP", flow![ - (type_text!("http://reddit.com/"), multiple![ - scrolling_suggestions!("http://reddit.com/r/", "http://reddit.com/u/"), // Should preserve http:// - shows_guide!("Welcome to Sorter") - ]), - ]); - - test_flow("Protocol Preservation: WWW", flow![ - (type_text!("www.reddit.com/"), multiple![ - scrolling_suggestions!("www.reddit.com/r/", "www.reddit.com/u/"), // Should preserve www. - shows_guide!("Welcome to Sorter") - ]), - ]); - - // Test that plain reddit.com still works - test_flow("Protocol Preservation: Plain Domain", flow![ - (type_text!("reddit.com/"), multiple![ - scrolling_suggestions!("reddit.com/r/", "reddit.com/u/"), // No protocol prefix - shows_guide!("Welcome to Sorter") - ]), - ]); - } - - #[test] - fn test_user_navigation_pattern() { - // Models how users actually navigate: type → tab → click suggestion → end up at destination - // This captures the "jump" from https://reddit.com/ to reddit.com/r/ seen in the trace - test_flow("User Navigation: Protocol to Domain", flow![ - // User types and gets to homepage - (type_text!("https://reddit.com/"), ExpectedAction::MultipleAny), - ]); - - // Then they navigate (perhaps clicking a suggestion) to subreddit selection - test_flow("User Navigation: Click to Subreddit", flow![ - // This is where they ended up - the suggestion in the guide probably said "reddit.com/r/" - (type_text!("reddit.com/r/"), ExpectedAction::MultipleAny), - ]); - } - - #[test] - fn test_progressive_typing_pattern() { - // Based on the trace pattern - users often type character by character - // This tests the exact sequence of suggestions they would see - test_flow("Progressive Typing Pattern", flow![ - (type_text!("h"), suggests!("https://")), - (type_text!("t"), suggests!("https://")), // Still suggests https:// - (type_text!("t"), suggests!("https://")), // ht -> htt, still suggests https:// - (type_text!("p"), suggests!("https://")), // http should still suggest https:// - (type_text!("s"), suggests!("https://")), // https should suggest https:// - (type_text!("://"), suggests!("https://")), // Even complete protocol still suggests itself - ]); - } - - #[test] - fn test_tab_completion_workflow() { - // Test what happens when user uses tab completions strategically - test_flow("Strategic Tab Completion Workflow", flow![ - // Start typing, get suggestion - (type_text!("h"), suggests!("https://")), - - // Accept suggestion with tab - this should move us to "https://" - (KeyAction::Tab, suggests!("https://")), // After tab, we're at "https://" which still suggests itself - - // Start typing reddit - (type_text!("r"), suggests!("https://reddit.com")), - - // Accept reddit suggestion - (KeyAction::Tab, suggests!("https://reddit.com/")), - - // Accept final suggestion to get to homepage - (KeyAction::Tab, ExpectedAction::MultipleAny), - ]); - } - - // Keep the original tests as well - #[test] - fn test_reddit_prefix_autocomplete() { - let graph = build_reddit_graph(); - - // "r" now suggests "r/", others suggest "reddit.com" - match graph.parse("r") { - ParserAction::ShowSuggestions(data) => { - assert_eq!(data.suggestion.as_ref().unwrap().completion, "r/"); - println!("✓ 'r' → r/"); - } - _ => panic!("Expected suggestion for 'r'"), - } - - // Test other prefixes that should suggest "reddit.com" - let prefixes = vec!["re", "red", "redd", "reddi", "reddit", "reddit.", "reddit.c", "reddit.co"]; - - for prefix in prefixes { - match graph.parse(prefix) { - ParserAction::ShowSuggestions(data) => { - assert_eq!(data.suggestion.as_ref().unwrap().completion, "reddit.com"); - println!("✓ '{}' → reddit.com", prefix); - } - _ => panic!("Expected suggestion for '{}'", prefix), - } - } - } - - #[test] - fn test_protocol_composition() { - let graph = build_reddit_graph(); - - // Test protocol + reddit compositions - let tests = vec![ - ("https://r", "https://reddit.com"), - ("https://re", "https://reddit.com"), - ("https://reddit", "https://reddit.com"), - ("https://www.r", "https://www.reddit.com"), - ("https://www.reddit", "https://www.reddit.com"), - ("http://r", "http://reddit.com"), - ("www.r", "www.reddit.com"), - ]; - - for (input, expected) in tests { - match graph.parse(input) { - ParserAction::ShowSuggestions(data) => { - assert_eq!(data.suggestion.as_ref().unwrap().completion, expected); - println!("✓ '{}' → {}", input, expected); - } - _ => panic!("Expected suggestion for '{}'", input), - } - } - } - - #[test] - fn test_alias_and_full_paths() { - let graph = build_reddit_graph(); - - // reddit.com/ should show guide, r/ should show subreddit selection - match graph.parse("reddit.com/") { - ParserAction::ShowMultiple { actions } => { - let has_guide = actions.iter() - .any(|a| matches!(a, ParserAction::ShowStaticGuide { .. })); - assert!(has_guide, "Path 'reddit.com/' should show guide"); - println!("✓ 'reddit.com/' shows Reddit root guide"); - } - _ => panic!("Expected Multiple action for 'reddit.com/'"), - } - - match graph.parse("r/") { - ParserAction::ShowMultiple { actions } => { - let has_scrolling_suggestions = actions.iter() - .any(|a| matches!(a, ParserAction::ShowScrollingSuggestions { .. })); - let has_db_suggestions = actions.iter() - .any(|a| matches!(a, ParserAction::SuggestSubredditsFromDb { .. })); - assert!(has_scrolling_suggestions && has_db_suggestions, - "Path 'r/' should show scrolling suggestions and DB suggestions"); - println!("✓ 'r/' shows subreddit selection"); - } - _ => panic!("Expected Multiple action for 'r/'"), - } - } - - #[test] - fn test_deep_navigation() { - let graph = build_reddit_graph(); - - // Test navigation to subreddit - now uses ResolveAndDisplaySubreddit - match graph.parse("reddit.com/r/rust") { - ParserAction::ResolveAndDisplaySubreddit { subreddit, prefix } => { - assert_eq!(subreddit, "rust"); - assert_eq!(prefix, "reddit.com/r/rust"); - println!("✓ reddit.com/r/rust recognized"); - } - _ => panic!("Expected ResolveAndDisplaySubreddit for subreddit"), - } - - // Test with alias (r/ goes directly to subreddit, no double r/) - match graph.parse("r/programming") { - ParserAction::ResolveAndDisplaySubreddit { subreddit, prefix } => { - assert_eq!(subreddit, "programming"); - assert_eq!(prefix, "r/programming"); - println!("✓ r/programming (alias) recognized"); - } - _ => panic!("Expected ResolveAndDisplaySubreddit for subreddit via alias"), - } + fn rejects_garbage() { + assert!(parse_reddit_url("hello world").is_err()); } } diff --git a/server/src/parser_action.rs b/server/src/parser_action.rs deleted file mode 100644 index 2b98556b562d548ce231a726f9e704f595e8f4a1..0000000000000000000000000000000000000000 --- a/server/src/parser_action.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! Parser output actions — graph handlers return these; HTML render turns them into markup. - -#[derive(Debug, Clone, PartialEq)] -pub struct Suggestion { - pub text: String, - pub completion: String, - pub description: Option, - pub score: f64, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct ScrollingSuggestion { - pub completion: String, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct GuideOption { - pub key: String, - pub label: String, - pub description: String, - pub completion: String, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct SuggestionsData { - pub query: String, - pub suggestion: Option, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct ErrorData { - pub error_type: String, - pub message: String, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum ParserAction { - ShowSuggestions(SuggestionsData), - ShowScrollingSuggestions { - query: String, - suggestions: Vec, - interval_ms: u64, - r#loop: bool, - }, - ShowStaticGuide { - query: String, - title: String, - subtitle: String, - options: Vec, - }, - ShowMultiple { - actions: Vec, - }, - ShowError(ErrorData), - SuggestSubredditsFromDb { - partial: String, - prefix: String, - }, - ResolveAndDisplaySubreddit { - subreddit: String, - prefix: String, - }, - RenderEntityView { - ns: String, - pk: String, - }, -} - -impl ParserAction { - pub fn suggest(query: String, suggestion: Option) -> Self { - Self::ShowSuggestions(SuggestionsData { query, suggestion }) - } - - pub fn error(error_type: String, message: String) -> Self { - Self::ShowError(ErrorData { - error_type, - message, - }) - } - - pub fn multiple(actions: Vec) -> Self { - Self::ShowMultiple { actions } - } - - pub fn scrolling_suggestions( - query: String, - suggestions: Vec, - interval_ms: u64, - r#loop: bool, - ) -> Self { - Self::ShowScrollingSuggestions { - query, - suggestions, - interval_ms, - r#loop, - } - } - - pub fn guide( - query: String, - title: String, - subtitle: String, - options: Vec, - ) -> Self { - Self::ShowStaticGuide { - query, - title, - subtitle, - options, - } - } - - /// Primary tab-completion string, if any. - pub fn primary_completion(&self) -> Option<&str> { - match self { - Self::ShowSuggestions(data) => data - .suggestion - .as_ref() - .map(|s| s.completion.as_str()), - Self::ShowMultiple { actions } => actions.iter().find_map(|a| a.primary_completion()), - _ => None, - } - } -} diff --git a/server/src/parser_render.rs b/server/src/parser_render.rs index 05e4f519cc3832392282b319272b61c104eaabf6..f2341afe21476b689a536137798d97277211a962 100644 --- a/server/src/parser_render.rs +++ b/server/src/parser_render.rs @@ -2,12 +2,9 @@ use maud::{html, Markup}; use crate::{ form_template::template_json_compact, - parser_action::{GuideOption, ParserAction, ScrollingSuggestion, Suggestion}, ui_action::UI_RPC_FIELD, }; -const SAMPLE_SUBREDDITS: &[&str] = &["programming", "askreddit", "rust", "webdev", "aww"]; - fn parse_query_rpc_template() -> String { template_json_compact(&serde_json::json!({ "action": "parse_query", @@ -16,193 +13,32 @@ fn parse_query_rpc_template() -> String { .expect("parse_query rpc template") } -fn completion_button(completion: &str, label: &str, primary: bool) -> Markup { - let class = if primary { - "parser-completion parser-suggestion-primary btn-link" - } else { - "parser-completion btn-link" - }; - html! { - button - type="button" - class=(class) - data-completion=(completion) - title="Use this path" { - (label) - } - } -} - -fn render_suggestion(s: &Suggestion) -> Markup { - let desc = s - .description - .as_deref() - .unwrap_or("Tab to complete"); - html! { - p class="parser-suggestion" { - (completion_button(&s.completion, &s.completion, true)) - span class="muted small" { " — " (desc) } - } - } -} - -fn render_scrolling(suggestions: &[ScrollingSuggestion]) -> Markup { - html! { - div class="parser-scrolling muted small" { - p { "Examples:" } - ul class="parser-scroll-list" { - @for s in suggestions { - li { (completion_button(&s.completion, &s.completion, false)) } - } - } - } - } -} - -fn render_guide(title: &str, subtitle: &str, options: &[GuideOption]) -> Markup { - html! { - div class="parser-guide" { - h3 { (title) } - p class="muted" { (subtitle) } - ul class="parser-guide-list" { - @for opt in options { - li { - strong { (opt.key) ": " } - (completion_button(&opt.completion, &opt.label, false)) - span class="muted small" { " — " (opt.description) } - } - } - } - } - } -} - -fn render_db_subs(partial: &str, prefix: &str) -> Markup { - let needle = partial.to_lowercase(); - let matches: Vec<_> = SAMPLE_SUBREDDITS - .iter() - .filter(|s| s.contains(&needle) || prefix.ends_with('/') && needle.is_empty()) - .take(6) - .collect(); - html! { - @if !matches.is_empty() { - div class="parser-db-subs muted small" { - p { "Subreddits:" } - ul { - @for sub in matches { - @let completion = format!("{prefix}{sub}"); - li { (completion_button(&completion, &format!("r/{sub}"), false)) } - } - } - } - } - } -} - -fn render_action(action: &ParserAction) -> Markup { - match action { - ParserAction::ShowSuggestions(data) => html! { - div class="parser-result parser-suggestions" { - @if let Some(s) = &data.suggestion { - (render_suggestion(s)) - } @else { - p class="muted" { "No completion" } - } - } - }, - ParserAction::ShowScrollingSuggestions { suggestions, .. } => { - render_scrolling(suggestions) - } - ParserAction::ShowStaticGuide { - title, - subtitle, - options, - .. - } => render_guide(title, subtitle, options), - ParserAction::ShowMultiple { actions } => html! { - div class="parser-multiple" { - @for a in actions { - (render_action(a)) - } - } - }, - ParserAction::ShowError(data) => html! { - p class="parser-error muted" { - strong { (data.error_type) ": " } - (data.message) - } - }, - ParserAction::SuggestSubredditsFromDb { partial, prefix } => { - render_db_subs(partial, prefix) - } - ParserAction::ResolveAndDisplaySubreddit { subreddit, prefix } => html! { - div class="parser-resolve" { - p { - "Subreddit " - strong { "r/" (subreddit) } - @if subreddit.len() <= 3 { - span class="muted small" { " (partial — tab or pick a match)" } - } - } - p { - a class="parser-rank-link" - href=(format!("/?sub={subreddit}")) { - "Rank r/" (subreddit) " →" - } - } - (render_db_subs(subreddit, prefix)) - } - }, - ParserAction::RenderEntityView { ns, pk } => html! { - div class="parser-entity" { - p { - "Would open " - code { (ns) "/" (pk) } - } - } - }, - } -} - -/// Parser output panel (inner content for `#parser-panel`). -pub fn parser_panel(query: &str, action: &ParserAction) -> Markup { +/// Navigate panel: paste a Reddit URL and click Go. +pub fn navigate_panel(query: &str, error: Option<&str>) -> Markup { html! { section id="parser-panel" class="demo-panel" { h2 { "Navigate" } p class="muted small" { - "Type a Reddit path — " - code { "r/rust" } - ", " - code { "reddit.com/r/programming/hot" } - ", etc. Tab completes; each keystroke posts " - code { "__rpc__" } - " to " - code { "/ui" } - "." + "Paste a Reddit URL or " + code { "r/subreddit" } + " path, then click Go to rank that subreddit." } form method="post" action="/ui" id="parser-form" { - input - type="text" + textarea name="query" id="parser-input" - value=(query) - placeholder="r/ or reddit.com/…" + rows="3" + placeholder="https://reddit.com/r/rust or r/rust" autocomplete="off" - spellcheck="false"; + spellcheck="false" { + (query) + } input type="hidden" name=(UI_RPC_FIELD) value=(parse_query_rpc_template()); + button type="submit" class="btn-primary" { "Go" } } - div id="parser-output" { - @if query.is_empty() { - p class="muted" { "Start typing…" } - } @else { - (render_action(action)) - } + @if let Some(msg) = error { + p class="parser-error muted" { (msg) } } } } } - -/// Wrap panel HTML for Idiomorph (morph `#parser-panel` only). -pub fn parser_panel_morph(query: &str, action: &ParserAction) -> Markup { - parser_panel(query, action) -} diff --git a/server/src/ui_action.rs b/server/src/ui_action.rs index 8c357b133599b798a9c06a77a826bcef05a3a407..0e030b3448b8e45acbe49d2de47ea26372445c54 100644 --- a/server/src/ui_action.rs +++ b/server/src/ui_action.rs @@ -22,7 +22,7 @@ pub enum HtmlUiAction { #[serde(default)] scope: String, }, - /// Parse address-bar query via Reddit transition graph; morph `#parser-panel`. + /// Parse pasted Reddit URL/path; redirect to subreddit ranking on success. ParseQuery { query: String, }, diff --git a/server/static/sorter_ui.js b/server/static/sorter_ui.js index 1e5c3c13d6f7d8f180a4126ba25b44e9801cdb5d..9c475d8e076ba527aaf7a25c177d0d651bd46ca9 100644 --- a/server/static/sorter_ui.js +++ b/server/static/sorter_ui.js @@ -19,39 +19,6 @@ }).then(evalJs); } - // Parser responses race: a slow response for an earlier keystroke can arrive - // after a newer one and clobber the panel. Tag each request with a monotonic - // sequence number and only apply a response if it is newer than the last one - // applied, so stale (superseded) responses are discarded. - var parserSeq = 0; - var parserApplied = 0; - - function postParserForm(form) { - var mySeq = ++parserSeq; - return fetch(form.action, { - method: 'POST', - body: new URLSearchParams(new FormData(form)), - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - credentials: 'same-origin', - }).then(function (resp) { - return resp.text(); - }).then(function (js) { - if (mySeq <= parserApplied) return; - parserApplied = mySeq; - evalJs(js); - }); - } - - var parserTimer = null; - - function scheduleParserInput(input) { - if (parserTimer) clearTimeout(parserTimer); - parserTimer = setTimeout(function () { - var form = document.getElementById('parser-form'); - if (form) postParserForm(form); - }, 120); - } - function initSorterUi() { document.addEventListener('submit', async function (e) { var f = e.target; @@ -67,38 +34,6 @@ if (firstField) firstField.focus(); } }); - - document.addEventListener('input', function (e) { - if (e.target && e.target.id === 'parser-input') { - scheduleParserInput(e.target); - } - }); - - document.addEventListener('keydown', function (e) { - if (!e.target || e.target.id !== 'parser-input') return; - if (e.key !== 'Tab') return; - var completion = - e.target.dataset.completion || - (function () { - var btn = document.querySelector('#parser-output .parser-suggestion-primary'); - return btn && btn.getAttribute('data-completion'); - })(); - if (!completion) return; - e.preventDefault(); - e.target.value = completion; - scheduleParserInput(e.target); - }); - - document.addEventListener('click', function (e) { - var btn = e.target.closest('.parser-completion'); - if (!btn) return; - var input = document.getElementById('parser-input'); - if (!input) return; - var completion = btn.getAttribute('data-completion'); - if (!completion) return; - input.value = completion; - scheduleParserInput(input); - }); } if (document.readyState === 'loading') { diff --git a/server/static/theme_default.css b/server/static/theme_default.css index c5fc9e7abf865ed689f58ff0763d3656d73e35f5..6ad0ac712bbc840bedee60f613794de9385fbbd1 100644 --- a/server/static/theme_default.css +++ b/server/static/theme_default.css @@ -129,34 +129,12 @@ code { background: var(--bg); color: var(--fg); font-size: 1rem; + font-family: inherit; + resize: vertical; } -.btn-link { - background: none; - border: none; - padding: 0; - color: var(--accent); - cursor: pointer; - font: inherit; -} - -.btn-link:hover { - text-decoration: underline; -} - -.parser-rank-link { - display: inline-block; - margin: 0.5rem 0; - padding: 0.4rem 0.8rem; - background: var(--accent); - color: #0f1115; - border-radius: 4px; - font-weight: 600; - text-decoration: none; -} - -.parser-rank-link:hover { - filter: brightness(1.1); +#parser-form .btn-primary { + margin-top: 0.5rem; } .scope-name { diff --git a/server/tests/integration_ui.rs b/server/tests/integration_ui.rs index 5112cb79ffe6e53df3d2432646770fc316cf4787..afeeee24e32f2d7f1d852ca96ac799fac8bce665 100644 --- a/server/tests/integration_ui.rs +++ b/server/tests/integration_ui.rs @@ -71,11 +71,11 @@ async fn post_ui_record_vote_morphs_ranking_and_persists() { } #[tokio::test] -async fn post_ui_parse_query_morphs_parser_panel() { +async fn post_ui_parse_query_redirects_to_subreddit() { let (addr, _tmp) = start_test_server().await; let rpc = serde_json::json!({ "action": "parse_query", - "query": "r" + "query": "r/rust" }) .to_string(); let mut form = HashMap::new(); @@ -92,7 +92,6 @@ async fn post_ui_parse_query_morphs_parser_panel() { .await .unwrap(); - assert!(body.contains("Idiomorph.morph")); - assert!(body.contains("parser-panel")); - assert!(body.contains("r/")); + assert!(body.contains("window.location.href")); + assert!(body.contains("/?sub=rust")); } diff --git a/test/parser_race.clj b/test/parser_race.clj deleted file mode 100644 index 23783837f8192ff24a556b73bdd670dc63b606cb..0000000000000000000000000000000000000000 --- a/test/parser_race.clj +++ /dev/null @@ -1,185 +0,0 @@ -(ns test.parser-race - "Browser test (spel / Playwright) for the parser search-box response race. - - The search box debounces keystrokes, POSTs each to `/ui`, and eval()s the - returned JS, which morphs `#parser-panel` (input value + `#parser-output`). - If responses are applied in arrival order with no ordering guard, a slow - response for an *earlier* query can land after a newer one and clobber it. - - To force the race deterministically without touching the Rust server, the - browser talks to a small in-process reverse proxy that injects an asymmetric - per-query delay: the earlier query (`r/rust`) is delayed far longer than the - later query (`r/aww`). The later query therefore renders first, then the - stale earlier response arrives. Correct behavior: the panel reflects the - *latest* query the user typed (`r/aww`)." - (:require [babashka.process :as process] - [clojure.java.io :as io] - [clojure.string :as str] - [clojure.test :refer [deftest is testing]] - [com.blockether.spel.assertions :as assert] - [com.blockether.spel.core :as core] - [com.blockether.spel.locator :as locator] - [com.blockether.spel.page :as page]) - (:import [com.sun.net.httpserver HttpServer HttpHandler] - [java.io ByteArrayOutputStream] - [java.net InetSocketAddress URI URLDecoder] - [java.net.http HttpClient HttpClient$Version HttpRequest - HttpRequest$BodyPublishers HttpResponse$BodyHandlers] - [java.nio.charset StandardCharsets] - [java.util.concurrent Executors])) - -(def ^:private slow-query "r/rust") -(def ^:private fast-query "r/aww") -(def ^:private slow-delay-ms 800) - -(defn- repo-root [] - (.getCanonicalPath (io/file (System/getProperty "user.dir")))) - -(defn- pick-port [] - (with-open [s (java.net.ServerSocket. 0)] - (.getLocalPort s))) - -(defn- wait-health [base-url ms] - (let [deadline (+ (System/currentTimeMillis) ms) - url (str base-url "/healthz")] - (loop [] - (let [resp (try - (process/shell {:out :string :err :string} "curl" "-sf" url) - (catch Exception _ nil))] - (if (and resp (zero? (:exit resp)) (= "ok" (str/trim (:out resp "")))) - true - (if (< (System/currentTimeMillis) deadline) - (do (Thread/sleep 200) (recur)) - false)))))) - -(defn- start-server - "Builds the release binary and starts it on a random port. Returns a map with - :proc and :base." - [root] - (is (zero? (:exit (process/shell {:dir root} - "cargo" "build" "--release" "--package" "sorter2-server"))) - "release build succeeds") - (let [bin (str root "/target/release/sorter2-server")] - (is (.exists (io/file bin)) "binary exists") - (let [data-dir (.getAbsolutePath - (doto (io/file (System/getProperty "java.io.tmpdir") - (str "sorter2-race-" (System/currentTimeMillis))) - (.mkdirs))) - port (pick-port) - base (str "http://127.0.0.1:" port) - proc (process/process {:dir root - :env {"SORTER2_DATA_DIR" data-dir - "SORTER2_EVENT_LOG" (str data-dir "/events.jsonl") - "PORT" (str port)} - :out :string - :err :string} - bin)] - {:proc proc :base base}))) - -(defn- read-all-bytes ^bytes [in] - (let [bos (ByteArrayOutputStream.)] - (io/copy in bos) - (.toByteArray bos))) - -(defn- ui-query - "Extracts the decoded `query` form field from a urlencoded body, or nil." - [body-str] - (some-> (re-find #"(?:^|&)query=([^&]*)" body-str) - second - (URLDecoder/decode "UTF-8"))) - -(defn- start-proxy - "Reverse proxy to `upstream` that sleeps `(delay-fn method path body-str)` ms - before forwarding each request. Runs handlers on a thread pool so concurrent - requests are delayed independently (the race needs out-of-order arrival). - Returns a map with :server and :base." - [upstream delay-fn] - (let [client (-> (HttpClient/newBuilder) - (.version HttpClient$Version/HTTP_1_1) - (.build)) - server (HttpServer/create (InetSocketAddress. "127.0.0.1" 0) 0) - handler (reify HttpHandler - (handle [_ ex] - (try - (let [method (.getRequestMethod ex) - uri (.getRequestURI ex) - path (.getRawPath uri) - query (.getRawQuery uri) - req-body (read-all-bytes (.getRequestBody ex)) - body-str (String. req-body StandardCharsets/UTF_8) - delay-ms (delay-fn method path body-str)] - (when (pos? delay-ms) - (Thread/sleep (long delay-ms))) - (let [target (str upstream path (when query (str "?" query))) - builder (doto (HttpRequest/newBuilder) - (.uri (URI/create target))) - ct (.getFirst (.getRequestHeaders ex) "Content-Type") - _ (when ct (.header builder "Content-Type" ct)) - publisher (if (zero? (alength req-body)) - (HttpRequest$BodyPublishers/noBody) - (HttpRequest$BodyPublishers/ofByteArray req-body)) - _ (.method builder method publisher) - resp (.send client (.build builder) - (HttpResponse$BodyHandlers/ofByteArray)) - resp-body (.body resp) - resp-ct (-> (.headers resp) - (.firstValue "content-type") - (.orElse nil))] - (when resp-ct - (.set (.getResponseHeaders ex) "Content-Type" resp-ct)) - (.sendResponseHeaders ex (.statusCode resp) (alength resp-body)) - (with-open [os (.getResponseBody ex)] - (.write os resp-body)))) - (catch Throwable t - (let [msg (.getBytes (str "proxy error: " (.getMessage t)) - StandardCharsets/UTF_8)] - (try - (.sendResponseHeaders ex 500 (alength msg)) - (with-open [os (.getResponseBody ex)] - (.write os msg)) - (catch Throwable _ nil)))) - (finally - (.close ex)))))] - (.createContext server "/" handler) - (.setExecutor server (Executors/newCachedThreadPool)) - (.start server) - {:server server - :base (str "http://127.0.0.1:" (.getPort (.getAddress server)))})) - -(defn- parser-delay-fn [method path body-str] - (if (and (= method "POST") (= path "/ui") (= (ui-query body-str) slow-query)) - slow-delay-ms - 0)) - -(deftest latest-search-query-wins - (testing "a slow earlier parser response must not clobber a newer one" - (let [root (repo-root) - {:keys [proc base]} (start-server root)] - (try - (is (wait-health base 15000) "server responds to /healthz") - (let [{:keys [server] proxy-base :base} (start-proxy base parser-delay-fn)] - (try - (core/with-testing-page [pg] - (page/navigate pg proxy-base) - (let [input (page/locator pg "#parser-input") - output (page/locator pg "#parser-output")] - ;; Type the slow query first; wait past the 120ms debounce so its - ;; (slow) request is in flight, then type the fast query. - (locator/fill input slow-query) - (Thread/sleep 300) - (locator/fill input fast-query) - ;; Wait until the slow response has certainly arrived and been - ;; (mis)applied if the race exists. - (Thread/sleep 2000) - ;; The panel must reflect the latest query, not the stale one. - (is (nil? (assert/contains-text (assert/assert-that output) fast-query)) - "output shows the latest query (r/aww)") - (is (nil? (assert/contains-text - (assert/loc-not (assert/assert-that output)) slow-query)) - "output does NOT show the stale earlier query (r/rust)") - (is (nil? (assert/has-value (assert/assert-that input) fast-query)) - "input value is the latest query (r/aww)"))) - (finally - (.stop server 0)))) - (finally - (process/destroy proc)))))) Side B — contributor: tommy-mor Side B — commit message: [5ca518f6] url refactor Side B — unified diff (full patch): diff --git a/Cargo.lock b/Cargo.lock index 67a09a3b54f778fa7e857fdd589c3ed9c92e1322..ad7e4fe6d4ba2f2b033916194c1ef1ed873f1d46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1757,6 +1757,7 @@ name = "slug-types" version = "0.1.0" dependencies = [ "serde", + "url", ] [[package]] @@ -2272,6 +2273,7 @@ dependencies = [ "idna", "percent-encoding", "serde", + "serde_derive", ] [[package]] diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs index 606f7d6f97a4428efb90d1e0d544934c861fc4c5..cd3e0f0afd972d9ad9e7e4b92c5fa4c22bb8f620 100644 --- a/server/src/api/ui_html.rs +++ b/server/src/api/ui_html.rs @@ -270,10 +270,10 @@ fn post_redirect_location(room: &str, thread_tag: &str) -> String { format!("/t/{tag}") } else { let room = room.trim(); - let Some((a, b)) = room.split_once('/') else { + let Some(seg) = slug_types::room_route_segment(room) else { return "/".to_string(); }; - format!("/r/{a}/{b}/t/{tag}") + format!("/r/{seg}/t/{tag}") } } diff --git a/server/src/api/write_actor.rs b/server/src/api/write_actor.rs index cb78d2f3f95b1bc163c1fb064d1d5f657e18000f..f9c3b8bd3fbf8fcb9c035e1a1572fef0b08fa8a9 100644 --- a/server/src/api/write_actor.rs +++ b/server/src/api/write_actor.rs @@ -19,13 +19,15 @@ use crate::{ use super::auth::{issue_token_for_user, verify_token}; use super::helpers::{now_ms, resolve_item}; use super::validate::{normalize_room_and_thread, validate_ingest_document}; -use slug_types::RpcResult; +use slug_types::{room_route_segment, RpcResult, ROOM_SHORT_ID_LEN}; fn gen_short_id() -> String { use rand::Rng; const ALPHABET: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz"; let mut rng = rand::thread_rng(); - (0..7).map(|_| ALPHABET[rng.gen_range(0..ALPHABET.len())] as char).collect() + (0..ROOM_SHORT_ID_LEN) + .map(|_| ALPHABET[rng.gen_range(0..ALPHABET.len())] as char) + .collect() } fn parse_capability(s: &str) -> Result { @@ -55,8 +57,8 @@ async fn broadcast_web_refresh(state: &AppState, room_key: &str, thread_id: &str let feed_id = if room_key == "public" { "thread-feed" } else { "room-thread-feed" }; let thread_url = if room_key == "public" { format!("/t/{thread_id}") - } else if let Some((short, slug)) = room_key.split_once('/') { - format!("/r/{short}/{slug}/t/{thread_id}") + } else if let Some(seg) = room_route_segment(room_key) { + format!("/r/{seg}/t/{thread_id}") } else { format!("/t/{thread_id}") }; @@ -78,8 +80,8 @@ async fn broadcast_web_refresh(state: &AppState, room_key: &str, thread_id: &str let js = builder.build(); let mut path_prefixes = vec![if room_key == "public" { "/".to_string() - } else if let Some((short, slug)) = room_key.split_once('/') { - format!("/r/{short}/{slug}") + } else if let Some(seg) = room_route_segment(room_key) { + format!("/r/{seg}") } else { "/".to_string() }]; diff --git a/server/src/html/forum/nav.rs b/server/src/html/forum/nav.rs index 0ee33d91160fc5542817b5e3e9ab4fee1d0e600f..48fe11e46731670874ff8b6b05baa6f09ae0b7e4 100644 --- a/server/src/html/forum/nav.rs +++ b/server/src/html/forum/nav.rs @@ -1,7 +1,8 @@ use crate::canonical_path::canonicalize_item; use crate::reducer::ScopeId; +use slug_types::room_route_segment; -/// URL helpers for public `/t/…` and private room threads `/r/{short}/{slug}/t/…`. +/// URL helpers for public `/t/…` and private room threads `/r/{short}{slug}/t/…`. #[derive(Clone)] pub struct ThreadNav { pub room_wire: String, @@ -22,18 +23,15 @@ impl ThreadNav { } } - /// `room_id` wire form `shortid/slug`. + /// `room_id` wire form `shortid/slug` (HTTP uses [`slug_types::room_route_segment`]). pub(crate) fn from_room_id(room_id: &str) -> Option { - let (short, slug) = room_id.split_once('/')?; - if short.is_empty() || slug.is_empty() { - return None; - } + let room_seg = room_route_segment(room_id)?; Some(Self { room_wire: room_id.to_string(), scope: ScopeId::Room(room_id.to_string()), - room_path: format!("/r/{short}/{slug}"), - thread_path_prefix: format!("/r/{short}/{slug}/t"), - garden_path_prefix: format!("/r/{short}/{slug}/~"), + room_path: format!("/r/{room_seg}"), + thread_path_prefix: format!("/r/{room_seg}/t"), + garden_path_prefix: format!("/r/{room_seg}/~"), }) } diff --git a/server/src/html/forum/post_single.rs b/server/src/html/forum/post_single.rs index c316f8f836df9d4ef9c05ebd9e54f699540e6d72..473747b3da3d4d7a54b5e0c63165d2533df643e1 100644 --- a/server/src/html/forum/post_single.rs +++ b/server/src/html/forum/post_single.rs @@ -93,12 +93,14 @@ pub async fn thread_post_view( pub async fn room_thread_post_view( State(state): State, - Path((room_short, room_slug, tag, index_str)): Path<(String, String, String, String)>, + Path((room_key, tag, index_str)): Path<(String, String, String)>, headers: HeaderMap, jar: CookieJar, uri: Uri, ) -> impl IntoResponse { - let room_id = format!("{room_short}/{room_slug}"); + let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else { + return (StatusCode::NOT_FOUND, "bad room path").into_response(); + }; let reduced = state.reduced.read().await; let user = optional_principal(&headers, &jar, &reduced); if !user_can_view_room(&reduced, &room_id, user.as_deref()) { diff --git a/server/src/html/forum/views.rs b/server/src/html/forum/views.rs index be5df1745ef580891a167c23c3dd6c06f804f295..1ec421f84335cbfe7f9db775b73a8ed24b197174 100644 --- a/server/src/html/forum/views.rs +++ b/server/src/html/forum/views.rs @@ -183,16 +183,18 @@ pub async fn thread_view( thread_view_inner(state, tag, q, ThreadNav::public(), headers, jar, uri).await } -/// Room thread — `/r/:short/:slug/t/:tag` +/// Room thread — `/r/:room_key/t/:tag` (`room_key` = `{short}{slug}`). pub async fn room_thread_view( State(state): State, - Path((room_short, room_slug, tag)): Path<(String, String, String)>, + Path((room_key, tag)): Path<(String, String)>, Query(q): Query, headers: HeaderMap, jar: CookieJar, uri: Uri, ) -> impl IntoResponse { - let room_id = format!("{room_short}/{room_slug}"); + let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else { + return (StatusCode::NOT_FOUND, "bad room path").into_response(); + }; let reduced = state.reduced.read().await; let user = optional_principal(&headers, &jar, &reduced); if !user_can_view_room(&reduced, &room_id, user.as_deref()) { @@ -226,15 +228,17 @@ pub(super) fn room_not_found_page(jar: &CookieJar, uri: &Uri) -> impl IntoRespon (StatusCode::NOT_FOUND, Html(page.into_string())) } -/// Private room index — `/r/:short/:slug` +/// Private room index — `/r/:room_key` pub async fn room_page( State(state): State, - Path((room_short, room_slug)): Path<(String, String)>, + Path(room_key): Path, headers: HeaderMap, jar: CookieJar, uri: Uri, ) -> impl IntoResponse { - let room_id = format!("{room_short}/{room_slug}"); + let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else { + return (StatusCode::NOT_FOUND, "room not found").into_response(); + }; let now = now_ms(); let reduced = state.reduced.read().await; if !reduced.rooms.contains(&room_id) { @@ -266,7 +270,10 @@ pub async fn room_page( let audit_cli = format!("npx slugsocial private {room_id} audit"); drop(reduced); - let slug_display = room_slug.as_str(); + let slug_display = room_id + .split_once('/') + .map(|(_, slug)| slug) + .unwrap_or(room_id.as_str()); let page = layout( &format!("room {slug_display} — slug.social"), "view-thread", diff --git a/server/src/html/garden.rs b/server/src/html/garden.rs index 423f23fd8c9ad7b7f454d6ea7a9a7607a4c9c5b9..e615dd356bcf634232d85610c0a26235ead125fd 100644 --- a/server/src/html/garden.rs +++ b/server/src/html/garden.rs @@ -309,12 +309,14 @@ pub async fn external_ontology_path( pub async fn room_garden_index( State(state): State, - Path((room_short, room_slug)): Path<(String, String)>, + Path(room_key): Path, headers: HeaderMap, jar: CookieJar, uri: Uri, ) -> impl IntoResponse { - let room_id = format!("{room_short}/{room_slug}"); + let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else { + return (StatusCode::NOT_FOUND, "bad room path").into_response(); + }; let Some(nav) = ThreadNav::from_room_id(&room_id) else { return (StatusCode::NOT_FOUND, "bad room path").into_response(); }; @@ -341,12 +343,14 @@ pub async fn room_garden_index( pub async fn room_external_garden_index( State(state): State, - Path((room_short, room_slug)): Path<(String, String)>, + Path(room_key): Path, headers: HeaderMap, jar: CookieJar, uri: Uri, ) -> impl IntoResponse { - let room_id = format!("{room_short}/{room_slug}"); + let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else { + return (StatusCode::NOT_FOUND, "bad room path").into_response(); + }; let Some(nav) = ThreadNav::from_room_id(&room_id) else { return (StatusCode::NOT_FOUND, "bad room path").into_response(); }; @@ -416,12 +420,14 @@ pub async fn room_external_garden_index( pub async fn room_external_ontology_path( State(state): State, - Path((room_short, room_slug, path)): Path<(String, String, String)>, + Path((room_key, path)): Path<(String, String)>, headers: HeaderMap, jar: CookieJar, uri: Uri, ) -> impl IntoResponse { - let room_id = format!("{room_short}/{room_slug}"); + let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else { + return (StatusCode::NOT_FOUND, "bad room path").into_response(); + }; let Some(nav) = ThreadNav::from_room_id(&room_id) else { return (StatusCode::NOT_FOUND, "bad room path").into_response(); }; @@ -442,12 +448,14 @@ pub async fn room_external_ontology_path( pub async fn room_ontology_path( State(state): State, - Path((room_short, room_slug, path)): Path<(String, String, String)>, + Path((room_key, path)): Path<(String, String)>, headers: HeaderMap, jar: CookieJar, uri: Uri, ) -> impl IntoResponse { - let room_id = format!("{room_short}/{room_slug}"); + let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else { + return (StatusCode::NOT_FOUND, "bad room path").into_response(); + }; let Some(nav) = ThreadNav::from_room_id(&room_id) else { return (StatusCode::NOT_FOUND, "bad room path").into_response(); }; diff --git a/server/src/html/search.rs b/server/src/html/search.rs index 43e6ebf36cf0fe72c96f0f9d850bea51ac094c43..f01732f7edb32c68fcc10c39545c8f56476adb27 100644 --- a/server/src/html/search.rs +++ b/server/src/html/search.rs @@ -351,8 +351,8 @@ fn render_search_results(results: &SearchResults, query: &str) -> Markup { ul class="search-posts" { @for r in &results.posts { @let (post_href, post_label) = if let Some((room, tag)) = r.thread.split_once("/#") { - if let Some((short, slug)) = room.split_once('/') { - (format!("/r/{short}/{slug}/t/{tag}"), format!("{room}/#{tag}")) + if let Some(seg) = slug_types::room_route_segment(room) { + (format!("/r/{seg}/t/{tag}"), format!("{room}/#{tag}")) } else { ("/".to_string(), r.thread.clone()) } diff --git a/server/src/lib.rs b/server/src/lib.rs index 9e69c3f4a153527caa77b00ad101aca94b425995..71032f9a0b556097d90f3b403c677e0c86429ee4 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -79,30 +79,30 @@ pub fn create_app(state: AppState) -> Router { .route("/~/*path", get(crate::html::ontology_path)) .route("/-", get(crate::html::external_garden_index)) .route("/-/*path", get(crate::html::external_ontology_path)) - .route("/r/:room_short/:room_slug/~", get(crate::html::room_garden_index)) + .route("/r/:room_key/~", get(crate::html::room_garden_index)) .route( - "/r/:room_short/:room_slug/~/*path", + "/r/:room_key/~/*path", get(crate::html::room_ontology_path), ) .route( - "/r/:room_short/:room_slug/-", + "/r/:room_key/-", get(crate::html::room_external_garden_index), ) .route( - "/r/:room_short/:room_slug/-/*path", + "/r/:room_key/-/*path", get(crate::html::room_external_ontology_path), ) .route("/t/:tag/:index", get(crate::html::thread_post_view)) .route("/t/:tag", get(crate::html::thread_view)) .route( - "/r/:room_short/:room_slug/t/:thread_tag/:index", + "/r/:room_key/t/:thread_tag/:index", get(crate::html::room_thread_post_view), ) .route( - "/r/:room_short/:room_slug/t/:thread_tag", + "/r/:room_key/t/:thread_tag", get(crate::html::room_thread_view), ) - .route("/r/:room_short/:room_slug", get(crate::html::room_page)) + .route("/r/:room_key", get(crate::html::room_page)) .route("/join/:token", get(api::get_join_invite)) .route("/auth/login", get(api::get_auth_login)) .route("/auth/callback", get(api::get_auth_callback)) diff --git a/server/tests/integration.rs b/server/tests/integration.rs index 515c691d04ef3f1f4bdfa8ee911360a43fd2b26e..feb73d475b3fc635d7f16c329d4600718c7472ba 100644 --- a/server/tests/integration.rs +++ b/server/tests/integration.rs @@ -1,4 +1,5 @@ use sha2::{Digest, Sha256}; +use slug_types::room_route_segment; use slugsocial_server::{ event_log::EventLog, events::{Event, TokenIssued, UserRegistered}, @@ -607,7 +608,7 @@ async fn test_private_room_thread_urls_use_t_segment() { .as_str() .unwrap() .to_string(); - let (room_short, room_slug) = room_id.split_once('/').unwrap(); + let room_seg = room_route_segment(&room_id).unwrap(); let rpc = ui_post_ingest_rpc(&room_id, "main-thread", "private post via web"); let post = client @@ -626,7 +627,7 @@ async fn test_private_room_thread_urls_use_t_segment() { Some("text/javascript; charset=utf-8") ); let post_js = post.text().await.unwrap(); - let location = format!("/r/{room_short}/{room_slug}/t/main-thread"); + let location = format!("/r/{room_seg}/t/main-thread"); assert!(post_js.contains(&format!("window.location = {:?};", location))); assert!(post_js.contains("#room-thread-feed")); assert!(post_js.contains("#thread-feed-region")); @@ -665,7 +666,7 @@ async fn test_private_room_post_links_use_private_garden_routes() { .as_str() .unwrap() .to_string(); - let (room_short, room_slug) = room_id.split_once('/').unwrap(); + let room_seg = room_route_segment(&room_id).unwrap(); let rpc = ui_post_ingest_rpc( &room_id, @@ -682,18 +683,18 @@ async fn test_private_room_post_links_use_private_garden_routes() { assert_eq!(post.status(), reqwest::StatusCode::OK); let thread_page = client - .get(format!("http://{addr}/r/{room_short}/{room_slug}/t/garden-thread")) + .get(format!("http://{addr}/r/{room_seg}/t/garden-thread")) .header("Authorization", format!("Bearer {bearer}")) .send() .await .unwrap(); assert!(thread_page.status().is_success()); let body = thread_page.text().await.unwrap(); - assert!(body.contains(&format!("/r/{room_short}/{room_slug}/~/secret/item"))); + assert!(body.contains(&format!("/r/{room_seg}/~/secret/item"))); assert!(!body.contains("href=\"/~/secret/item\"")); let garden_page = client - .get(format!("http://{addr}/r/{room_short}/{room_slug}/~/secret/item")) + .get(format!("http://{addr}/r/{room_seg}/~/secret/item")) .header("Authorization", format!("Bearer {bearer}")) .send() .await @@ -701,7 +702,7 @@ async fn test_private_room_post_links_use_private_garden_routes() { assert!(garden_page.status().is_success()); let garden_body = garden_page.text().await.unwrap(); assert!(garden_body.contains("classified")); - assert!(garden_body.contains(&format!("/r/{room_short}/{room_slug}/t/garden-thread"))); + assert!(garden_body.contains(&format!("/r/{room_seg}/t/garden-thread"))); } #[tokio::test] @@ -726,7 +727,7 @@ async fn test_private_room_garden_root_lists_top_level_tilde_children() { .as_str() .unwrap() .to_string(); - let (room_short, room_slug) = room_id.split_once('/').unwrap(); + let room_seg = room_route_segment(&room_id).unwrap(); let rpc = ui_post_ingest_rpc( &room_id, @@ -743,7 +744,7 @@ async fn test_private_room_garden_root_lists_top_level_tilde_children() { assert_eq!(post.status(), reqwest::StatusCode::OK); let root_page = client - .get(format!("http://{addr}/r/{room_short}/{room_slug}/~")) + .get(format!("http://{addr}/r/{room_seg}/~")) .header("Authorization", format!("Bearer {bearer}")) .send() .await @@ -782,10 +783,10 @@ async fn test_empty_private_room_garden_returns_404() { .as_str() .unwrap() .to_string(); - let (room_short, room_slug) = room_id.split_once('/').unwrap(); + let room_seg = room_route_segment(&room_id).unwrap(); let root = client - .get(format!("http://{addr}/r/{room_short}/{room_slug}/~")) + .get(format!("http://{addr}/r/{room_seg}/~")) .header("Authorization", format!("Bearer {bearer}")) .send() .await @@ -896,8 +897,8 @@ async fn test_sse_stream_emits_evalable_js_after_post() { .as_str() .unwrap() .to_string(); - let (room_short, room_slug) = room_id.split_once('/').unwrap(); - let room_path = format!("/r/{room_short}/{room_slug}"); + let room_seg = room_route_segment(&room_id).unwrap(); + let room_path = format!("/r/{room_seg}"); let sse_resp = client .get(format!("http://{addr}/sse?path={}", urlencoding::encode(&room_path))) diff --git a/test/browser_room_delete.clj b/test/browser_room_delete.clj index 833e3f8aa7f850b60ee59742736143cbf101a07d..764ecaa674798a61c1ffca3859f2a56a91a0e97e 100644 --- a/test/browser_room_delete.clj +++ b/test/browser_room_delete.clj @@ -54,7 +54,7 @@ room-id (get-in create-json ["results" 0 "result" "RoomCreated" "room_id"]) _ (is (string? room-id) "room id present") [room-short room-slug] (str/split room-id #"/" 2) - room-path (str "/r/" room-short "/" room-slug)] + room-path (str "/r/" room-short room-slug)] (core/with-playwright [pw] (core/with-browser [browser (core/launch-chromium pw {:headless true :channel "chrome"})] (core/with-context [ctx (core/new-context browser)] diff --git a/test/browser_sse.clj b/test/browser_sse.clj index 8bb064dbc2dc0feb6caaa67f520a461645958277..678399b79f78ff48b5e77342fa21e69992393834 100644 --- a/test/browser_sse.clj +++ b/test/browser_sse.clj @@ -77,7 +77,7 @@ (login-user! bob-pg base-url "bob") (let [[room-short room-slug] (str/split room-id #"/" 2) - room-url (str base-url "/r/" room-short "/" room-slug) + room-url (str base-url "/r/" room-short room-slug) thread-url (str room-url "/t/sse-thread")] ;; Object under test: slug_ui.js intercepts POST /ui, evals JS, morphs ;; #new-thread-ui-slot (expand compose), then post_ingest redirects to thread. diff --git a/test/walkthrough_fixture.clj b/test/walkthrough_fixture.clj index a487ff1ef8548580577914fb33f321586859c9af..f7eb1cacca0317129e9baf68fa4f4e33356ad70f 100644 --- a/test/walkthrough_fixture.clj +++ b/test/walkthrough_fixture.clj @@ -88,9 +88,9 @@ :room {:id room-id :short room-short :slug room-slug - :url (str base-url "/r/" room-short "/" room-slug) - :thread_url (str base-url "/r/" room-short "/" room-slug "/t/walkthrough-thread") - :garden_url (str base-url "/r/" room-short "/" room-slug "/~/secret/item")}})) + :url (str base-url "/r/" room-short room-slug) + :thread_url (str base-url "/r/" room-short room-slug "/t/walkthrough-thread") + :garden_url (str base-url "/r/" room-short room-slug "/~/secret/item")}})) (defn- rebase-fixture-summary [saved current-base-url current-google-url current-data-dir] (let [inner (:summary saved) @@ -103,9 +103,9 @@ :data_dir (str current-data-dir) :summary (assoc inner :room (assoc room - :url (str current-base-url "/r/" rs "/" lg) - :thread_url (str current-base-url "/r/" rs "/" lg "/t/walkthrough-thread") - :garden_url (str current-base-url "/r/" rs "/" lg "/~/secret/item")))))) + :url (str current-base-url "/r/" rs lg) + :thread_url (str current-base-url "/r/" rs lg "/t/walkthrough-thread") + :garden_url (str current-base-url "/r/" rs lg "/~/secret/item")))))) (defn- fixture-log-present? [data-dir] (let [p (fs/path data-dir "events.jsonl")] diff --git a/types/Cargo.toml b/types/Cargo.toml index 1ed06d483ac7c126516bce27f90e7639c2dfe370..5dc3becf238f23243313dff0484c682a7b225737 100644 --- a/types/Cargo.toml +++ b/types/Cargo.toml @@ -5,3 +5,4 @@ edition = "2021" [dependencies] serde = { version = "1.0", features = ["derive"] } +url = { version = "2.5", features = ["serde"] } diff --git a/types/src/lib.rs b/types/src/lib.rs index fce1b5fa5e259a4b86a11cb4d4f7cc9bec3a0aa1..516cf935f15fca97081b39b988da5be894c67725 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -1,5 +1,7 @@ use serde::{Deserialize, Serialize}; +pub mod room_route; +pub mod url_normalize; pub mod paths; pub mod timeago; @@ -8,6 +10,8 @@ pub use paths::{ CanonicalItemUrl, ForumThreadUrl, GardenItemUrl, RelativePath, SLUG_TILDE_ONTOLOGY_ROOT, TildeHttpPathTail, TildeOntologyPath, TildePath, tilde_http_path_to_canonical, }; +pub use room_route::{room_id_from_route_segment, room_route_segment, ROOM_SHORT_ID_LEN}; +pub use url_normalize::normalize_http_identity_url; /// Max characters returned for a garden item body unless `full=true` / `--full` (API + CLI). pub const MAX_ITEM_BODY_PREVIEW_CHARS: usize = 100_000; @@ -657,3 +661,6 @@ pub struct VoteResponse { pub ranking: Vec, pub next: NextMoves, } + +#[cfg(test)] +mod url_identity_tests; diff --git a/types/src/paths.rs b/types/src/paths.rs index 8971f599a7ebcf399f60c306d35ee28d0f581194..98787a5fb481a1599556564bbbbd1d54dc693fc3 100644 --- a/types/src/paths.rs +++ b/types/src/paths.rs @@ -5,7 +5,7 @@ //! //! - **[`canonicalize_item`] / [`CanonicalItemUrl`]** — graph storage key and DSL form; tilde //! ontology root is always [`SLUG_TILDE_ONTOLOGY_ROOT`] (no `…/~/` trailing slash only). -//! - **[`TildeHttpPathTail`]** — capture from `GET /~/*path` or `…/r/…/~/…` (the `*path` segment). +//! - **[`TildeHttpPathTail`]** — capture from `GET /~/*path` or `…/r/{short}{slug}/~/…` (the `*path` segment). //! - **`-/…` wire form** — external items; see [`canonicalize_item`] dash branch. //! - **[`GardenItemUrl`], [`ForumThreadUrl`]** — JSON / browser href surfaces. @@ -15,6 +15,9 @@ use std::ops::Deref; use serde::{Deserialize, Serialize}; +use crate::room_route::room_route_segment; +use crate::url_normalize::{host_preserves_dash_path_case, normalize_http_identity_url}; + // --------------------------------------------------------------------------- // Slug tilde ontology (single storage form for `~/`) // --------------------------------------------------------------------------- @@ -41,6 +44,29 @@ pub fn canonicalize_tag(input: &str) -> String { input.trim().trim_start_matches('#').to_lowercase() } +fn finalize_external_identity_url(s: String) -> String { + if s.starts_with("https://slug.social/") { + return s; + } + let normalized = normalize_http_identity_url(&s).unwrap_or_else(|| s.clone()); + strip_redundant_root_slash(&normalized).unwrap_or(normalized) +} + +/// `url::Url` serializes bare hosts with a `/` path; we keep host-only items slash-free for stable +/// keys matching the pre-normalizer spellings. +fn strip_redundant_root_slash(s: &str) -> Option { + let u = url::Url::parse(s).ok()?; + if u.path() == "/" && u.query().is_none() && u.fragment().is_none() { + let scheme = u.scheme(); + let host = u.host_str()?; + return Some(match u.port() { + Some(p) => format!("{scheme}://{host}:{p}"), + None => format!("{scheme}://{host}"), + }); + } + None +} + /// Ontology item reference → canonical absolute URL on the slug host. pub fn canonicalize_item(input: &str) -> String { let s = input.trim(); @@ -57,8 +83,9 @@ pub fn canonicalize_item(input: &str) -> String { if host.is_empty() { return String::new(); } + let preserve_case = host_preserves_dash_path_case(&host); return if tail.is_empty() { - format!("https://{}", host) + finalize_external_identity_url(format!("https://{}", host)) } else { let path = tail .trim_start_matches('/') @@ -68,33 +95,35 @@ pub fn canonicalize_item(input: &str) -> String { let t = seg.trim(); if t.is_empty() { None + } else if preserve_case { + Some(t.to_string()) } else { Some(t.to_lowercase()) } }) .collect::>() .join("/"); - format!("https://{}/{}", host, path) + finalize_external_identity_url(format!("https://{}/{}", host, path)) }; } if let Some(rest) = s.strip_prefix("https://") { let (host, tail) = rest.split_once('/').map_or((rest, ""), |(h, t)| (h, t)); let host = host.trim().to_lowercase(); - if tail.is_empty() { - return format!("https://{}", host); + return finalize_external_identity_url(if tail.is_empty() { + format!("https://{}", host) } else { - return format!("https://{}/{}", host, tail); - } + format!("https://{}/{}", host, tail) + }); } if let Some(rest) = s.strip_prefix("http://") { let (host, tail) = rest.split_once('/').map_or((rest, ""), |(h, t)| (h, t)); let host = host.trim().to_lowercase(); - if tail.is_empty() { - return format!("http://{}", host); + return finalize_external_identity_url(if tail.is_empty() { + format!("http://{}", host) } else { - return format!("http://{}/{}", host, tail); - } + format!("http://{}/{}", host, tail) + }); } let is_tilde = s.starts_with("~/"); @@ -319,7 +348,7 @@ impl CanonicalItemUrl { } } -/// HTTP route capture: path segment after `~/` in `GET /~/*path` or `…/r/…/~/…` (empty = ontology root). +/// HTTP route capture: path segment after `~/` in `GET /~/*path` or `…/r/{short}{slug}/~/…` (empty = ontology root). #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct TildeHttpPathTail(pub String); @@ -506,12 +535,9 @@ fn garden_href_string(item: &str, room_wire: &str) -> String { if room.is_empty() || room == "public" { return api_path_or_url(item); } - let Some((short, slug)) = room.split_once('/') else { + let Some(room_seg) = room_route_segment(room) else { return api_path_or_url(item); }; - if short.is_empty() || slug.is_empty() { - return api_path_or_url(item); - } let Some(c) = CanonicalItemUrl::parse(item) else { return api_path_or_url(item); }; @@ -520,19 +546,19 @@ fn garden_href_string(item: &str, room_wire: &str) -> String { let root_norm = root.as_str().trim_end_matches('/'); if let Some(tail) = c.tilde_tail() { return if tail.is_empty() { - format!("https://slug.social/r/{short}/{slug}/~") + format!("https://slug.social/r/{room_seg}/~") } else { - format!("https://slug.social/r/{short}/{slug}/~/{}", tail) + format!("https://slug.social/r/{room_seg}/~/{}", tail) }; } if item_norm == root_norm { - return format!("https://slug.social/r/{short}/{slug}/~"); + return format!("https://slug.social/r/{room_seg}/~"); } // External http(s) items use the same `/-/…` namespace under the room garden. if c.as_str().starts_with("https://") || c.as_str().starts_with("http://") { let tail = c.display_path(); let tail = tail.strip_prefix("-/").unwrap_or(tail.as_str()); - return format!("https://slug.social/r/{short}/{slug}/-/{tail}"); + return format!("https://slug.social/r/{room_seg}/-/{tail}"); } api_path_or_url(item) } @@ -556,12 +582,8 @@ impl ForumThreadUrl { let tag = thread_tag.trim().trim_start_matches('#'); Self(if room.is_empty() || room == "public" { format!("https://slug.social/t/{tag}") - } else if let Some((short, slug)) = room.split_once('/') { - if short.is_empty() || slug.is_empty() { - format!("https://slug.social/t/{tag}") - } else { - format!("https://slug.social/r/{short}/{slug}/t/{tag}") - } + } else if let Some(room_seg) = room_route_segment(room) { + format!("https://slug.social/r/{room_seg}/t/{tag}") } else { format!("https://slug.social/t/{tag}") }) @@ -706,7 +728,7 @@ mod tests { fn garden_private_room_prefixes_ontology() { assert_eq!( GardenItemUrl::from_storage_str("https://slug.social/~/topic/x", "9ab12cd/my-room").as_str(), - "https://slug.social/r/9ab12cd/my-room/~/topic/x" + "https://slug.social/r/9ab12cdmy-room/~/topic/x" ); } @@ -714,11 +736,11 @@ mod tests { fn garden_private_room_ontology_root() { assert_eq!( GardenItemUrl::from_storage_str("https://slug.social/~", "9ab12cd/my-room").as_str(), - "https://slug.social/r/9ab12cd/my-room/~" + "https://slug.social/r/9ab12cdmy-room/~" ); assert_eq!( GardenItemUrl::from_storage_str("https://slug.social/~/", "9ab12cd/my-room").as_str(), - "https://slug.social/r/9ab12cd/my-room/~" + "https://slug.social/r/9ab12cdmy-room/~" ); } @@ -727,7 +749,7 @@ mod tests { let u = "https://example.com/z"; assert_eq!( GardenItemUrl::from_storage_str(u, "9ab12cd/my-room").as_str(), - "https://slug.social/r/9ab12cd/my-room/-/example.com/z" + "https://slug.social/r/9ab12cdmy-room/-/example.com/z" ); } @@ -739,7 +761,19 @@ mod tests { ); assert_eq!( ForumThreadUrl::from_room_tag("9ab12cd/my-room", "#debate").as_str(), - "https://slug.social/r/9ab12cd/my-room/t/debate" + "https://slug.social/r/9ab12cdmy-room/t/debate" + ); + } + + #[test] + fn canonicalize_youtube_short_links() { + assert_eq!( + canonicalize_item("https://youtu.be/dQw4w9WgXcQ"), + "https://www.youtube.com/watch?v=dQw4w9WgXcQ" + ); + assert_eq!( + canonicalize_item("-/youtu.be/dQw4w9WgXcQ"), + "https://www.youtube.com/watch?v=dQw4w9WgXcQ" ); } diff --git a/types/src/room_route.rs b/types/src/room_route.rs new file mode 100644 index 0000000000000000000000000000000000000000..4f4780c88e30f2b28e2cfcd7aee713d39dbd1c66 --- /dev/null +++ b/types/src/room_route.rs @@ -0,0 +1,56 @@ +//! HTTP path encoding for private rooms: `/r/{short}{slug}` (short is fixed width). + +/// Byte length of the random `short` segment in `short/slug` room ids. +/// Must match room creation (`gen_short_id`) and [`super::paths`][] URL builders. +pub const ROOM_SHORT_ID_LEN: usize = 7; + +/// `ab12cde/my-room` → `ab12cdemy-room` for a single `/r/…` path segment. +pub fn room_route_segment(room_id: &str) -> Option { + let (short, slug) = room_id.split_once('/')?; + if short.len() != ROOM_SHORT_ID_LEN || short.is_empty() || slug.is_empty() { + return None; + } + if !short + .bytes() + .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'z')) + { + return None; + } + Some(format!("{short}{slug}")) +} + +/// `/r/{short}{slug}` path segment → `short/slug` wire id (inverse of [`room_route_segment`]). +pub fn room_id_from_route_segment(seg: &str) -> Option { + if seg.len() <= ROOM_SHORT_ID_LEN { + return None; + } + let (short, slug) = seg.split_at(ROOM_SHORT_ID_LEN); + if short.is_empty() || slug.is_empty() { + return None; + } + if !short + .bytes() + .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'z')) + { + return None; + } + Some(format!("{short}/{slug}")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trip_room_segment() { + let id = "9ab12cd/my-room"; + let seg = room_route_segment(id).unwrap(); + assert_eq!(seg, "9ab12cdmy-room"); + assert_eq!(room_id_from_route_segment(&seg).as_deref(), Some(id)); + } + + #[test] + fn too_short_segment_rejected() { + assert!(room_id_from_route_segment("9ab12cd").is_none()); + } +} diff --git a/types/src/url_identity_tests.rs b/types/src/url_identity_tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..e2ff0a9a64a88049e31f20979c703777df6a9b65 --- /dev/null +++ b/types/src/url_identity_tests.rs @@ -0,0 +1,126 @@ +//! How `url::Url` behaves as `HashMap` keys (`Eq` + `Hash`). +//! +//! If `ItemId::External` stores `Url`, these tests are the contract you are buying into +//! (or the baseline before you add a custom normalization layer). + +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use url::Url; + +fn hash_one(url: &Url) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + url.hash(&mut h); + h.finish() +} + +#[test] +fn identical_parse_strings_are_eq_and_share_hash_bucket() { + let a = Url::parse("https://example.com/path").unwrap(); + let b = Url::parse("https://example.com/path").unwrap(); + assert_eq!(a, b); + assert_eq!(hash_one(&a), hash_one(&b)); + + let mut m: HashMap = HashMap::new(); + m.insert(a, 1); + *m.entry(b).or_default() += 10; + assert_eq!(m.len(), 1); + assert_eq!(m[&Url::parse("https://example.com/path").unwrap()], 11); +} + +#[test] +fn host_is_ascii_lowercase_in_eq() { + let lower = Url::parse("https://examplE.com/").unwrap(); + let upper = Url::parse("https://EXAMPLE.com/").unwrap(); + assert_eq!(lower, upper); + assert_eq!(hash_one(&lower), hash_one(&upper)); +} + +#[test] +fn path_space_normalizes_to_percent_encoding_so_forms_merge() { + let encoded = Url::parse("https://example.com/a%20b").unwrap(); + let decoded = Url::parse("https://example.com/a b").unwrap(); + // Parser normalizes both to the same internal path (`/a%20b`). + assert_eq!(encoded, decoded); + assert_eq!(hash_one(&encoded), hash_one(&decoded)); + + let mut m: HashMap = HashMap::new(); + m.insert(encoded, "first"); + assert_eq!(m.insert(decoded, "second"), Some("first")); + assert_eq!(m.len(), 1); + assert_eq!(m.values().next().copied(), Some("second")); +} + +#[test] +fn encoded_slash_in_segment_stays_distinct_from_real_path_separator() { + let encoded = Url::parse("https://example.com/a%2Fb").unwrap(); + let real_slash = Url::parse("https://example.com/a/b").unwrap(); + assert_ne!(encoded, real_slash); + assert_ne!(hash_one(&encoded), hash_one(&real_slash)); +} + +#[test] +fn trailing_slash_on_path_is_significant_for_eq() { + let with_slash = Url::parse("https://example.com/foo/").unwrap(); + let no_slash = Url::parse("https://example.com/foo").unwrap(); + assert_ne!(with_slash, no_slash); + assert_ne!(hash_one(&with_slash), hash_one(&no_slash)); +} + +#[test] +fn default_http_port_80_is_normalized_in_representation() { + let explicit = Url::parse("http://example.com:80/").unwrap(); + let implicit = Url::parse("http://example.com/").unwrap(); + assert_eq!(explicit, implicit); + assert_eq!(hash_one(&explicit), hash_one(&implicit)); +} + +#[test] +fn default_https_port_443_is_normalized() { + let explicit = Url::parse("https://example.com:443/foo").unwrap(); + let implicit = Url::parse("https://example.com/foo").unwrap(); + assert_eq!(explicit, implicit); +} + +#[test] +fn non_default_port_is_part_of_identity() { + let a = Url::parse("https://example.com:444/").unwrap(); + let b = Url::parse("https://example.com:445/").unwrap(); + assert_ne!(a, b); +} + +#[test] +fn empty_path_vs_slash_only_path_may_differ() { + let root = Url::parse("https://example.com").unwrap(); + let slash = Url::parse("https://example.com/").unwrap(); + // Both serialize to `https://example.com/` in practice for this crate — verify. + assert_eq!(root, slash, "document: root and trailing-slash-only merge for this parser"); +} + +#[test] +fn scheme_case_is_normalized_to_lowercase() { + let lower = Url::parse("https://example.com/").unwrap(); + let upper = Url::parse("HTTPS://example.com/").unwrap(); + assert_eq!(lower, upper); +} + +#[test] +fn fragment_is_part_of_eq_and_hash() { + let no_frag = Url::parse("https://example.com/a").unwrap(); + let frag = Url::parse("https://example.com/a#section").unwrap(); + assert_ne!( + no_frag, frag, + "#fragment is included in PartialEq — anchors are different HashMap keys" + ); + assert_ne!(hash_one(&no_frag), hash_one(&frag)); +} + +#[test] +fn query_order_and_encoding_can_split_identity() { + let a = Url::parse("https://example.com/?b=2&a=1").unwrap(); + let b = Url::parse("https://example.com/?a=1&b=2").unwrap(); + assert_ne!(a, b, "query pairs order is preserved in serialization"); + + let plus = Url::parse("https://example.com/?q=a+b").unwrap(); + let encoded = Url::parse("https://example.com/?q=a%20b").unwrap(); + assert_ne!(plus, encoded, "space as + vs %20 — different keys unless normalized"); +} diff --git a/types/src/url_normalize.rs b/types/src/url_normalize.rs new file mode 100644 index 0000000000000000000000000000000000000000..d5bc913f33ad29cd0cd1c7158e28e4fefdbf5f5d --- /dev/null +++ b/types/src/url_normalize.rs @@ -0,0 +1,234 @@ +//! Normalization for external `http(s)://` item identity (not slug tilde ontology). +//! +//! Policy (intentional, extend here as new domains need treatment): +//! - Query pairs sorted lexicographically by **lowercased** key, then value. +//! - YouTube family → stable `www.youtube.com` shapes where possible. + +use url::Url; + +/// Whether `-/` → `https://…` path segments should keep original casing (YouTube video IDs are +/// case-sensitive). +pub(crate) fn host_preserves_dash_path_case(host: &str) -> bool { + let h = host.trim().to_ascii_lowercase(); + let h = h.strip_prefix("www.").unwrap_or(h.as_str()); + matches!( + h, + "youtu.be" | "youtube.com" | "m.youtube.com" | "music.youtube.com" + ) +} + +/// Normalize external http(s) URLs for stable [`super::paths::canonicalize_item`] output. +pub fn normalize_http_identity_url(s: &str) -> Option { + let mut u = Url::parse(s).ok()?; + if !matches!(u.scheme(), "http" | "https") { + return None; + } + rewrite_youtube(&mut u); + sort_query_pairs(&mut u); + Some(u.to_string()) +} + +fn base_host(host: &str) -> String { + let lower = host.to_ascii_lowercase(); + lower + .strip_prefix("www.") + .unwrap_or(lower.as_str()) + .to_string() +} + +fn rewrite_youtube(u: &mut Url) { + let Some(host_raw) = u.host_str() else { + return; + }; + let base = base_host(host_raw); + let path = u.path().to_string(); + + match base.as_str() { + "youtu.be" => { + let id = path.trim_start_matches('/').split('/').next().unwrap_or("").to_string(); + if id.is_empty() { + return; + } + let saved: Vec<(String, String)> = u.query_pairs().into_owned().collect(); + let Ok(mut out) = Url::parse(&format!("https://www.youtube.com/watch?v={id}")) else { + return; + }; + { + let mut q = out.query_pairs_mut(); + for (k, v) in saved { + if k.eq_ignore_ascii_case("v") { + continue; + } + q.append_pair(&k, &v); + } + } + *u = out; + } + "youtube.com" | "m.youtube.com" => { + if base == "m.youtube.com" { + let _ = u.set_host(Some("www.youtube.com")); + } + if path.starts_with("/embed/") { + let id = path + .strip_prefix("/embed/") + .unwrap_or("") + .trim_matches('/') + .split('/') + .next() + .unwrap_or("") + .to_string(); + if id.is_empty() { + return; + } + let saved: Vec<(String, String)> = u.query_pairs().into_owned().collect(); + let Ok(mut out) = Url::parse(&format!("https://www.youtube.com/watch?v={id}")) + else { + return; + }; + { + let mut q = out.query_pairs_mut(); + for (k, v) in saved { + if k.eq_ignore_ascii_case("v") { + continue; + } + q.append_pair(&k, &v); + } + } + *u = out; + return; + } + if path.starts_with("/v/") { + let id = path + .strip_prefix("/v/") + .unwrap_or("") + .trim_matches('/') + .split('/') + .next() + .unwrap_or("") + .to_string(); + if id.is_empty() { + return; + } + let saved: Vec<(String, String)> = u.query_pairs().into_owned().collect(); + let Ok(mut out) = Url::parse(&format!("https://www.youtube.com/watch?v={id}")) + else { + return; + }; + { + let mut q = out.query_pairs_mut(); + for (k, v) in saved { + if k.eq_ignore_ascii_case("v") { + continue; + } + q.append_pair(&k, &v); + } + } + *u = out; + return; + } + if path.starts_with("/watch") { + let _ = u.set_host(Some("www.youtube.com")); + return; + } + if path.starts_with("/shorts/") { + let id = path + .strip_prefix("/shorts/") + .unwrap_or("") + .trim_matches('/') + .split('/') + .next() + .unwrap_or("") + .to_string(); + if id.is_empty() { + return; + } + let saved: Vec<(String, String)> = u.query_pairs().into_owned().collect(); + let Ok(mut out) = Url::parse(&format!("https://www.youtube.com/shorts/{id}")) + else { + return; + }; + { + let mut q = out.query_pairs_mut(); + for (k, v) in saved { + q.append_pair(&k, &v); + } + } + *u = out; + return; + } + let _ = u.set_host(Some("www.youtube.com")); + } + "music.youtube.com" => {} + _ => {} + } +} + +fn sort_query_pairs(u: &mut Url) { + let pairs: Vec<(String, String)> = u.query_pairs().into_owned().collect(); + if pairs.is_empty() { + u.set_query(None); + return; + } + let mut pairs = pairs; + pairs.sort_by(|a, b| { + a.0.to_ascii_lowercase() + .cmp(&b.0.to_ascii_lowercase()) + .then_with(|| a.1.cmp(&b.1)) + }); + u.set_query(None); + { + let mut q = u.query_pairs_mut(); + for (k, v) in pairs { + q.append_pair(&k, &v); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn youtube_youtu_be_to_watch() { + assert_eq!( + normalize_http_identity_url("https://youtu.be/dQw4w9WgXcQ").as_deref(), + Some("https://www.youtube.com/watch?v=dQw4w9WgXcQ") + ); + } + + #[test] + fn youtube_watch_query_sorted() { + assert_eq!( + normalize_http_identity_url("https://youtube.com/watch?v=Z&a=1&b=2").as_deref(), + Some("https://www.youtube.com/watch?a=1&b=2&v=Z") + ); + assert_eq!( + normalize_http_identity_url("https://youtube.com/watch?b=2&a=1&v=Z").as_deref(), + Some("https://www.youtube.com/watch?a=1&b=2&v=Z") + ); + } + + #[test] + fn youtube_embed_to_watch() { + assert_eq!( + normalize_http_identity_url("https://www.youtube.com/embed/dQw4w9WgXcQ").as_deref(), + Some("https://www.youtube.com/watch?v=dQw4w9WgXcQ") + ); + } + + #[test] + fn youtube_shorts_host() { + assert_eq!( + normalize_http_identity_url("https://youtube.com/shorts/AbCdEfGhIjK").as_deref(), + Some("https://www.youtube.com/shorts/AbCdEfGhIjK") + ); + } + + #[test] + fn arbitrary_query_sorted() { + assert_eq!( + normalize_http_identity_url("https://example.com/x?z=1&a=2").as_deref(), + Some("https://example.com/x?a=2&z=1") + ); + } +}