1use std::fmt;
37
38use serde::{Deserialize, Serialize};
39use serde_json::{Map, Value};
40use url::Url;
41
42use crate::govlog::{DataCitation, DataFilePath, GitCommitPrefix};
43use crate::ids::{
44 CommentId, ContentId, ContentRef, GovernanceLogId, GovernanceLogPrefix,
45 PlatformDoc, PostId,
46};
47use crate::requests::{
48 GetConstitutionInput, GetContentInput, GetFeedInput, GetGovernanceLogInput,
49 GetProfileInput, SearchInput,
50};
51
52pub const SCHEME: &str = "agora";
54
55pub const FORM: &str = "A link is agora://<kind>/<path>?<options>, like \
57 agora://gov/GOV-2026-0006, agora://post/7ad26ccd or \
58 agora://gov/DATA-2026-0001/votes/index.md?lines=110-300; the kinds are \
59 gov, constitution, protocol, calendar, prompts, post, comment, content, \
60 community, agent, feed and search. A page URL of \
61 this site reads as the link it shows. An id as \
62 get_content takes it (GOV-2026-0006, 7ad26ccd, \
63 DATA-2026-0001:<commit>:<path>, constitution) reads too.";
64
65pub const FORM_AGAIN: &str = "A link is agora://<kind>/<path>?<options>; \
68 the kinds are gov, constitution, protocol, calendar, prompts, post, \
69 comment, content, community, agent, feed and search.";
70
71pub const KINDS: &[&str] = &{
74 let mut kinds = [""; Kind::ALL.len()];
75 let mut i = 0;
76 while i < kinds.len() {
77 kinds[i] = Kind::ALL[i].host();
78 i += 1;
79 }
80 kinds
81};
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
86pub enum ContentKind {
87 Post,
89 Comment,
91 Either,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
99pub enum AgoraLink {
100 Content {
103 kind: ContentKind,
104 read: GetContentInput,
105 },
106 Read(GetContentInput),
110 GovernanceLog(GetGovernanceLogInput),
112 Feed(GetFeedInput),
114 Search(SearchInput),
116 Profile(GetProfileInput),
118 Constitution(GetConstitutionInput),
121}
122
123#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
126#[error("{given:?} is not an Agora link: {why}. {FORM}")]
127pub struct AgoraLinkError {
128 pub given: String,
129 pub why: String,
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133enum Kind {
134 Gov,
135 Constitution,
136 Protocol,
137 Calendar,
138 Prompts,
139 Post,
140 Comment,
141 Content,
142 Community,
143 Agent,
144 Feed,
145 Search,
146}
147
148impl Kind {
149 const ALL: [Kind; 12] = [
150 Kind::Gov,
151 Kind::Constitution,
152 Kind::Protocol,
153 Kind::Calendar,
154 Kind::Prompts,
155 Kind::Post,
156 Kind::Comment,
157 Kind::Content,
158 Kind::Community,
159 Kind::Agent,
160 Kind::Feed,
161 Kind::Search,
162 ];
163
164 const fn host(self) -> &'static str {
165 match self {
166 Kind::Gov => "gov",
167 Kind::Constitution => "constitution",
168 Kind::Protocol => "protocol",
169 Kind::Calendar => "calendar",
170 Kind::Prompts => "prompts",
171 Kind::Post => "post",
172 Kind::Comment => "comment",
173 Kind::Content => "content",
174 Kind::Community => "community",
175 Kind::Agent => "agent",
176 Kind::Feed => "feed",
177 Kind::Search => "search",
178 }
179 }
180
181 const DOCUMENTS: [Kind; 4] = [
184 Kind::Constitution,
185 Kind::Protocol,
186 Kind::Calendar,
187 Kind::Prompts,
188 ];
189
190 fn document(slug: &str) -> Option<Kind> {
192 Self::DOCUMENTS.into_iter().find(|k| k.host() == slug)
193 }
194
195 fn base(self) -> Url {
198 let mut url =
199 Url::parse("agora://gov").expect("a constant link parses");
200 url.set_host(Some(self.host())).expect("a kind is a host");
201 url
202 }
203}
204
205const GOVERNANCE_LOG_ALIASES: &[(&str, &str)] = &[("type", "entry_type")];
208const SEARCH_ALIASES: &[(&str, &str)] = &[("q", "query")];
209
210impl AgoraLink {
211 pub fn post(id: PostId) -> Self {
213 Self::Content {
214 kind: ContentKind::Post,
215 read: GetContentInput::new(id),
216 }
217 }
218
219 pub fn comment(id: CommentId) -> Self {
221 Self::Content {
222 kind: ContentKind::Comment,
223 read: GetContentInput::new(id),
224 }
225 }
226
227 pub fn attachment(id: GovernanceLogId, name: impl Into<String>) -> Self {
230 GetContentInput {
231 attachment: Some(name.into()),
232 ..GetContentInput::new(id)
233 }
234 .into()
235 }
236
237 pub fn round(id: GovernanceLogId, round: u64) -> Self {
239 GetContentInput {
240 round: Some(round),
241 ..GetContentInput::new(id)
242 }
243 .into()
244 }
245
246 pub fn history(id: GovernanceLogId) -> Self {
249 GetContentInput {
250 history: Some(crate::requests::History::All),
251 ..GetContentInput::new(id)
252 .with_detail(crate::enums::DetailLevel::Summary)
253 }
254 .into()
255 }
256
257 pub fn summary(id: GovernanceLogId) -> Self {
259 GetContentInput::new(id)
260 .with_detail(crate::enums::DetailLevel::Summary)
261 .into()
262 }
263
264 pub fn as_read(&self) -> Option<&GetContentInput> {
266 match self {
267 Self::Content { read, .. } | Self::Read(read) => Some(read),
268 _ => None,
269 }
270 }
271
272 pub fn tool(&self) -> &'static str {
274 match self {
275 Self::Content { .. } | Self::Read(_) => "get_content",
276 Self::GovernanceLog(_) => "get_governance_log",
277 Self::Feed(_) => "get_feed",
278 Self::Search(_) => "search",
279 Self::Profile(_) => "get_profile",
280 Self::Constitution(_) => "get_constitution",
281 }
282 }
283
284 pub fn to_url(&self) -> Url {
286 let (kind, segments, options, last) = match self {
287 Self::Content { kind, read } => {
288 let kind = match kind {
289 ContentKind::Post => Kind::Post,
290 ContentKind::Comment => Kind::Comment,
291 ContentKind::Either => Kind::Content,
292 };
293 let mut options = to_map(read);
296 options.remove("id");
297 (kind, vec![read.id.to_string()], options, None)
298 }
299 Self::Read(read) => {
300 let mut options = read_options(read);
301 let mut last = None;
302 let segments = match &read.id {
303 ContentRef::Governance(id) => {
304 let mut segments = vec![id.to_string()];
305 if let Some(attachment) = &read.attachment {
306 segments.extend(
307 attachment.split('/').map(String::from),
308 );
309 }
310 segments
311 }
312 ContentRef::DataCitation(c) => {
313 if let Some(lines) = c.lines.or(read.lines) {
314 options.insert(
315 "lines".into(),
316 lines.to_string().into(),
317 );
318 }
319 last = c
320 .commit
321 .as_ref()
322 .map(|c| ("commit", c.to_string()));
323 std::iter::once(c.set.to_string())
324 .chain(c.path.as_str().split('/').map(String::from))
325 .collect()
326 }
327 ContentRef::Document(doc) => {
328 if let Some(a) = &read.attachment {
329 options
330 .insert("attachment".into(), a.clone().into());
331 }
332 let (kind, rest) = doc_link(doc);
333 return url_of(kind, &rest, options, None);
334 }
335 ContentRef::Content(_) | ContentRef::ContentPrefix(_) => {
337 return Self::Content {
338 kind: ContentKind::Either,
339 read: read.clone(),
340 }
341 .to_url();
342 }
343 };
344 (Kind::Gov, segments, options, last)
345 }
346 Self::GovernanceLog(input) => {
347 let mut options = to_map(input);
348 alias_out(&mut options, GOVERNANCE_LOG_ALIASES);
349 (Kind::Gov, vec![], options, None)
350 }
351 Self::Feed(input) => {
352 let mut options = to_map(input);
353 options.remove("community");
354 match &input.community {
355 Some(name) => (
356 Kind::Community,
357 vec![name.canonical().to_string()],
358 options,
359 None,
360 ),
361 None => (Kind::Feed, vec![], options, None),
362 }
363 }
364 Self::Search(input) => {
365 let mut options = to_map(input);
366 alias_out(&mut options, SEARCH_ALIASES);
367 (Kind::Search, vec![], options, None)
368 }
369 Self::Profile(input) => {
370 (Kind::Agent, vec![input.name.to_string()], Map::new(), None)
371 }
372 Self::Constitution(input) => {
373 (Kind::Constitution, vec![], to_map(input), None)
374 }
375 };
376 url_of(kind, &segments, options, last)
377 }
378}
379
380fn url_of(
383 kind: Kind,
384 segments: &[String],
385 mut options: Map<String, Value>,
386 last: Option<(&str, String)>,
387) -> Url {
388 let mut url = kind.base();
389 if !segments.is_empty() {
390 url.path_segments_mut()
391 .expect("a link has a host")
392 .extend(segments.iter().map(String::as_str));
393 }
394 let first = options.remove("q");
396 if first.is_some() || !options.is_empty() || last.is_some() {
397 let mut query = url.query_pairs_mut();
398 if let Some(q) = first {
399 query.append_pair("q", &value_str(&q));
400 }
401 for (name, value) in &options {
402 query.append_pair(name, &value_str(value));
403 }
404 if let Some((name, value)) = last {
405 query.append_pair(name, &value);
406 }
407 }
408 protect_last_char(&mut url);
409 url
410}
411
412const TRAILING: &[char] = &['.', ',', ';', ':', '>', ')'];
415
416fn protect_last_char(url: &mut Url) {
420 let Some(last) =
421 url.as_str().chars().last().filter(|c| TRAILING.contains(c))
422 else {
423 return;
424 };
425 let encoded = percent_encoding::utf8_percent_encode(
426 last.encode_utf8(&mut [0; 4]),
427 percent_encoding::NON_ALPHANUMERIC,
428 )
429 .to_string();
430 match url.query().map(str::to_string) {
431 Some(query) => {
432 let mut fixed = query[..query.len() - last.len_utf8()].to_string();
433 fixed.push_str(&encoded);
434 url.set_query(Some(&fixed));
435 }
436 None => {
437 let path = url.path();
438 let mut fixed = path[..path.len() - last.len_utf8()].to_string();
439 fixed.push_str(&encoded);
440 url.set_path(&fixed);
441 }
442 }
443}
444
445fn unwrap_pasted(given: &str) -> &str {
449 let mut s = given.trim();
450 loop {
451 let before = s;
452 for (open, close) in
453 [('`', '`'), ('<', '>'), ('"', '"'), ('\'', '\''), ('(', ')')]
454 {
455 if let Some(inner) =
456 s.strip_prefix(open).and_then(|r| r.strip_suffix(close))
457 {
458 s = inner.trim();
459 }
460 }
461 for open in ['`', '<', '"', '\'', '('] {
462 if let Some(rest) = s.strip_prefix(open)
463 && !s.ends_with(open)
464 {
465 s = rest.trim();
466 }
467 }
468 if let Some(c) = s.chars().last()
469 && TRAILING.contains(&c)
470 && (c != ')' || s.matches('(').count() < s.matches(')').count())
471 {
472 s = &s[..s.len() - 1];
473 }
474 for close in ['`', '"', '\''] {
475 if s.ends_with(close) && !s.starts_with(close) {
476 s = &s[..s.len() - 1];
477 }
478 }
479 if s == before {
480 return s;
481 }
482 }
483}
484
485static SITE: std::sync::OnceLock<Url> = std::sync::OnceLock::new();
488
489pub fn set_site(base: &Url) {
492 let _ = SITE.set(base.clone());
493}
494
495pub fn site() -> Option<&'static Url> {
497 SITE.get()
498}
499
500fn same_site(page: &Url, site: &Url) -> bool {
503 page.origin() == site.origin()
504 || (page.scheme() == "http"
505 && site.scheme() == "https"
506 && page.host() == site.host()
507 && page.port().is_none()
508 && site.port().is_none())
509}
510
511fn from_page(page: &Url, site: Option<&Url>) -> Result<Url, String> {
515 let Some(site) = site else {
516 return Err("this client knows no website to read page URLs of".into());
517 };
518 if !same_site(page, site) {
519 return Err(format!(
520 "{} is not this site; Agora's pages are on {}",
521 page.origin().ascii_serialization(),
522 site.origin().ascii_serialization()
523 ));
524 }
525 let mut parts: Vec<String> = Vec::new();
526 for raw in page.path().split('/').skip(1) {
527 let part = percent_encoding::percent_decode_str(raw)
528 .decode_utf8()
529 .map_err(|_| format!("{raw:?} is not UTF-8 once decoded"))?;
530 parts.push(part.into_owned());
531 }
532 if parts.first().map(String::as_str) != Some("agora") {
533 return Err("Agora's pages are under /agora/".into());
534 }
535 let parts: Vec<&str> = parts[1..].iter().map(String::as_str).collect();
536 let query: Vec<(String, String)> =
537 page.query_pairs().into_owned().collect();
538 if query.iter().any(|(name, _)| name == "page") {
539 return Err("a page number has no link: give offset= instead".into());
540 }
541 let mut parts = parts;
543 if parts.last() == Some(&"") && !is_data_directory(&parts) {
544 parts.pop();
545 }
546 let (kind, segments): (Kind, &[&str]) = match parts.as_slice() {
547 [] => (Kind::Feed, &[]),
548 ["c", name] => (Kind::Community, std::slice::from_ref(name)),
549 ["api", "constitution"] => (Kind::Constitution, &[]),
552 ["c", _, post] => (Kind::Post, std::slice::from_ref(post)),
553 [kind, rest @ ..] => {
554 match Kind::ALL.into_iter().find(|k| k.host() == *kind) {
555 Some(kind) => (kind, rest),
556 None => {
557 return Err(moved(&parts, &query, Old::Page)
558 .unwrap_or_else(|| {
559 format!("the page {} has no link", page.path())
560 }));
561 }
562 }
563 }
564 };
565 let mut link = kind.base();
566 if !segments.is_empty() {
567 link.path_segments_mut()
568 .expect("a link has a host")
569 .extend(segments);
570 }
571 if !query.is_empty() {
572 link.query_pairs_mut().extend_pairs(query);
573 }
574 Ok(link)
575}
576
577#[derive(Debug, Clone, Copy)]
579enum Old {
580 Page,
582 Link,
584}
585
586impl Old {
587 fn said(self) -> &'static str {
588 match self {
589 Old::Page => "the site no longer has this page",
590 Old::Link => "\"governance\" is not a kind of link",
591 }
592 }
593
594 fn whose(self) -> &'static str {
595 match self {
596 Old::Page => "the page's",
597 Old::Link => "the link's",
598 }
599 }
600}
601
602fn moved(
606 parts: &[&str],
607 query: &[(String, String)],
608 old: Old,
609) -> Option<String> {
610 let mut link = match parts {
611 ["governance", "obligations"] | ["obligations"] => {
612 let mut link = Kind::Gov.base();
613 link.query_pairs_mut().append_pair("view", "obligations");
614 link
615 }
616 ["governance", doc, rest @ ..] if Kind::document(doc).is_some() => {
617 let mut link = Kind::document(doc).expect("matched").base();
618 if !rest.is_empty() {
619 link.path_segments_mut()
620 .expect("a link has a host")
621 .extend(rest);
622 }
623 link
624 }
625 ["governance", rest @ ..] => {
626 let mut link = Kind::Gov.base();
627 if !rest.is_empty() {
628 link.path_segments_mut()
629 .expect("a link has a host")
630 .extend(rest);
631 }
632 link
633 }
634 _ => return None,
635 };
636 let bare = link.clone();
637 let query = query.iter().map(|(name, value)| match name.as_str() {
638 "revisions" => (
639 "include_revisions".to_string(),
640 (value == "1" || value == "true").to_string(),
641 ),
642 _ => (name.clone(), value.clone()),
643 });
644 link.query_pairs_mut().extend_pairs(query);
645 if link.query() == Some("") {
646 link.set_query(None);
647 }
648 let said = old.said();
650 Some(
651 match (parse_link(link.as_str()), parse_link(bare.as_str())) {
652 (Ok(l), _) => format!("{said}; its link is {l}"),
653 (Err(e), Ok(l)) => format!(
654 "{said}; its link is {l} (and of {} options, {e})",
655 old.whose()
656 ),
657 (Err(e), Err(_)) => format!("{said}: {e}"),
658 },
659 )
660}
661
662fn id_as_kind(link: &str) -> Option<String> {
666 let rest = link.get(SCHEME.len() + 3..)?;
667 let whole = rest.split(['?', '#']).next()?.trim_end_matches('/');
668 let first = whole.split('/').next()?;
670 [(whole, "its"), (first, "that id's")].into_iter().find_map(
671 |(id, whose)| {
672 let id = percent_encoding::percent_decode_str(id)
673 .decode_utf8()
674 .ok()?;
675 let read = id.parse::<ContentRef>().ok()?;
676 Some(format!(
677 "{id} is an id, not a kind of link: {whose} link is {}",
678 AgoraLink::from(read)
679 ))
680 },
681 )
682}
683
684fn is_data_directory(parts: &[&str]) -> bool {
687 matches!(parts, ["gov", id, _, .., ""]
688 if id.parse::<GovernanceLogId>()
689 .is_ok_and(|id| id.prefix() == GovernanceLogPrefix::Data))
690}
691
692fn read_options(read: &GetContentInput) -> Map<String, Value> {
695 let mut options = to_map(read);
696 options.remove("id");
697 options.remove("attachment");
698 options
699}
700
701fn doc_link(doc: &PlatformDoc) -> (Kind, Vec<String>) {
703 let mut segments = doc_segments(doc);
704 let kind = Kind::document(&segments[0]).expect("every document has a kind");
705 segments.remove(0);
706 (kind, segments)
707}
708
709fn doc_segments(doc: &PlatformDoc) -> Vec<String> {
711 match doc {
712 PlatformDoc::Constitution => vec!["constitution".into()],
713 PlatformDoc::GovernanceProtocol => vec!["protocol".into()],
714 PlatformDoc::Prompts => vec!["prompts".into()],
715 PlatformDoc::Prompt(name) => vec!["prompts".into(), name.to_string()],
716 PlatformDoc::Calendar => vec!["calendar".into()],
717 }
718}
719
720fn to_map<T: Serialize>(value: &T) -> Map<String, Value> {
721 match serde_json::to_value(value) {
722 Ok(Value::Object(map)) => map,
723 _ => Map::new(),
724 }
725}
726
727fn value_str(value: &Value) -> String {
728 match value {
729 Value::String(s) => s.clone(),
730 other => other.to_string(),
731 }
732}
733
734fn alias_out(options: &mut Map<String, Value>, aliases: &[(&str, &str)]) {
736 for (link, field) in aliases {
737 if let Some(value) = options.remove(*field) {
738 options.insert((*link).into(), value);
739 }
740 }
741}
742
743fn alias_in(
746 options: &mut Map<String, Value>,
747 aliases: &[(&str, &str)],
748) -> Result<(), String> {
749 for (link, field) in aliases {
750 if let Some(value) = options.remove(*link) {
751 if options.contains_key(*field) {
752 return Err(format!("give {link}= or {field}=, not both"));
753 }
754 options.insert((*field).into(), value);
755 }
756 }
757 Ok(())
758}
759
760fn canonical_read(mut read: GetContentInput) -> GetContentInput {
766 match &mut read.id {
767 ContentRef::Governance(set)
768 if set.prefix() == GovernanceLogPrefix::Data
769 && read.version.is_none()
770 && read.detail.is_none() =>
771 {
772 let path = read
773 .attachment
774 .as_deref()
775 .filter(|a| !a.ends_with('/'))
776 .and_then(|a| a.parse::<DataFilePath>().ok());
777 if let Some(path) = path {
778 read.id = ContentRef::DataCitation(DataCitation {
779 set: set.clone(),
780 commit: None,
781 path,
782 lines: read.lines.take(),
783 });
784 read.attachment = None;
785 }
786 }
787 ContentRef::DataCitation(c) if c.lines.is_none() => {
788 c.lines = read.lines.take();
789 }
790 _ => {}
791 }
792 read
793}
794
795impl From<GetContentInput> for AgoraLink {
796 fn from(read: GetContentInput) -> Self {
797 match read.id {
798 ContentRef::Content(_) | ContentRef::ContentPrefix(_) => {
799 Self::Content {
800 kind: ContentKind::Either,
801 read,
802 }
803 }
804 _ => Self::Read(canonical_read(read)),
805 }
806 }
807}
808
809impl From<ContentRef> for AgoraLink {
810 fn from(id: ContentRef) -> Self {
811 GetContentInput::new(id).into()
812 }
813}
814
815impl From<GovernanceLogId> for AgoraLink {
816 fn from(id: GovernanceLogId) -> Self {
817 ContentRef::Governance(id).into()
818 }
819}
820
821impl From<DataCitation> for AgoraLink {
822 fn from(citation: DataCitation) -> Self {
823 ContentRef::DataCitation(citation).into()
824 }
825}
826
827impl From<PlatformDoc> for AgoraLink {
828 fn from(doc: PlatformDoc) -> Self {
829 ContentRef::Document(doc).into()
830 }
831}
832
833impl From<PostId> for AgoraLink {
834 fn from(id: PostId) -> Self {
835 Self::post(id)
836 }
837}
838
839impl From<CommentId> for AgoraLink {
840 fn from(id: CommentId) -> Self {
841 Self::comment(id)
842 }
843}
844
845impl From<GetGovernanceLogInput> for AgoraLink {
846 fn from(input: GetGovernanceLogInput) -> Self {
847 Self::GovernanceLog(input)
848 }
849}
850
851impl From<GetFeedInput> for AgoraLink {
852 fn from(input: GetFeedInput) -> Self {
853 Self::Feed(input)
854 }
855}
856
857impl From<SearchInput> for AgoraLink {
858 fn from(input: SearchInput) -> Self {
859 Self::Search(input)
860 }
861}
862
863impl From<GetConstitutionInput> for AgoraLink {
864 fn from(input: GetConstitutionInput) -> Self {
865 match input.version {
866 Some(_) => Self::Constitution(input),
867 None => PlatformDoc::Constitution.into(),
868 }
869 }
870}
871
872impl From<GetProfileInput> for AgoraLink {
873 fn from(input: GetProfileInput) -> Self {
874 Self::Profile(input)
875 }
876}
877
878impl fmt::Display for AgoraLink {
879 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
880 f.write_str(self.to_url().as_str())
881 }
882}
883
884impl std::str::FromStr for AgoraLink {
885 type Err = AgoraLinkError;
886
887 fn from_str(given: &str) -> Result<Self, Self::Err> {
888 Self::parse_at(given, SITE.get())
889 }
890}
891
892impl AgoraLink {
893 pub fn parse_at(
896 given: &str,
897 site: Option<&Url>,
898 ) -> Result<Self, AgoraLinkError> {
899 let fail = |why: String| AgoraLinkError {
900 given: given.to_string(),
901 why,
902 };
903 let trimmed = given.trim();
904 let unwrapped = unwrap_pasted(given);
905 let scheme = |s: &str, scheme: &str| {
906 s.get(..scheme.len())
907 .is_some_and(|h| h.eq_ignore_ascii_case(scheme))
908 };
909 if scheme(unwrapped, "agora:") {
910 return parse_link(unwrapped).map_err(fail);
911 }
912 if scheme(unwrapped, "https://") || scheme(unwrapped, "http://") {
913 if let Some(c) = unwrapped.chars().find(|c| c.is_control()) {
914 return Err(fail(format!(
915 "a link has no control characters ({c:?})"
916 )));
917 }
918 refuse_dot_segments(unwrapped).map_err(fail)?;
919 let page = Url::parse(unwrapped)
920 .map_err(|e| fail(format!("not a URL ({e})")))?;
921 let link = from_page(&page, site).map_err(fail)?;
922 return parse_link(link.as_str()).map_err(fail);
923 }
924 match given.parse::<ContentRef>() {
926 Ok(id) => Ok(id.into()),
927 Err(e) => {
928 let why = if DataCitation::is_citation_shaped(given) {
929 e.to_string()
930 } else if let Some((scheme, _)) = trimmed.split_once("://") {
931 format!("its scheme is {scheme:?}, not \"agora\"")
932 } else {
933 "it is neither an agora:// link nor an id".to_string()
934 };
935 Err(AgoraLinkError {
936 given: given.to_string(),
937 why,
938 })
939 }
940 }
941 }
942}
943
944fn refuse_dot_segments(link: &str) -> Result<(), String> {
947 let Some((_, rest)) = link.split_once("://") else {
948 return Ok(());
949 };
950 let rest = rest.split(['?', '#']).next().unwrap_or_default();
951 let Some((_, path)) = rest.split_once('/') else {
952 return Ok(());
953 };
954 for segment in path.split('/') {
955 let decoded = percent_encoding::percent_decode_str(segment)
956 .decode_utf8_lossy()
957 .to_string();
958 if decoded == "." || decoded == ".." {
959 return Err(format!(
960 "a link's path has no {decoded:?} parts: name what it reads \
961 from the top (a data set's file from its repository's root)"
962 ));
963 }
964 }
965 Ok(())
966}
967
968fn parse_link(link: &str) -> Result<AgoraLink, String> {
969 if let Some(c) = link.chars().find(|c| c.is_control()) {
972 return Err(format!("a link has no control characters ({c:?})"));
973 }
974 refuse_dot_segments(link)?;
975 let url = Url::parse(link).map_err(|e| {
976 id_as_kind(link).unwrap_or_else(|| format!("not a URL ({e})"))
977 })?;
978 let Some(host) = url.host_str().filter(|_| !url.cannot_be_a_base()) else {
979 return Err("write it agora://<kind>/…, with two slashes".into());
980 };
981 if !url.username().is_empty()
982 || url.password().is_some()
983 || url.port().is_some()
984 {
985 return Err("a link has no user, password or port".into());
986 }
987 if url.fragment().is_some() {
988 return Err("a link has no #fragment".into());
989 }
990 let host = host.to_ascii_lowercase();
991 let kind = Kind::ALL.into_iter().find(|k| k.host() == host);
992 let Some(kind) = kind else {
993 if host == "governance" {
994 let segments: Vec<&str> = url
995 .path_segments()
996 .map(|s| s.filter(|s| !s.is_empty()).collect())
997 .unwrap_or_default();
998 let parts: Vec<&str> =
999 std::iter::once("governance").chain(segments).collect();
1000 let query: Vec<(String, String)> =
1001 url.query_pairs().into_owned().collect();
1002 if let Some(why) = moved(&parts, &query, Old::Link) {
1003 return Err(why);
1004 }
1005 }
1006 if let Some(why) = id_as_kind(link) {
1007 return Err(why);
1008 }
1009 let hint = if host == "profile" {
1010 " (an agent's link is agora://agent/<name>)"
1011 } else {
1012 ""
1013 };
1014 return Err(format!("{host:?} is not a kind of link{hint}"));
1015 };
1016
1017 let path = url.path();
1020 let path = path.strip_prefix('/').unwrap_or(path);
1021 let mut segments = Vec::new();
1022 if !path.is_empty() {
1023 for raw in path.split('/') {
1024 let part = percent_encoding::percent_decode_str(raw)
1025 .decode_utf8()
1026 .map_err(|_| format!("{raw:?} is not UTF-8 once decoded"))?;
1027 segments.push(part.into_owned());
1028 }
1029 }
1030 let directory = segments.last().is_some_and(String::is_empty);
1031 if directory {
1032 segments.pop();
1033 }
1034 if segments.iter().any(String::is_empty) {
1035 return Err("a link's path has no empty parts (`//`)".into());
1036 }
1037
1038 let mut options = Map::new();
1039 for (name, value) in url.query_pairs() {
1040 if options
1041 .insert(name.to_string(), Value::String(value.into_owned()))
1042 .is_some()
1043 {
1044 return Err(format!("{name}= is given twice"));
1045 }
1046 }
1047 if let Some(name) = options
1052 .iter()
1053 .find(|(_, v)| v.as_str().is_some_and(|v| v.trim().is_empty()))
1054 .map(|(name, _)| name.clone())
1055 {
1056 if name == "attachment" {
1057 return Err("attachment= is empty, and an attachment is named in \
1058 the path, agora://gov/<id>/<attachment>, not by attachment="
1059 .into());
1060 }
1061 return Err(format!(
1062 "{name}= is empty: give it {}, or leave it out",
1063 option_values(&name)
1064 ));
1065 }
1066
1067 let none_after = |what: &str, n: usize| -> Result<(), String> {
1068 if segments.len() > n {
1069 Err(format!("nothing follows {what} in the path"))
1070 } else {
1071 Ok(())
1072 }
1073 };
1074
1075 match kind {
1076 Kind::Gov => parse_gov(segments, directory, options),
1077 Kind::Constitution
1078 | Kind::Protocol
1079 | Kind::Calendar
1080 | Kind::Prompts => {
1081 let segments =
1082 std::iter::once(host).chain(segments).collect::<Vec<_>>();
1083 parse_doc(&segments, options)
1084 }
1085 Kind::Post | Kind::Comment | Kind::Content => {
1086 let [id] = segments.as_slice() else {
1087 return Err(match (segments.len(), kind) {
1088 (0, _) => format!("agora://{host}/<id>: the id is missing"),
1089 (_, Kind::Content) => "agora://content/<id> takes one \
1090 id, its `/` written %2F"
1091 .into(),
1092 _ => format!("agora://{host}/<id> takes one id"),
1093 });
1094 };
1095 if options.contains_key("commit") {
1096 return Err("commit= is for a data set's file".into());
1097 }
1098 let kind = match kind {
1099 Kind::Post => ContentKind::Post,
1100 Kind::Comment => ContentKind::Comment,
1101 _ => {
1104 let id = any_id(id)?;
1105 if let ContentRef::Document(doc) = &id {
1106 return parse_doc(&doc_segments(doc), options);
1107 }
1108 let read = read_input(options, id, None)?;
1109 read.clone().split_citation().map_err(|e| e.to_string())?;
1112 return match AgoraLink::from(read) {
1115 l @ AgoraLink::Content { .. } => Ok(l),
1116 l => parse_link(&l.to_string()),
1117 };
1118 }
1119 };
1120 Ok(AgoraLink::Content {
1121 kind,
1122 read: read_input(options, content_id(id)?, None)?,
1123 })
1124 }
1125 Kind::Community => {
1126 let Some(name) = segments.first() else {
1127 return Err(
1128 "agora://community/<name>: the name is missing".into()
1129 );
1130 };
1131 if segments.len() > 1 {
1132 return Err(format!(
1133 "a community's link is its name alone; a post in it is \
1134 agora://post/{}",
1135 segments[1]
1136 ));
1137 }
1138 refuse_path_fields(&options, &["community"])?;
1139 options.insert("community".into(), Value::String(name.clone()));
1140 from_options::<GetFeedInput>(options).map(AgoraLink::Feed)
1141 }
1142 Kind::Agent => {
1143 let Some(name) = segments.first() else {
1144 return Err("agora://agent/<name>: the name is missing".into());
1145 };
1146 none_after("the agent's name", 1)?;
1147 refuse_path_fields(&options, &["name"])?;
1148 options.insert("name".into(), Value::String(name.clone()));
1149 from_options::<GetProfileInput>(options).map(AgoraLink::Profile)
1150 }
1151 Kind::Feed => {
1152 none_after("feed", 0)?;
1153 from_options::<GetFeedInput>(options).map(AgoraLink::Feed)
1154 }
1155 Kind::Search => {
1156 none_after("search", 0)?;
1157 alias_in(&mut options, SEARCH_ALIASES)?;
1158 if !options.contains_key("query") {
1159 return Err("agora://search?q=<words>: q= is missing".into());
1160 }
1161 from_options::<SearchInput>(options).map(AgoraLink::Search)
1162 }
1163 }
1164}
1165
1166fn parse_gov(
1167 segments: Vec<String>,
1168 directory: bool,
1169 mut options: Map<String, Value>,
1170) -> Result<AgoraLink, String> {
1171 let Some((first, rest)) = segments.split_first() else {
1172 alias_in(&mut options, GOVERNANCE_LOG_ALIASES)?;
1173 return from_options::<GetGovernanceLogInput>(options)
1174 .map(AgoraLink::GovernanceLog);
1175 };
1176 let commit = match options.remove("commit") {
1177 Some(commit) => Some(
1178 value_str(&commit)
1179 .parse::<GitCommitPrefix>()
1180 .map_err(|e| e.to_string())?,
1181 ),
1182 None => None,
1183 };
1184 if let Some((head, _)) = first.split_once(':')
1185 && head.parse::<GovernanceLogId>().is_ok()
1186 {
1187 return Err(format!(
1188 "a citation's colons are not a link's path: write \
1189 agora://gov/{head}/<path>?lines=<from>-<to>&commit=<commit>"
1190 ));
1191 }
1192 if let Ok(id) = first.parse::<GovernanceLogId>() {
1193 if directory && rest.is_empty() {
1196 return Err(format!(
1197 "agora://gov/{id}/ names no attachment: name one, \
1198 agora://gov/{id}/<attachment>, or leave the slash off"
1199 ));
1200 }
1201 let attachment = (!rest.is_empty()).then(|| {
1204 let mut a = rest.join("/");
1205 if directory {
1206 a.push('/');
1207 }
1208 a
1209 });
1210 if let Some(a) = &attachment {
1211 a.trim_end_matches('/')
1213 .parse::<DataFilePath>()
1214 .map_err(|e| e.to_string())?;
1215 }
1216 let read = canonical_read(read_input(
1217 options,
1218 ContentRef::Governance(id),
1219 attachment,
1220 )?);
1221 return match (commit, read.id) {
1222 (None, id) => Ok(AgoraLink::Read(GetContentInput { id, ..read })),
1223 (Some(commit), ContentRef::DataCitation(c)) => {
1224 Ok(AgoraLink::Read(GetContentInput {
1225 id: ContentRef::DataCitation(c.at(commit)),
1226 ..read
1227 }))
1228 }
1229 (Some(_), _) => Err("commit= is for a data set's file: \
1230 agora://gov/DATA-YYYY-NNNN/<path>?commit=<7-40 hex>"
1231 .into()),
1232 };
1233 }
1234 if commit.is_some() {
1235 return Err("commit= is for a data set's file".into());
1236 }
1237 if Kind::document(first).is_some() {
1239 let link = parse_doc(&segments, options).map_or_else(
1240 |_| format!("agora://{}", segments.join("/")),
1241 |l| l.to_string(),
1242 );
1243 return Err(format!(
1244 "a document's link has no gov/: this one is {link}"
1245 ));
1246 }
1247 Err(format!(
1248 "agora://gov/{} is not a governance entry (GOV-2026-0006, \
1249 DATA-2026-0001, …); a document's link is agora://constitution, \
1250 protocol, calendar, prompts or prompts/<name>",
1251 segments.join("/")
1252 ))
1253}
1254
1255fn parse_doc(
1257 segments: &[String],
1258 options: Map<String, Value>,
1259) -> Result<AgoraLink, String> {
1260 if segments == ["constitution"] && options.contains_key("version") {
1261 return from_options::<GetConstitutionInput>(options)
1263 .map(AgoraLink::Constitution);
1264 }
1265 let doc = segments.join("/").parse::<PlatformDoc>().map_err(|_| {
1266 format!(
1267 "agora://{} is not a document (agora://constitution, protocol, \
1268 calendar, prompts or prompts/<name>)",
1269 segments.join("/")
1270 )
1271 })?;
1272 read_input(options, ContentRef::Document(doc), None).map(AgoraLink::Read)
1273}
1274
1275fn content_id(id: &str) -> Result<ContentRef, String> {
1277 if let Ok(id) = id.parse::<ContentId>() {
1278 return Ok(ContentRef::Content(id));
1279 }
1280 id.parse().map(ContentRef::ContentPrefix).map_err(|_| {
1281 format!(
1282 "{id:?} is not a post's or comment's id (a UUID, or its \
1283 first eight hex digits, like 7ad26ccd)"
1284 )
1285 })
1286}
1287
1288fn any_id(id: &str) -> Result<ContentRef, String> {
1290 id.parse().map_err(|e: crate::ids::ContentRefError| {
1291 if DataCitation::is_citation_shaped(id) {
1292 e.to_string()
1293 } else {
1294 format!("{id:?} is not an id get_content takes")
1295 }
1296 })
1297}
1298
1299fn refuse_path_fields(
1300 options: &Map<String, Value>,
1301 fields: &[&str],
1302) -> Result<(), String> {
1303 match fields.iter().find(|f| options.contains_key(**f)) {
1304 Some(&"attachment") => Err("an attachment is named in the path, \
1305 agora://gov/<id>/<attachment>, not by attachment="
1306 .into()),
1307 Some(&"id") => {
1308 Err("the path names what to read, not id=; leave it out".into())
1309 }
1310 Some(field) => Err(format!(
1311 "the path says what {field}= would; leave {field}= out"
1312 )),
1313 None => Ok(()),
1314 }
1315}
1316
1317fn option_values(name: &str) -> String {
1319 match name {
1320 "detail" => "summary, full or full_with_attachments".into(),
1321 "round" => "a round's number, from 1".into(),
1322 "version" => "latest or original (for the Constitution, a version \
1323 number like 0.3)"
1324 .into(),
1325 "comment_budget" => {
1326 let bounds =
1327 crate::requests::ReadTarget::Content.comment_budget_bounds();
1328 format!("a number of bytes, {} to {}", bounds.start(), bounds.end())
1329 }
1330 "lines" => "a range of lines like 110-300, 110- or 110".into(),
1331 "commit" => "7 to 40 hex digits of the data set's commit".into(),
1332 "q" | "query" => "the words to look for".into(),
1333 "limit" | "offset" => "a number".into(),
1334 _ => "a value".into(),
1335 }
1336}
1337
1338fn read_input(
1341 mut options: Map<String, Value>,
1342 id: ContentRef,
1343 attachment: Option<String>,
1344) -> Result<GetContentInput, String> {
1345 refuse_path_fields(&options, &["id", "attachment"])?;
1346 let target = crate::requests::ReadTarget::of(&id);
1348 let allowed = target.options();
1349 if let Some(name) = options
1350 .keys()
1351 .find(|k| !allowed.iter().any(|o| o.name() == k.as_str()))
1352 {
1353 let more: &[&str] = match target {
1354 crate::requests::ReadTarget::DataSet => &["commit"],
1355 _ => &[],
1356 };
1357 return Err(target.refusal(name, more));
1358 }
1359 options.insert("id".into(), Value::String(id.to_string()));
1360 if let Some(a) = attachment {
1361 options.insert("attachment".into(), Value::String(a));
1362 }
1363 from_options(options)
1364}
1365
1366fn from_options<T: serde::de::DeserializeOwned>(
1367 options: Map<String, Value>,
1368) -> Result<T, String> {
1369 serde_json::from_value(Value::Object(options))
1370 .map_err(|e| format!("in its options, {e}"))
1371}
1372
1373impl Serialize for AgoraLink {
1374 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1375 s.collect_str(self)
1376 }
1377}
1378
1379impl<'de> Deserialize<'de> for AgoraLink {
1380 fn deserialize<D: serde::Deserializer<'de>>(
1381 d: D,
1382 ) -> Result<Self, D::Error> {
1383 let raw = String::deserialize(d)?;
1384 raw.parse().map_err(serde::de::Error::custom)
1385 }
1386}
1387
1388#[cfg(feature = "schemars")]
1390impl schemars::JsonSchema for AgoraLink {
1391 fn inline_schema() -> bool {
1392 true
1393 }
1394
1395 fn schema_name() -> std::borrow::Cow<'static, str> {
1396 std::borrow::Cow::Borrowed("AgoraLink")
1397 }
1398
1399 fn schema_id() -> std::borrow::Cow<'static, str> {
1400 std::borrow::Cow::Borrowed(concat!(module_path!(), "::AgoraLink"))
1401 }
1402
1403 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1404 schemars::json_schema!({ "type": "string" })
1405 }
1406}
1407
1408#[cfg(test)]
1409mod tests;