jacquard 0.11.0

Simple and powerful AT Protocol client library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
//! Rich text utilities for Bluesky posts
//!
//! Provides parsing and building of rich text with facets (mentions, links, tags)
//! and detection of embed candidates (record and external embeds).

#[cfg(feature = "api_bluesky")]
use crate::api::app_bsky::richtext::facet::Facet;
#[cfg(feature = "api_bluesky")]
use crate::api::com_atproto::repo::strong_ref::StrongRef;
use crate::common::CowStr;
#[cfg(feature = "api_bluesky")]
use crate::types::aturi::AtUri;
use jacquard_common::IntoStatic;
#[cfg(feature = "api_bluesky")]
use jacquard_common::http_client::HttpClient;
use jacquard_common::types::did::{DID_REGEX, Did};
use jacquard_common::types::handle::HANDLE_REGEX;
use jacquard_common::types::string::AtStrError;
use jacquard_common::types::uri::UriParseError;
use jacquard_identity::resolver::IdentityError;
#[cfg(feature = "api_bluesky")]
use jacquard_identity::resolver::IdentityResolver;
#[cfg(not(target_family = "wasm"))]
use regex::{Captures, Regex};
#[cfg(target_family = "wasm")]
use regex_lite::{Captures, Regex};
use std::marker::PhantomData;
use std::ops::Range;
use std::sync::LazyLock;

// Regex patterns based on Bluesky's official implementation
// https://github.com/bluesky-social/atproto/blob/main/packages/api/src/rich-text/util.ts

static MENTION_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(^|\s|\()(@)([a-zA-Z0-9.:-]+)(\b)").unwrap());

static URL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(^|\s|\()((https?://[\S]+)|((?<domain>[a-z][a-z0-9]*(\.[a-z0-9]+)+)[\S]*))")
        .unwrap()
});

static TAG_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    // Pattern: (^|\s)[##](prefix* core+ suffix*)?
    //
    // - prefix: [^\s\u{00AD}...]* - any chars except spaces/zero-width (optional)
    // - core: [^\d\s\p{P}\u{00AD}...]+ - at least one char that's not digit/space/punct/zero-width (required)
    // - suffix: [^\s\u{00AD}...]* - any chars except spaces/zero-width (optional)
    //
    // Zero-width chars excluded: \u{00AD} (soft hyphen), \u{2060} (word joiner),
    //   \u{200A}-\u{200D} (hair space, zero-width space/joiner/non-joiner), \u{20e2} (combining mark)
    //
    // Note: emoji modifier (\ufe0f) is filtered in detect_tags() since Rust regex
    // doesn't support negative lookahead
    Regex::new(
        r"(^|\s)[##]([^\s\u{00AD}\u{2060}\u{200A}\u{200B}\u{200C}\u{200D}\u{20e2}]*[^\d\s\p{P}\u{00AD}\u{2060}\u{200A}\u{200B}\u{200C}\u{200D}\u{20e2}]+[^\s\u{00AD}\u{2060}\u{200A}\u{200B}\u{200C}\u{200D}\u{20e2}]*)?"
    ).unwrap()
});

static MARKDOWN_LINK_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\[([^\]]+)\]\(([^)]+)\)").unwrap());

static TRAILING_PUNCT_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\p{P}+$").unwrap());

// Sanitization regex - removes soft hyphens, zero-width chars, normalizes newlines
// Matches one of the special chars, optionally followed by whitespace, repeated
// This ensures at least one special char is in the match (won't match pure spaces)
static SANITIZE_NEWLINES_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"([\r\n\u{00AD}\u{2060}\u{200D}\u{200C}\u{200B}]\s*)+").unwrap());

/// Default domains that support at-URI extraction from URLs
/// (bsky.app URL patterns like /profile/{actor}/post/{rkey})
#[cfg(feature = "api_bluesky")]
pub static DEFAULT_EMBED_DOMAINS: &[&str] = &[
    "bsky.app",
    "deer.social",
    "blacksky.community",
    "catsky.social",
];

/// Marker type indicating all facets are resolved (no handles pending DID resolution)
pub struct Resolved;

/// Marker type indicating some facets may need resolution (handles → DIDs)
pub struct Unresolved;

/// Rich text with facets (mentions, links, tags)
#[derive(Debug, Clone)]
#[cfg(feature = "api_bluesky")]
pub struct RichText<'a> {
    /// The text content
    pub text: CowStr<'a>,
    /// Facets (mentions, links, tags)
    pub facets: Option<Vec<Facet<'a>>>,
}

#[cfg(feature = "api_bluesky")]
impl RichText<'static> {
    /// Entry point for parsing text with automatic facet detection
    ///
    /// Uses default embed domains (bsky.app, deer.social) for at-URI extraction.
    pub fn parse(text: impl AsRef<str>) -> RichTextBuilder<Unresolved> {
        parse(text)
    }

    /// Entry point for manual richtext construction
    pub fn builder() -> RichTextBuilder<Resolved> {
        RichTextBuilder::builder()
    }
}

/// Detected embed candidate from URL or at-URI
#[derive(Debug, Clone)]
#[cfg(feature = "api_bluesky")]
pub enum EmbedCandidate<'a> {
    /// Bluesky record (post, list, starterpack, feed)
    Record {
        /// The at:// URI identifying the record
        at_uri: AtUri<'a>,
        /// Strong reference (repo + CID) if resolved
        strong_ref: Option<StrongRef<'a>>,
    },
    /// External link embed
    External {
        /// The URL
        url: CowStr<'a>,
        /// OpenGraph metadata if fetched
        metadata: Option<ExternalMetadata<'a>>,
    },
}

/// External embed metadata (OpenGraph)
#[derive(Debug, Clone)]
#[cfg(feature = "api_bluesky")]
pub struct ExternalMetadata<'a> {
    /// Page title
    pub title: CowStr<'a>,
    /// Page description
    pub description: CowStr<'a>,
    /// Thumbnail URL
    pub thumbnail: Option<CowStr<'a>>,
}

/// Rich text builder supporting both parsing and manual construction
#[derive(Debug)]
pub struct RichTextBuilder<State> {
    text: String,
    facet_candidates: Vec<FacetCandidate>,
    #[cfg(feature = "api_bluesky")]
    embed_candidates: Option<Vec<EmbedCandidate<'static>>>,
    _state: PhantomData<State>,
}

/// Internal representation of facet before resolution
///
/// Stores minimal data to save memory:
/// - Markdown links store URL (since syntax is stripped from text)
/// - Mentions/tags store just ranges (@ and # included, extract at build time)
/// - Links store just ranges (normalize URL at build time)
#[derive(Debug, Clone)]
enum FacetCandidate {
    /// Markdown link: `[display](url)` → display text in final text
    MarkdownLink {
        /// Range of display text in final processed text
        display_range: Range<usize>,
        /// URL from markdown (not in final text, so must store)
        url: String,
    },
    /// Mention: `@handle.bsky.social`
    /// Range includes the @ symbol, process at build time
    Mention {
        /// Range in text including @ symbol
        range: Range<usize>,
        /// DID when provided, otherwise resolved later
        did: Option<Did<'static>>,
    },
    /// Plain URL link
    /// Range points to URL in text, normalize at build time
    Link {
        /// Range in text pointing to URL (may need normalization)
        range: Range<usize>,
    },
    /// Hashtag: `#tag`
    /// Range includes the # symbol, process at build time
    Tag {
        /// Range in text including # symbol
        range: Range<usize>,
    },
}

/// Sanitize text by removing invisible characters and normalizing newlines
///
/// This removes:
/// - Soft hyphens (\u{00AD})
/// - Zero-width non-joiner (\u{200C})
/// - Zero-width joiner (\u{200D})
/// - Zero-width space (\u{200B})
/// - Word joiner (\u{2060})
///
/// And normalizes all newline variants (\r\n, \r, \n) to \n, while collapsing
/// runs of newlines and invisible chars to at most two newlines.
fn sanitize_text(text: &str) -> String {
    SANITIZE_NEWLINES_REGEX
        .replace_all(text, |caps: &Captures| {
            let matched = caps.get(0).unwrap().as_str();

            // Count newline sequences, treating \r\n as one unit
            let mut newline_sequences = 0;
            let mut chars = matched.chars().peekable();

            while let Some(c) = chars.next() {
                if c == '\r' {
                    // Check if followed by \n
                    if chars.peek() == Some(&'\n') {
                        chars.next(); // consume the \n
                    }
                    newline_sequences += 1;
                } else if c == '\n' {
                    newline_sequences += 1;
                }
                // Skip invisible chars (they don't increment count)
            }

            if newline_sequences == 0 {
                // Only invisible chars, remove them
                ""
            } else if newline_sequences == 1 {
                "\n"
            } else {
                // Multiple newlines, collapse to \n\n (paragraph break)
                "\n\n"
            }
        })
        .to_string()
}

/// Entry point for parsing text with automatic facet detection
///
/// Uses default embed domains (bsky.app, deer.social, blacksky.community, catsky.social) for at-URI extraction.
/// For custom domains, use [`parse_with_domains`].
pub fn parse(text: impl AsRef<str>) -> RichTextBuilder<Unresolved> {
    #[cfg(feature = "api_bluesky")]
    {
        parse_with_domains(text, DEFAULT_EMBED_DOMAINS)
    }
    #[cfg(not(feature = "api_bluesky"))]
    {
        parse_with_domains(text)
    }
}

/// Parse text with custom embed domains for at-URI extraction
///
/// This allows specifying additional domains (beyond the defaults)
/// that use the same URL patterns for records (e.g., /profile/{actor}/post/{rkey}).
#[cfg(feature = "api_bluesky")]
pub fn parse_with_domains(
    text: impl AsRef<str>,
    embed_domains: &[&str],
) -> RichTextBuilder<Unresolved> {
    // Step 0: Sanitize text (remove invisible chars, normalize newlines)
    let text = sanitize_text(text.as_ref());

    let mut facet_candidates = Vec::new();
    let mut embed_candidates = Vec::new();

    // Step 1: Detect and strip markdown links first
    let (text_processed, markdown_facets) = detect_markdown_links(&text);

    // Check markdown links for embed candidates
    for facet in &markdown_facets {
        if let FacetCandidate::MarkdownLink { url, .. } = facet {
            if let Some(embed) = classify_embed(url, embed_domains) {
                embed_candidates.push(embed);
            }
        }
    }

    facet_candidates.extend(markdown_facets);

    // Step 2: Detect mentions
    let mention_facets = detect_mentions(&text_processed);
    facet_candidates.extend(mention_facets);

    // Step 3: Detect URLs
    let url_facets = detect_urls(&text_processed);

    // Check URLs for embed candidates
    for facet in &url_facets {
        if let FacetCandidate::Link { range } = facet {
            let url = &text_processed[range.clone()];
            if let Some(embed) = classify_embed(url, embed_domains) {
                embed_candidates.push(embed);
            }
        }
    }

    facet_candidates.extend(url_facets);

    // Step 4: Detect tags
    let tag_facets = detect_tags(&text_processed);
    facet_candidates.extend(tag_facets);

    RichTextBuilder {
        text: text_processed,
        facet_candidates,
        embed_candidates: if embed_candidates.is_empty() {
            None
        } else {
            Some(embed_candidates)
        },
        _state: PhantomData,
    }
}

/// Parse text without embed detection (no api_bluesky feature)
#[cfg(not(feature = "api_bluesky"))]
pub fn parse_with_domains(text: impl AsRef<str>) -> RichTextBuilder<Unresolved> {
    // Step 0: Sanitize text (remove invisible chars, normalize newlines)
    let text = sanitize_text(text.as_ref());

    let mut facet_candidates = Vec::new();

    // Step 1: Detect and strip markdown links first
    let (text_processed, markdown_facets) = detect_markdown_links(&text);
    facet_candidates.extend(markdown_facets);

    // Step 2: Detect mentions
    let mention_facets = detect_mentions(&text_processed);
    facet_candidates.extend(mention_facets);

    // Step 3: Detect URLs
    let url_facets = detect_urls(&text_processed);
    facet_candidates.extend(url_facets);

    // Step 4: Detect tags
    let tag_facets = detect_tags(&text_processed);
    facet_candidates.extend(tag_facets);

    RichTextBuilder {
        text: text_processed,
        facet_candidates,
        _state: PhantomData,
    }
}

impl RichTextBuilder<Resolved> {
    /// Entry point for manual richtext construction
    pub fn builder() -> Self {
        RichTextBuilder {
            text: String::new(),
            facet_candidates: Vec::new(),
            #[cfg(feature = "api_bluesky")]
            embed_candidates: None,
            _state: PhantomData,
        }
    }

    /// Add a mention by handle (transitions to Unresolved state)
    pub fn mention_handle(
        mut self,
        handle: impl AsRef<str>,
        range: Option<Range<usize>>,
    ) -> RichTextBuilder<Unresolved> {
        let handle = handle.as_ref();
        let range = range.unwrap_or_else(|| {
            // Scan text for @handle
            let search = format!("@{}", handle);
            self.find_substring(&search).unwrap_or(0..0)
        });

        self.facet_candidates
            .push(FacetCandidate::Mention { range, did: None });

        RichTextBuilder {
            text: self.text,
            facet_candidates: self.facet_candidates,
            #[cfg(feature = "api_bluesky")]
            embed_candidates: self.embed_candidates,
            _state: PhantomData,
        }
    }
}

impl<S> RichTextBuilder<S> {
    /// Set the text content
    pub fn text(mut self, text: impl AsRef<str>) -> Self {
        self.text = sanitize_text(text.as_ref());
        self
    }

    /// Add a mention facet with a resolved DID (requires explicit range)
    pub fn mention(mut self, did: &Did<'_>, range: Range<usize>) -> Self {
        self.facet_candidates.push(FacetCandidate::Mention {
            range,
            did: Some(did.clone().into_static()),
        });
        self
    }

    /// Add a link facet (auto-detects range if None)
    pub fn link(mut self, url: impl AsRef<str>, range: Option<Range<usize>>) -> Self {
        let url = url.as_ref();
        let range = range.unwrap_or_else(|| {
            // Scan text for the URL
            self.find_substring(url).unwrap_or(0..0)
        });

        self.facet_candidates.push(FacetCandidate::Link { range });
        self
    }

    /// Add a tag facet (auto-detects range if None)
    pub fn tag(mut self, tag: impl AsRef<str>, range: Option<Range<usize>>) -> Self {
        let tag = tag.as_ref();
        let range = range.unwrap_or_else(|| {
            // Scan text for #tag
            let search = format!("#{}", tag);
            self.find_substring(&search).unwrap_or(0..0)
        });

        self.facet_candidates.push(FacetCandidate::Tag { range });
        self
    }

    /// Add a markdown-style link with display text
    pub fn markdown_link(mut self, url: impl Into<String>, display_range: Range<usize>) -> Self {
        self.facet_candidates.push(FacetCandidate::MarkdownLink {
            url: url.into(),
            display_range,
        });
        self
    }

    #[cfg(feature = "api_bluesky")]
    /// Add a record embed candidate
    pub fn embed_record(
        mut self,
        at_uri: AtUri<'static>,
        strong_ref: Option<StrongRef<'static>>,
    ) -> Self {
        self.embed_candidates
            .get_or_insert_with(Vec::new)
            .push(EmbedCandidate::Record { at_uri, strong_ref });
        self
    }

    #[cfg(feature = "api_bluesky")]
    /// Add an external embed candidate
    pub fn embed_external(
        mut self,
        url: impl Into<CowStr<'static>>,
        metadata: Option<ExternalMetadata<'static>>,
    ) -> Self {
        self.embed_candidates
            .get_or_insert_with(Vec::new)
            .push(EmbedCandidate::External {
                url: url.into(),
                metadata,
            });
        self
    }

    fn find_substring(&self, needle: &str) -> Option<Range<usize>> {
        self.text.find(needle).map(|start| {
            let end = start + needle.len();
            start..end
        })
    }
}

fn detect_markdown_links(text: &str) -> (String, Vec<FacetCandidate>) {
    let mut result = String::with_capacity(text.len());
    let mut facets = Vec::new();
    let mut last_end = 0;
    let mut offset = 0;

    for cap in MARKDOWN_LINK_REGEX.captures_iter(text) {
        let full_match = cap.get(0).unwrap();
        let display_text = cap.get(1).unwrap().as_str();
        let url = cap.get(2).unwrap().as_str();

        // Append text before this match
        result.push_str(&text[last_end..full_match.start()]);

        // Append only the display text (strip markdown syntax)
        let start = result.len() - offset;
        result.push_str(display_text);
        let end = result.len() - offset;

        // Track offset change (we removed the markdown syntax)
        offset += full_match.as_str().len() - display_text.len();

        // Store URL string since it's not in the final text
        facets.push(FacetCandidate::MarkdownLink {
            display_range: start..end,
            url: url.to_string(),
        });

        last_end = full_match.end();
    }

    // Append remaining text
    result.push_str(&text[last_end..]);

    (result, facets)
}

fn detect_mentions(text: &str) -> Vec<FacetCandidate> {
    let mut facets = Vec::new();

    for cap in MENTION_REGEX.captures_iter(text) {
        let handle = cap.get(3).unwrap().as_str();

        if !HANDLE_REGEX.is_match(handle) && !DID_REGEX.is_match(handle) {
            continue;
        }

        let did = if let Ok(did) = Did::new(handle) {
            Some(did.into_static())
        } else {
            None
        };

        // Store range including @ symbol - extract text at build time
        let at_sign = cap.get(2).unwrap();
        let start = at_sign.start();
        let end = cap.get(3).unwrap().end();

        facets.push(FacetCandidate::Mention {
            range: start..end,
            did,
        });
    }

    facets
}

fn detect_urls(text: &str) -> Vec<FacetCandidate> {
    let mut facets = Vec::new();

    for cap in URL_REGEX.captures_iter(text) {
        let url_match = if let Some(full_url) = cap.get(3) {
            full_url
        } else if let Some(_domain) = cap.name("domain") {
            // Bare domain - will prepend https:// at build time
            cap.get(2).unwrap()
        } else {
            continue;
        };

        let url_str = url_match.as_str();

        // Calculate actual end after stripping trailing punctuation
        let trimmed_len = if let Some(trimmed) = TRAILING_PUNCT_REGEX.find(url_str) {
            trimmed.start()
        } else {
            url_str.len()
        };

        if trimmed_len == 0 {
            continue;
        }

        let start = url_match.start();
        let end = start + trimmed_len;

        // Store just the range - normalize URL at build time
        facets.push(FacetCandidate::Link { range: start..end });
    }

    facets
}

fn detect_tags(text: &str) -> Vec<FacetCandidate> {
    let mut facets = Vec::new();

    for cap in TAG_REGEX.captures_iter(text) {
        // capture group 2 is optional, skip if empty (just # with nothing after)
        let tag_match = match cap.get(2) {
            Some(m) => m,
            None => continue,
        };
        let tag_str = tag_match.as_str();

        // Filter out tags starting with emoji modifier (since regex can't do negative lookahead)
        if tag_str.starts_with('\u{fe0f}') {
            continue;
        }

        // Calculate trimmed length after stripping trailing punctuation
        let trimmed_len = if let Some(trimmed) = TRAILING_PUNCT_REGEX.find(tag_str) {
            trimmed.start()
        } else {
            tag_str.len()
        };

        // Validate length (0-64 chars per Bluesky spec)
        if trimmed_len == 0 || trimmed_len > 64 {
            continue;
        }

        let hash_pos = cap.get(0).unwrap().start();
        // Find the actual # character position
        let hash_start = text[hash_pos..]
            .chars()
            .position(|c| c == '#' || c == '#')
            .unwrap();
        let start = hash_pos + hash_start;
        let end = start + 1 + trimmed_len; // # + tag length

        // Store range including # symbol - extract and process at build time
        facets.push(FacetCandidate::Tag { range: start..end });
    }

    facets
}

/// Classifies a URL or at-URI as an embed candidate
#[cfg(feature = "api_bluesky")]
fn classify_embed(url: &str, embed_domains: &[&str]) -> Option<EmbedCandidate<'static>> {
    // Check if it's an at:// URI
    if url.starts_with("at://") {
        if let Ok(at_uri) = AtUri::new(url) {
            return Some(EmbedCandidate::Record {
                at_uri: at_uri.into_static(),
                strong_ref: None,
            });
        }
    }

    // Check if it's an HTTP(S) URL
    if url.starts_with("http://") || url.starts_with("https://") {
        // Try to extract at-uri from configured domain URL patterns
        if let Some(at_uri) = extract_at_uri_from_url(url, embed_domains) {
            return Some(EmbedCandidate::Record {
                at_uri,
                strong_ref: None,
            });
        }

        // Otherwise, it's an external embed
        return Some(EmbedCandidate::External {
            url: CowStr::from(url.to_string()),
            metadata: None,
        });
    }

    None
}

/// Extracts an at-URI from a URL with bsky.app-style path patterns
///
/// Supports these patterns:
/// - https://{domain}/profile/{handle|did}/post/{rkey} → at://{actor}/app.bsky.feed.post/{rkey}
/// - https://{domain}/profile/{handle|did}/lists/{rkey} → at://{actor}/app.bsky.graph.list/{rkey}
/// - https://{domain}/profile/{handle|did}/feed/{rkey} → at://{actor}/app.bsky.feed.generator/{rkey}
/// - https://{domain}/starter-pack/{handle|did}/{rkey} → at://{actor}/app.bsky.graph.starterpack/{rkey}
/// - https://{domain}/profile/{handle|did}/{collection}/{rkey} → at://{actor}/{collection}/{rkey} (if collection looks like NSID)
///
/// Only works for domains in the provided `embed_domains` list.
#[cfg(feature = "api_bluesky")]
pub fn extract_at_uri_from_url(url: &str, embed_domains: &[&str]) -> Option<AtUri<'static>> {
    // Parse URL
    use jacquard_common::deps::fluent_uri::Uri;

    let url_parsed = Uri::parse(url).ok()?;

    // Check if domain is in allowed list
    let domain = url_parsed.authority()?.host();
    if !embed_domains.contains(&domain) {
        return None;
    }

    let path = url_parsed.path().as_str();
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();

    let at_uri_str = match segments.as_slice() {
        // Known shortcuts
        ["profile", actor, "post", rkey] => {
            format!("at://{}/app.bsky.feed.post/{}", actor, rkey)
        }
        ["profile", actor, "lists", rkey] => {
            format!("at://{}/app.bsky.graph.list/{}", actor, rkey)
        }
        ["profile", actor, "feed", rkey] => {
            format!("at://{}/app.bsky.feed.generator/{}", actor, rkey)
        }
        ["starter-pack", actor, rkey] => {
            format!("at://{}/app.bsky.graph.starterpack/{}", actor, rkey)
        }
        // Generic pattern: /profile/{actor}/{collection}/{rkey}
        // Accept if collection looks like it could be an NSID (contains dots)
        ["profile", actor, collection, rkey] if collection.contains('.') => {
            format!("at://{}/{}/{}", actor, collection, rkey)
        }
        _ => return None,
    };

    AtUri::new(&at_uri_str).ok().map(|u| u.into_static())
}

/// Errors that can occur during richtext building
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
#[non_exhaustive]
pub enum RichTextError {
    /// Handle found that needs resolution but no resolver provided
    #[error("Handle '{0}' requires resolution - use build_async() with an IdentityResolver")]
    HandleNeedsResolution(String),

    /// Facets overlap (not allowed by spec)
    #[error("Facets overlap at byte range {0}..{1}")]
    OverlappingFacets(usize, usize),

    /// Identity resolution failed
    #[error("Failed to resolve identity")]
    IdentityResolution(#[from] IdentityError),

    /// Invalid byte range
    #[error("Invalid byte range {start}..{end} for text of length {text_len}")]
    InvalidRange {
        /// Range start position
        start: usize,
        /// Range end position
        end: usize,
        /// Total text length
        text_len: usize,
    },

    /// Invalid AT Protocol string (URI, DID, or Handle)
    #[error("Invalid AT Protocol string")]
    InvalidAtStr(#[from] AtStrError),

    /// Invalid URI
    #[error("Invalid URI")]
    Uri(#[from] UriParseError),
}

#[cfg(feature = "api_bluesky")]
impl RichTextBuilder<Resolved> {
    /// Build the richtext (sync - all facets must be resolved)
    pub fn build(self) -> Result<RichText<'static>, RichTextError> {
        if self.facet_candidates.is_empty() {
            return Ok(RichText {
                text: CowStr::from(self.text),
                facets: None,
            });
        }

        // Sort facets by start position
        let mut candidates = self.facet_candidates;
        candidates.sort_by_key(|fc| match fc {
            FacetCandidate::MarkdownLink { display_range, .. } => display_range.start,
            FacetCandidate::Mention { range, .. } => range.start,
            FacetCandidate::Link { range } => range.start,
            FacetCandidate::Tag { range } => range.start,
        });

        // Check for overlaps and convert to Facet types
        let mut facets = Vec::with_capacity(candidates.len());
        let mut last_end = 0;
        let text_len = self.text.len();

        for candidate in candidates {
            use crate::api::app_bsky::richtext::facet::{
                ByteSlice, FacetFeaturesItem, Link, Mention, Tag,
            };
            use crate::types::uri::UriValue;

            let (range, feature) = match candidate {
                FacetCandidate::MarkdownLink { display_range, url } => {
                    // MarkdownLink stores URL directly, use display_range for index

                    let feature = FacetFeaturesItem::Link(Box::new(Link {
                        uri: UriValue::new_owned(&url)?,
                        extra_data: None,
                    }));
                    (display_range, feature)
                }
                FacetCandidate::Mention { range, did } => {
                    // In Resolved state, DID must be present
                    let did = did.ok_or_else(|| {
                        // Extract handle from text for error message
                        let handle = if range.end <= text_len {
                            self.text[range.clone()].trim_start_matches('@')
                        } else {
                            "<invalid range>"
                        };
                        RichTextError::HandleNeedsResolution(handle.to_string())
                    })?;

                    let feature = FacetFeaturesItem::Mention(Box::new(Mention {
                        did,
                        extra_data: None,
                    }));
                    (range, feature)
                }
                FacetCandidate::Link { range } => {
                    // Extract URL from text[range] and normalize
                    if range.end > text_len {
                        return Err(RichTextError::InvalidRange {
                            start: range.start,
                            end: range.end,
                            text_len,
                        });
                    }

                    let mut url = self.text[range.clone()].to_string();

                    // Prepend https:// if URL doesn't have a scheme
                    if !url.starts_with("http://") && !url.starts_with("https://") {
                        url = format!("https://{}", url);
                    }

                    let feature = FacetFeaturesItem::Link(Box::new(Link {
                        uri: UriValue::new_owned(&url)?,
                        extra_data: None,
                    }));
                    (range, feature)
                }
                FacetCandidate::Tag { range } => {
                    // Extract tag from text[range] (includes #), strip # and trailing punct

                    use smol_str::ToSmolStr;
                    if range.end > text_len {
                        return Err(RichTextError::InvalidRange {
                            start: range.start,
                            end: range.end,
                            text_len,
                        });
                    }

                    let tag_with_hash = &self.text[range.clone()];
                    // Strip # prefix (could be # or #)
                    let tag = tag_with_hash
                        .trim_start_matches('#')
                        .trim_start_matches('#');

                    let feature = FacetFeaturesItem::Tag(Box::new(Tag {
                        tag: CowStr::from(tag.to_smolstr()),
                        extra_data: None,
                    }));
                    (range, feature)
                }
            };

            // Check overlap
            if range.start < last_end {
                return Err(RichTextError::OverlappingFacets(range.start, range.end));
            }

            // Validate range
            if range.end > text_len {
                return Err(RichTextError::InvalidRange {
                    start: range.start,
                    end: range.end,
                    text_len,
                });
            }

            facets.push(Facet {
                index: ByteSlice {
                    byte_start: range.start as i64,
                    byte_end: range.end as i64,
                    extra_data: None,
                },
                features: vec![feature],
                extra_data: None,
            });

            last_end = range.end;
        }

        Ok(RichText {
            text: CowStr::from(self.text),
            facets: Some(facets.into_static()),
        })
    }
}

#[cfg(feature = "api_bluesky")]
impl RichTextBuilder<Unresolved> {
    /// Build richtext, resolving handles to DIDs using the provided resolver
    pub async fn build_async<R>(self, resolver: &R) -> Result<RichText<'static>, RichTextError>
    where
        R: IdentityResolver + Sync,
    {
        use crate::api::app_bsky::richtext::facet::{
            ByteSlice, FacetFeaturesItem, Link, Mention, Tag,
        };

        if self.facet_candidates.is_empty() {
            return Ok(RichText {
                text: CowStr::from(self.text),
                facets: None,
            });
        }

        // Sort facets by start position
        let mut candidates = self.facet_candidates;
        candidates.sort_by_key(|fc| match fc {
            FacetCandidate::MarkdownLink { display_range, .. } => display_range.start,
            FacetCandidate::Mention { range, .. } => range.start,
            FacetCandidate::Link { range } => range.start,
            FacetCandidate::Tag { range } => range.start,
        });

        // Resolve handles and convert to Facet types
        let mut facets = Vec::with_capacity(candidates.len());
        let mut last_end = 0;
        let text_len = self.text.len();

        for candidate in candidates {
            let (range, feature) = match candidate {
                FacetCandidate::MarkdownLink { display_range, url } => {
                    // MarkdownLink stores URL directly, use display_range for index

                    let feature = FacetFeaturesItem::Link(Box::new(Link {
                        uri: crate::types::uri::UriValue::new_owned(&url)?,
                        extra_data: None,
                    }));
                    (display_range, feature)
                }
                FacetCandidate::Mention { range, did } => {
                    let did = if let Some(did) = did {
                        // Already resolved
                        did
                    } else {
                        // Extract handle from text and resolve
                        if range.end > text_len {
                            return Err(RichTextError::InvalidRange {
                                start: range.start,
                                end: range.end,
                                text_len,
                            });
                        }

                        let handle_str = self.text[range.clone()].trim_start_matches('@');
                        let handle = jacquard_common::types::handle::Handle::new(handle_str)?;

                        resolver.resolve_handle(&handle).await?
                    };

                    let feature = FacetFeaturesItem::Mention(Box::new(Mention {
                        did,
                        extra_data: None,
                    }));
                    (range, feature)
                }
                FacetCandidate::Link { range } => {
                    // Extract URL from text[range] and normalize

                    if range.end > text_len {
                        return Err(RichTextError::InvalidRange {
                            start: range.start,
                            end: range.end,
                            text_len,
                        });
                    }

                    let mut url = self.text[range.clone()].to_string();

                    // Prepend https:// if URL doesn't have a scheme
                    if !url.starts_with("http://") && !url.starts_with("https://") {
                        url = format!("https://{}", url);
                    }

                    let feature = FacetFeaturesItem::Link(Box::new(Link {
                        uri: crate::types::uri::UriValue::new_owned(&url)?,
                        extra_data: None,
                    }));
                    (range, feature)
                }
                FacetCandidate::Tag { range } => {
                    // Extract tag from text[range] (includes #), strip # and trailing punct

                    use smol_str::ToSmolStr;
                    if range.end > text_len {
                        return Err(RichTextError::InvalidRange {
                            start: range.start,
                            end: range.end,
                            text_len,
                        });
                    }

                    let tag_with_hash = &self.text[range.clone()];
                    // Strip # prefix (could be # or #)
                    let tag = tag_with_hash
                        .trim_start_matches('#')
                        .trim_start_matches('#');

                    let feature = FacetFeaturesItem::Tag(Box::new(Tag {
                        tag: CowStr::from(tag.to_smolstr()),
                        extra_data: None,
                    }));
                    (range, feature)
                }
            };

            // Check overlap
            if range.start < last_end {
                return Err(RichTextError::OverlappingFacets(range.start, range.end));
            }

            // Validate range
            if range.end > text_len {
                return Err(RichTextError::InvalidRange {
                    start: range.start,
                    end: range.end,
                    text_len,
                });
            }

            facets.push(Facet {
                index: ByteSlice {
                    byte_start: range.start as i64,
                    byte_end: range.end as i64,
                    extra_data: None,
                },
                features: vec![feature],
                extra_data: None,
            });

            last_end = range.end;
        }

        Ok(RichText {
            text: CowStr::from(self.text),
            facets: Some(facets.into_static()),
        })
    }

    /// Build richtext with embed resolution using HttpClient
    ///
    /// This resolves handles to DIDs and fetches OpenGraph metadata for external links.
    pub async fn build_with_embeds_async<C>(
        mut self,
        client: &C,
    ) -> Result<(RichText<'static>, Option<Vec<EmbedCandidate<'static>>>), RichTextError>
    where
        C: HttpClient + IdentityResolver + Sync,
    {
        // Extract embed candidates
        let embed_candidates = self.embed_candidates.take().unwrap_or_default();

        // Build facets (resolves handles)
        let richtext = self.build_async(client).await?;

        // Now resolve embed candidates
        let mut resolved_embeds = Vec::new();

        for candidate in embed_candidates {
            match candidate {
                EmbedCandidate::Record { at_uri, strong_ref } => {
                    // TODO: could fetch the record to get CID for strong_ref
                    // For now, just pass through
                    resolved_embeds.push(EmbedCandidate::Record { at_uri, strong_ref });
                }
                EmbedCandidate::External {
                    url,
                    metadata: None,
                } => {
                    // Fetch OpenGraph metadata
                    match fetch_opengraph_metadata(client, &url).await {
                        Ok(Some(metadata)) => {
                            resolved_embeds.push(EmbedCandidate::External {
                                url,
                                metadata: Some(metadata),
                            });
                        }
                        Ok(None) | Err(_) => {
                            // If we fail to fetch metadata, include embed without metadata
                            resolved_embeds.push(EmbedCandidate::External {
                                url,
                                metadata: None,
                            });
                        }
                    }
                }
                other => resolved_embeds.push(other),
            }
        }

        Ok((richtext, Some(resolved_embeds).filter(|v| !v.is_empty())))
    }
}

/// Fetch OpenGraph metadata from a URL using the webpage crate
#[cfg(feature = "api_bluesky")]
pub async fn fetch_opengraph_metadata<C>(
    client: &C,
    url: &str,
) -> Result<Option<ExternalMetadata<'static>>, Box<dyn std::error::Error + Send + Sync>>
where
    C: HttpClient,
{
    // Build HTTP GET request
    let request = http::Request::builder()
        .method("GET")
        .uri(url)
        .header("User-Agent", "jacquard/0.8")
        .body(Vec::new())?;

    // Fetch the page
    let response = client.send_http(request).await?;

    // Parse HTML body
    let html = String::from_utf8_lossy(response.body());

    // Use webpage crate to extract OpenGraph metadata
    let info = webpage::HTML::from_string(html.to_string(), Some(url.to_string()))
        .ok()
        .map(|html| html.opengraph);

    if let Some(og) = info {
        // Extract title, description, and thumbnail

        use jacquard_common::cowstr::ToCowStr;
        let title = og.properties.get("title").map(|s| s.to_cowstr());

        let description = og.properties.get("description").map(|s| s.to_cowstr());

        let thumbnail = og.images.first().map(|img| CowStr::from(img.url.clone()));

        // Only return metadata if we have at least a title
        if let Some(title) = title {
            return Ok(Some(ExternalMetadata {
                title: title.into_static(),
                description: description
                    .unwrap_or_else(|| CowStr::new_static(""))
                    .into_static(),
                thumbnail: thumbnail.into_static(),
            }));
        }
    }

    Ok(None)
}

#[cfg(test)]
mod tests;