ebook-rs 0.16.4

Pure Rust multi-format eBook engine (EPUB 2/3, MOBI, AZW3, KFX, FB2, LIT, CBZ, PDF, ODT, DOCX, RTF, TXT, MD) featuring Mozilla UniFFI, Readium CFI/LCP, SpeechSynthesis TTS sync, CJK vertical/RTL reflow, EPUB3 optimizer, AI RAG BM25 chunking, zero-copy search, Zstd caching, Python/WASM bindings, and native MCP server.
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
use serde::{Deserialize, Serialize};

/// A parsed EPUB Canonical Fragment Identifier (CFI).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Cfi {
    pub raw: String,
    pub path: CfiPath,
    pub range_start: Option<CfiPath>,
    pub range_end: Option<CfiPath>,
}

/// DOM Element target resolved from CFI element steps and ID assertions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CfiDomTarget {
    pub element_id: Option<String>,
    pub css_selector: String,
    pub char_offset: usize,
}

/// A path component inside a CFI.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CfiPath {
    pub steps: Vec<CfiStep>,
    pub offset: Option<CfiOffset>,
}

/// A single step in a CFI path (e.g. /6/4[chap01ref]!).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CfiStep {
    pub index: usize,
    pub indirection: bool,
    pub element_id: Option<String>,
}

/// Character or temporal offset at the end of a CFI path.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CfiOffset {
    Character(usize),
    Temporal(f64),
    Spatial(f64, f64),
}

impl Cfi {
    /// Parse a CFI string representation into a structured `Cfi`.
    pub fn parse(cfi_str: &str) -> Result<Self, String> {
        let clean = cfi_str.trim();
        let payload = if clean.starts_with("epubcfi(") && clean.ends_with(')') {
            &clean[8..clean.len() - 1]
        } else {
            clean
        };

        if let Some(parts) = split_cfi_range(payload) {
            // Range CFI: /6/2!/4/2/1, :10, :45
            let parent_str = parts[0];
            let start_str = parts[1];
            let end_str = parts[2];

            let parent_path = parse_single_path(parent_str)?;
            let mut start_path = parse_single_path(start_str)?;
            let mut end_path = parse_single_path(end_str)?;

            // Combine parent steps into range endpoints
            let mut full_start_steps = parent_path.steps.clone();
            full_start_steps.append(&mut start_path.steps);
            let combined_start = CfiPath {
                steps: full_start_steps,
                offset: start_path.offset,
            };

            let mut full_end_steps = parent_path.steps.clone();
            full_end_steps.append(&mut end_path.steps);
            let combined_end = CfiPath {
                steps: full_end_steps,
                offset: end_path.offset,
            };

            Ok(Self {
                raw: cfi_str.to_string(),
                path: combined_start.clone(),
                range_start: Some(combined_start),
                range_end: Some(combined_end),
            })
        } else {
            let path = parse_single_path(payload)?;
            Ok(Self {
                raw: cfi_str.to_string(),
                path,
                range_start: None,
                range_end: None,
            })
        }
    }

    /// Helper constructor: Create a simple CFI pointing to a spine index and character offset.
    /// B5 Fix: Support optional element_id assertion to preserve CFI id assertions on roundtrip.
    pub fn from_spine_index(
        spine_index: usize,
        element_id: Option<&str>,
        char_offset: usize,
    ) -> Self {
        let spine_step_idx = (spine_index + 1) * 2;
        let steps = vec![
            CfiStep {
                index: 6,
                indirection: false,
                element_id: None,
            },
            CfiStep {
                index: spine_step_idx,
                indirection: true,
                element_id: element_id.map(|s| s.to_string()),
            },
            CfiStep {
                index: 4,
                indirection: false,
                element_id: None,
            },
            CfiStep {
                index: 2,
                indirection: false,
                element_id: None,
            },
            CfiStep {
                index: 1,
                indirection: false,
                element_id: None,
            },
        ];

        let id_str = element_id.map(|s| format!("[{}]", s)).unwrap_or_default();
        let raw = format!(
            "epubcfi(/6/{}{}!/4/2/1:{})",
            spine_step_idx, id_str, char_offset
        );
        let path = CfiPath {
            steps: steps.clone(),
            offset: Some(CfiOffset::Character(char_offset)),
        };

        Self {
            raw,
            path,
            range_start: None,
            range_end: None,
        }
    }

    /// Extract the 0-based spine item index from this CFI, returning an error if no indirection step `!` is found (B5 Fix).
    pub fn try_spine_index(&self) -> Result<usize, String> {
        for step in &self.path.steps {
            if step.indirection && step.index >= 2 {
                return Ok((step.index / 2) - 1);
            }
        }
        Err("CFI missing indirection step ('!')".to_string())
    }

    /// Extract the 0-based spine item index from this CFI (defaults to 0 if missing indirection).
    pub fn spine_index(&self) -> usize {
        self.try_spine_index().unwrap_or(0)
    }

    /// Extract character offset.
    pub fn char_offset(&self) -> usize {
        match self.path.offset {
            Some(CfiOffset::Character(off)) => off,
            _ => 0,
        }
    }

    /// Compare two CFIs by spine index and character offset.
    pub fn compare(&self, other: &Self) -> std::cmp::Ordering {
        let s1 = self.spine_index();
        let s2 = other.spine_index();
        if s1 != s2 {
            return s1.cmp(&s2);
        }
        let o1 = self.char_offset();
        let o2 = other.char_offset();
        o1.cmp(&o2)
    }

    /// Resolve IDPF element steps and assertion IDs into CSS DOM selectors and target element IDs (F1 Fix).
    pub fn resolve_dom_path(&self, html: &str) -> Option<CfiDomTarget> {
        let mut element_id = None;
        let mut selectors = Vec::new();

        for step in &self.path.steps {
            if let Some(id) = &step.element_id {
                element_id = Some(id.clone());
                selectors.push(format!("#{}", id));
            } else if !step.indirection && step.index >= 2 {
                let child_num = step.index / 2;
                selectors.push(format!("*:nth-child({})", child_num));
            }
        }

        // Prune selectors prior to the last ID anchor if present
        if let Some(id_idx) = selectors.iter().rposition(|s| s.starts_with('#')) {
            selectors = selectors[id_idx..].to_vec();
        }

        let css_selector = if selectors.is_empty() {
            "body".to_string()
        } else {
            selectors.join(" > ")
        };

        // Check if element_id exists in target HTML
        if element_id.is_none() {
            let lower_html = html.to_lowercase();
            for step in &self.path.steps {
                if let Some(id) = &step.element_id {
                    let id_lower = id.to_lowercase();
                    if lower_html.contains(&format!("id=\"{}\"", id_lower))
                        || lower_html.contains(&format!("id='{}'", id_lower))
                    {
                        element_id = Some(id.clone());
                        break;
                    }
                }
            }
        }

        Some(CfiDomTarget {
            element_id,
            css_selector,
            char_offset: self.char_offset(),
        })
    }

    /// Convert back to formatted `epubcfi(...)` string.
    pub fn to_cfi_string(&self) -> String {
        format!("epubcfi({})", format_path(&self.path))
    }
}

impl std::fmt::Display for Cfi {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "epubcfi({})", format_path(&self.path))
    }
}

fn parse_single_path(s: &str) -> Result<CfiPath, String> {
    let mut steps = Vec::new();
    let mut offset = None;

    let mut chars = s.chars().peekable();
    let mut current_num = String::new();
    let mut indirection;

    while let Some(&ch) = chars.peek() {
        if ch == '/' {
            chars.next();
            current_num.clear();
            while let Some(&c) = chars.peek() {
                if c.is_ascii_digit() {
                    current_num.push(c);
                    chars.next();
                } else {
                    break;
                }
            }

            if !current_num.is_empty() {
                let idx: usize = current_num.parse().unwrap_or(0);

                // Check for element_id assertion [id]
                let mut element_id = None;
                if let Some(&'[') = chars.peek() {
                    chars.next();
                    let mut id_str = String::new();
                    let mut escaped = false;
                    while let Some(&c) = chars.peek() {
                        if escaped {
                            id_str.push(c);
                            chars.next();
                            escaped = false;
                            continue;
                        }
                        if c == '^' {
                            escaped = true;
                            chars.next();
                            continue;
                        }
                        if c == ']' {
                            chars.next();
                            break;
                        }
                        id_str.push(c);
                        chars.next();
                    }
                    element_id = Some(id_str);
                }

                // Check for indirection !
                if let Some(&'!') = chars.peek() {
                    indirection = true;
                    chars.next();
                } else {
                    indirection = false;
                }

                steps.push(CfiStep {
                    index: idx,
                    indirection,
                    element_id,
                });
            }
        } else if ch == ':' {
            chars.next();
            let mut off_num = String::new();
            while let Some(&c) = chars.peek() {
                if c.is_ascii_digit() {
                    off_num.push(c);
                    chars.next();
                } else {
                    break;
                }
            }
            if let Ok(off) = off_num.parse::<usize>() {
                offset = Some(CfiOffset::Character(off));
            }
        } else {
            chars.next();
        }
    }

    Ok(CfiPath { steps, offset })
}

fn split_cfi_range(payload: &str) -> Option<Vec<&str>> {
    let mut parts = Vec::new();
    let mut in_bracket = false;
    let mut escaped = false;
    let mut last_idx = 0;

    for (idx, c) in payload.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        match c {
            '^' => escaped = true,
            '[' => in_bracket = true,
            ']' => in_bracket = false,
            ',' if !in_bracket => {
                parts.push(&payload[last_idx..idx]);
                last_idx = idx + 1;
            }
            _ => {}
        }
    }
    if parts.is_empty() {
        None
    } else {
        parts.push(&payload[last_idx..]);
        if parts.len() >= 3 { Some(parts) } else { None }
    }
}

fn format_path(path: &CfiPath) -> String {
    let mut out = String::new();
    for step in &path.steps {
        out.push_str(&format!("/{}", step.index));
        if let Some(ref id) = step.element_id {
            out.push('[');
            for c in id.chars() {
                if matches!(c, '^' | '[' | ']' | '(' | ')' | ',' | ';' | '!') {
                    out.push('^');
                }
                out.push(c);
            }
            out.push(']');
        }
        if step.indirection {
            out.push('!');
        }
    }
    if let Some(CfiOffset::Character(off)) = path.offset {
        out.push_str(&format!(":{}", off));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cfi_parsing_and_formatting() {
        let cfi_str = "epubcfi(/6/4[chap01ref]!/4/2/10/1:42)";
        let cfi = Cfi::parse(cfi_str).unwrap();

        assert_eq!(cfi.spine_index(), 1);
        assert_eq!(cfi.char_offset(), 42);
        assert_eq!(cfi.to_string(), cfi_str);
    }

    #[test]
    fn test_cfi_with_comma_in_id() {
        let cfi_str = "epubcfi(/6/4[chap01,heading]!/4/2:10)";
        let cfi = Cfi::parse(cfi_str).expect("CFI with comma in ID should parse as single path");
        assert_eq!(cfi.spine_index(), 1);
        assert_eq!(cfi.char_offset(), 10);
        assert!(cfi.range_start.is_none());
    }
}