cf-file-parser 0.1.25

File Parser module
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
use modkit_macros::domain_model;

use crate::domain::ir::{ParsedBlock, ParsedDocument};

/// Markdown renderer that converts `ParsedDocument` to Markdown string
#[domain_model]
pub struct MarkdownRenderer;

impl Default for MarkdownRenderer {
    fn default() -> Self {
        Self::new()
    }
}

/// Iterator over Markdown chunks from a `ParsedDocument`
/// This iterator owns the document to avoid lifetime issues with async streaming
#[domain_model]
pub struct MarkdownRenderIter {
    doc: ParsedDocument,
    header_emitted: bool,
    block_index: usize,
}

impl Iterator for MarkdownRenderIter {
    type Item = String;

    fn next(&mut self) -> Option<Self::Item> {
        // First emit header chunk if not yet emitted
        if !self.header_emitted {
            self.header_emitted = true;
            let header = Self::render_header(&self.doc);
            if !header.is_empty() {
                return Some(header);
            }
        }

        // Then emit one chunk per block
        if self.block_index < self.doc.blocks.len() {
            let block = &self.doc.blocks[self.block_index];
            self.block_index += 1;
            let mut chunk = String::new();
            MarkdownRenderer::render_block(block, &mut chunk);
            Some(chunk)
        } else {
            None
        }
    }
}

impl MarkdownRenderIter {
    /// Render the header chunk (title + metadata)
    fn render_header(doc: &ParsedDocument) -> String {
        let mut header = String::new();

        // Render title if present
        if let Some(ref title) = doc.title {
            header.push_str("# ");
            header.push_str(title);
            header.push_str("\n\n");
        }

        // Render metadata section if we have useful info
        if doc.language.is_some()
            || doc.meta.original_filename.is_some()
            || doc.meta.content_type.is_some()
        {
            use std::fmt::Write;
            header.push_str("---\n");
            if let Some(ref lang) = doc.language {
                _ = writeln!(header, "language: {lang}");
            }
            if let Some(ref filename) = doc.meta.original_filename {
                _ = writeln!(header, "filename: {filename}");
            }
            if let Some(ref content_type) = doc.meta.content_type {
                _ = writeln!(header, "content-type: {content_type}");
            }
            header.push_str("---\n\n");
        }

        header
    }
}

impl MarkdownRenderer {
    /// Create a new markdown renderer
    #[must_use]
    pub fn new() -> Self {
        Self
    }

    /// Render a document using this renderer instance
    #[must_use]
    pub fn render_doc(doc: &ParsedDocument) -> String {
        Self::render(doc)
    }

    /// Create a streaming iterator over Markdown chunks
    /// Takes ownership of the document to avoid lifetime issues with async streaming
    #[must_use]
    pub fn render_iter(doc: ParsedDocument) -> MarkdownRenderIter {
        MarkdownRenderIter {
            doc,
            header_emitted: false,
            block_index: 0,
        }
    }

    /// Create a streaming iterator over Markdown chunks from a borrowed document
    /// This is a convenience method for when you don't need to move the document
    #[must_use]
    pub fn render_iter_ref(doc: &ParsedDocument) -> MarkdownRenderIter {
        MarkdownRenderIter {
            doc: doc.clone(),
            header_emitted: false,
            block_index: 0,
        }
    }

    /// Render a parsed document to Markdown (static method)
    /// Collects all chunks from the streaming iterator
    #[must_use]
    pub fn render(doc: &ParsedDocument) -> String {
        let mut output = String::new();
        for chunk in Self::render_iter_ref(doc) {
            output.push_str(&chunk);
        }
        output
    }

    fn render_block(block: &ParsedBlock, output: &mut String) {
        match block {
            ParsedBlock::Heading { level, inlines } => {
                let level = (*level).clamp(1, 6);
                output.push_str(&"#".repeat(level as usize));
                output.push(' ');
                Self::render_inlines(inlines, output);
                output.push_str("\n\n");
            }
            ParsedBlock::Paragraph { inlines } => {
                Self::render_inlines(inlines, output);
                output.push_str("\n\n");
            }
            ParsedBlock::ListItem {
                level,
                ordered,
                blocks,
            } => {
                // Add indentation
                let indent = "  ".repeat(*level as usize);
                output.push_str(&indent);

                // Add bullet or number
                if *ordered {
                    output.push_str("1. ");
                } else {
                    output.push_str("- ");
                }

                // Render blocks within list item
                for (idx, block) in blocks.iter().enumerate() {
                    if idx > 0 {
                        output.push_str(&indent);
                        output.push_str("   "); // Extra indent for continuation
                    }

                    let mut block_output = String::new();
                    Self::render_block(block, &mut block_output);
                    // Remove trailing double newlines from nested blocks
                    let block_text = block_output.trim_end();
                    output.push_str(block_text);

                    if idx < blocks.len() - 1 {
                        output.push('\n');
                    }
                }

                output.push('\n');
            }
            ParsedBlock::CodeBlock { language, code } => {
                output.push_str("```");
                if let Some(lang) = language {
                    output.push_str(lang);
                }
                output.push('\n');
                output.push_str(code);
                if !code.ends_with('\n') {
                    output.push('\n');
                }
                output.push_str("```\n\n");
            }
            ParsedBlock::Table(table_block) => {
                Self::render_table(table_block, output);
                output.push_str("\n\n");
            }
            ParsedBlock::Quote { blocks } => {
                let mut quote_content = String::new();
                for block in blocks {
                    Self::render_block(block, &mut quote_content);
                }

                // Prefix each line with "> "
                for line in quote_content.lines() {
                    output.push_str("> ");
                    output.push_str(line);
                    output.push('\n');
                }
                output.push('\n');
            }
            ParsedBlock::HorizontalRule => {
                output.push_str("---\n\n");
            }
            ParsedBlock::Image { alt, title, src } => {
                output.push('!');
                output.push('[');
                if let Some(alt_text) = alt {
                    output.push_str(alt_text);
                }
                output.push(']');
                output.push('(');
                if let Some(source) = src {
                    output.push_str(source);
                }
                if let Some(title_text) = title {
                    output.push_str(" \"");
                    output.push_str(title_text);
                    output.push('"');
                }
                output.push(')');
                output.push_str("\n\n");
            }
            ParsedBlock::PageBreak => {
                output.push_str("\n\n---\n\n");
            }
        }
    }

    fn render_inlines(inlines: &[crate::domain::ir::Inline], output: &mut String) {
        use crate::domain::ir::Inline;

        for inline in inlines {
            match inline {
                Inline::Text { text, style } => {
                    Self::render_styled_text(text, style, output);
                }
                Inline::Link {
                    text,
                    target,
                    style,
                } => {
                    output.push('[');
                    Self::render_styled_text(text, style, output);
                    output.push_str("](");
                    output.push_str(target);
                    output.push(')');
                }
                Inline::Code { text, style } => {
                    // Code inline takes precedence, then apply other styles
                    output.push('`');
                    Self::render_styled_text(text, style, output);
                    output.push('`');
                }
            }
        }
    }

    fn render_styled_text(text: &str, style: &crate::domain::ir::InlineStyle, output: &mut String) {
        let mut wrapped = text.to_owned();

        // Apply styles in order: code, bold, italic, underline, strike
        // Note: code is handled by Inline::Code variant, not here

        if style.strike {
            wrapped = format!("~~{wrapped}~~");
        }

        if style.underline {
            wrapped = format!("__{wrapped}__");
        }

        if style.italic {
            wrapped = format!("*{wrapped}*");
        }

        if style.bold {
            wrapped = format!("**{wrapped}**");
        }

        if style.code {
            wrapped = format!("`{wrapped}`");
        }

        output.push_str(&wrapped);
    }

    fn render_table(table: &crate::domain::ir::TableBlock, output: &mut String) {
        if table.rows.is_empty() {
            return;
        }

        // Determine number of columns from first row
        let num_cols = table.rows[0].cells.len();

        // Check if we have a header row
        let has_header = table.rows.first().is_some_and(|r| r.is_header);

        let (header_row, data_rows) = if has_header {
            (&table.rows[0], &table.rows[1..])
        } else {
            // Create synthetic header if needed
            let first_row = &table.rows[0];
            (first_row, &table.rows[..])
        };

        // Render header row
        Self::render_table_row(header_row, num_cols, output);
        output.push('\n');

        // Render separator row
        output.push('|');
        for _ in 0..num_cols {
            output.push_str(" --- |");
        }
        output.push('\n');

        // Render data rows
        for row in data_rows {
            Self::render_table_row(row, num_cols, output);
            output.push('\n');
        }
    }

    fn render_table_row(row: &crate::domain::ir::TableRow, num_cols: usize, output: &mut String) {
        output.push('|');

        for i in 0..num_cols {
            output.push(' ');

            if let Some(cell) = row.cells.get(i) {
                let cell_content = Self::render_cell_content(&cell.blocks);
                // Escape pipes and backslashes in cell content
                let escaped = Self::escape_table_content(&cell_content);
                output.push_str(&escaped);
            }

            output.push_str(" |");
        }
    }

    fn render_cell_content(blocks: &[ParsedBlock]) -> String {
        let mut content = String::new();

        for (idx, block) in blocks.iter().enumerate() {
            if idx > 0 {
                content.push_str("<br/>");
            }

            let mut block_output = String::new();
            Self::render_block(block, &mut block_output);

            // Remove trailing whitespace and newlines for cell content
            let trimmed = block_output.trim();
            content.push_str(trimmed);
        }

        content
    }

    fn escape_table_content(text: &str) -> String {
        text.replace('\\', "\\\\").replace('|', "\\|")
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;
    use crate::domain::ir::{
        Inline, InlineStyle, ParsedMetadata, ParsedSource, TableBlock, TableCell, TableRow,
    };

    #[test]
    fn test_render_heading() {
        let doc = ParsedDocument {
            id: None,
            title: None,
            language: None,
            meta: ParsedMetadata {
                source: ParsedSource::LocalPath("test.txt".to_owned()),
                original_filename: None,
                content_type: None,
                created_at: None,
                modified_at: None,
                is_stub: false,
            },
            blocks: vec![
                ParsedBlock::Heading {
                    level: 1,
                    inlines: vec![Inline::plain("Title")],
                },
                ParsedBlock::Heading {
                    level: 2,
                    inlines: vec![Inline::plain("Subtitle")],
                },
            ],
        };

        let markdown = MarkdownRenderer::render(&doc);
        assert!(markdown.contains("# Title\n"));
        assert!(markdown.contains("## Subtitle\n"));
    }

    #[test]
    fn test_render_paragraph() {
        let doc = ParsedDocument {
            id: None,
            title: None,
            language: None,
            meta: ParsedMetadata {
                source: ParsedSource::LocalPath("test.txt".to_owned()),
                original_filename: None,
                content_type: None,
                created_at: None,
                modified_at: None,
                is_stub: false,
            },
            blocks: vec![ParsedBlock::Paragraph {
                inlines: vec![Inline::plain("Hello world")],
            }],
        };

        let markdown = MarkdownRenderer::render(&doc);
        assert!(markdown.contains("Hello world\n"));
    }

    #[test]
    fn test_render_styled_text() {
        let style = InlineStyle {
            bold: true,
            italic: true,
            ..Default::default()
        };

        let doc = ParsedDocument {
            id: None,
            title: None,
            language: None,
            meta: ParsedMetadata {
                source: ParsedSource::LocalPath("test.txt".to_owned()),
                original_filename: None,
                content_type: None,
                created_at: None,
                modified_at: None,
                is_stub: false,
            },
            blocks: vec![ParsedBlock::Paragraph {
                inlines: vec![Inline::styled("Bold and italic", style)],
            }],
        };

        let markdown = MarkdownRenderer::render(&doc);
        assert!(markdown.contains("**") && markdown.contains('*'));
    }

    #[test]
    fn test_render_list() {
        let doc = ParsedDocument {
            id: None,
            title: None,
            language: None,
            meta: ParsedMetadata {
                source: ParsedSource::LocalPath("test.txt".to_owned()),
                original_filename: None,
                content_type: None,
                created_at: None,
                modified_at: None,
                is_stub: false,
            },
            blocks: vec![
                ParsedBlock::ListItem {
                    level: 0,
                    ordered: false,
                    blocks: vec![ParsedBlock::Paragraph {
                        inlines: vec![Inline::plain("Item 1")],
                    }],
                },
                ParsedBlock::ListItem {
                    level: 1,
                    ordered: false,
                    blocks: vec![ParsedBlock::Paragraph {
                        inlines: vec![Inline::plain("Nested item")],
                    }],
                },
            ],
        };

        let markdown = MarkdownRenderer::render(&doc);
        assert!(markdown.contains("- Item 1\n"));
        assert!(markdown.contains("  - Nested item\n"));
    }

    #[test]
    fn test_render_code_block() {
        let doc = ParsedDocument {
            id: None,
            title: None,
            language: None,
            meta: ParsedMetadata {
                source: ParsedSource::LocalPath("test.txt".to_owned()),
                original_filename: None,
                content_type: None,
                created_at: None,
                modified_at: None,
                is_stub: false,
            },
            blocks: vec![ParsedBlock::CodeBlock {
                language: Some("rust".to_owned()),
                code: "fn main() {\n    println!(\"Hello\");\n}".to_owned(),
            }],
        };

        let markdown = MarkdownRenderer::render(&doc);
        assert!(markdown.contains("```rust\n"));
        assert!(markdown.contains("fn main()"));
    }

    #[test]
    fn test_render_simple_table() {
        let table = TableBlock {
            rows: vec![
                TableRow {
                    is_header: true,
                    cells: vec![
                        TableCell {
                            blocks: vec![ParsedBlock::Paragraph {
                                inlines: vec![Inline::plain("Name")],
                            }],
                        },
                        TableCell {
                            blocks: vec![ParsedBlock::Paragraph {
                                inlines: vec![Inline::plain("Age")],
                            }],
                        },
                    ],
                },
                TableRow {
                    is_header: false,
                    cells: vec![
                        TableCell {
                            blocks: vec![ParsedBlock::Paragraph {
                                inlines: vec![Inline::plain("Alice")],
                            }],
                        },
                        TableCell {
                            blocks: vec![ParsedBlock::Paragraph {
                                inlines: vec![Inline::plain("30")],
                            }],
                        },
                    ],
                },
            ],
        };

        let doc = ParsedDocument {
            id: None,
            title: None,
            language: None,
            meta: ParsedMetadata {
                source: ParsedSource::LocalPath("test.txt".to_owned()),
                original_filename: None,
                content_type: None,
                created_at: None,
                modified_at: None,
                is_stub: false,
            },
            blocks: vec![ParsedBlock::Table(table)],
        };

        let markdown = MarkdownRenderer::render(&doc);
        assert!(markdown.contains("| Name |"));
        assert!(markdown.contains("| Age |"));
        assert!(markdown.contains("| --- |"));
        assert!(markdown.contains("| Alice |"));
    }

    #[test]
    fn test_render_table_with_escaped_content() {
        let table = TableBlock {
            rows: vec![
                TableRow {
                    is_header: true,
                    cells: vec![TableCell {
                        blocks: vec![ParsedBlock::Paragraph {
                            inlines: vec![Inline::plain("Column")],
                        }],
                    }],
                },
                TableRow {
                    is_header: false,
                    cells: vec![TableCell {
                        blocks: vec![ParsedBlock::Paragraph {
                            inlines: vec![Inline::plain("Pipe|test")],
                        }],
                    }],
                },
                TableRow {
                    is_header: false,
                    cells: vec![TableCell {
                        blocks: vec![ParsedBlock::Paragraph {
                            inlines: vec![Inline::plain("Backslash\\test")],
                        }],
                    }],
                },
            ],
        };

        let doc = ParsedDocument {
            id: None,
            title: None,
            language: None,
            meta: ParsedMetadata {
                source: ParsedSource::LocalPath("test.txt".to_owned()),
                original_filename: None,
                content_type: None,
                created_at: None,
                modified_at: None,
                is_stub: false,
            },
            blocks: vec![ParsedBlock::Table(table)],
        };

        let markdown = MarkdownRenderer::render(&doc);
        // Pipes and backslashes should be escaped
        assert!(markdown.contains("Pipe\\|test"));
        assert!(markdown.contains("Backslash\\\\test"));
    }

    #[test]
    fn test_render_nested_table() {
        let inner_table = TableBlock {
            rows: vec![
                TableRow {
                    is_header: true,
                    cells: vec![TableCell {
                        blocks: vec![ParsedBlock::Paragraph {
                            inlines: vec![Inline::plain("Inner")],
                        }],
                    }],
                },
                TableRow {
                    is_header: false,
                    cells: vec![TableCell {
                        blocks: vec![ParsedBlock::Paragraph {
                            inlines: vec![Inline::plain("Data")],
                        }],
                    }],
                },
            ],
        };

        let outer_table = TableBlock {
            rows: vec![
                TableRow {
                    is_header: true,
                    cells: vec![TableCell {
                        blocks: vec![ParsedBlock::Paragraph {
                            inlines: vec![Inline::plain("Outer")],
                        }],
                    }],
                },
                TableRow {
                    is_header: false,
                    cells: vec![TableCell {
                        blocks: vec![ParsedBlock::Table(inner_table)],
                    }],
                },
            ],
        };

        let doc = ParsedDocument {
            id: None,
            title: None,
            language: None,
            meta: ParsedMetadata {
                source: ParsedSource::LocalPath("test.txt".to_owned()),
                original_filename: None,
                content_type: None,
                created_at: None,
                modified_at: None,
                is_stub: false,
            },
            blocks: vec![ParsedBlock::Table(outer_table)],
        };

        let markdown = MarkdownRenderer::render(&doc);
        // Should contain both tables rendered
        assert!(markdown.contains("Outer"));
        assert!(markdown.contains("Inner"));
    }

    #[test]
    fn test_render_with_title() {
        let doc = ParsedDocument {
            id: None,
            title: Some("Document Title".to_owned()),
            language: None,
            meta: ParsedMetadata {
                source: ParsedSource::LocalPath("test.txt".to_owned()),
                original_filename: None,
                content_type: None,
                created_at: None,
                modified_at: None,
                is_stub: false,
            },
            blocks: vec![ParsedBlock::Paragraph {
                inlines: vec![Inline::plain("Content")],
            }],
        };

        let markdown = MarkdownRenderer::render(&doc);
        assert!(markdown.starts_with("# Document Title\n"));
    }

    #[test]
    fn test_render_iter_streaming() {
        let doc = ParsedDocument {
            id: None,
            title: Some("Test Title".to_owned()),
            language: Some("en".to_owned()),
            meta: ParsedMetadata {
                source: ParsedSource::LocalPath("test.txt".to_owned()),
                original_filename: Some("test.txt".to_owned()),
                content_type: Some("text/plain".to_owned()),
                created_at: None,
                modified_at: None,
                is_stub: false,
            },
            blocks: vec![
                ParsedBlock::Heading {
                    level: 2,
                    inlines: vec![Inline::plain("Section 1")],
                },
                ParsedBlock::Paragraph {
                    inlines: vec![Inline::plain("First paragraph")],
                },
                ParsedBlock::Paragraph {
                    inlines: vec![Inline::plain("Second paragraph")],
                },
            ],
        };

        // Collect chunks from iterator using render_iter_ref
        let chunks: Vec<String> = MarkdownRenderer::render_iter_ref(&doc).collect();

        // Should have header + 3 blocks = 4 chunks
        assert_eq!(chunks.len(), 4);

        // First chunk is header with title and metadata
        assert!(chunks[0].contains("# Test Title"));
        assert!(chunks[0].contains("language: en"));
        assert!(chunks[0].contains("filename: test.txt"));
        assert!(chunks[0].contains("content-type: text/plain"));

        // Remaining chunks are blocks
        assert!(chunks[1].contains("## Section 1"));
        assert!(chunks[2].contains("First paragraph"));
        assert!(chunks[3].contains("Second paragraph"));

        // Streamed result should match non-streamed
        let streamed = chunks.join("");
        let non_streamed = MarkdownRenderer::render(&doc);
        assert_eq!(streamed, non_streamed);
    }

    #[test]
    fn test_render_iter_no_header() {
        let doc = ParsedDocument {
            id: None,
            title: None,
            language: None,
            meta: ParsedMetadata {
                source: ParsedSource::LocalPath("test.txt".to_owned()),
                original_filename: None,
                content_type: None,
                created_at: None,
                modified_at: None,
                is_stub: false,
            },
            blocks: vec![ParsedBlock::Paragraph {
                inlines: vec![Inline::plain("Only content")],
            }],
        };

        let chunks: Vec<String> = MarkdownRenderer::render_iter_ref(&doc).collect();

        // Should have only 1 chunk (the paragraph, no header)
        assert_eq!(chunks.len(), 1);
        assert!(chunks[0].contains("Only content"));
    }
}