surf-parse 0.10.0

Parser for the SurfDoc format — typed document format with block directives, Markdown-compatible
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
//! Schema validation for SurfDoc documents.
//!
//! Checks required attributes, front matter rules, and block-level constraints.
//! Returns a list of `Diagnostic` items (non-fatal).

use crate::error::{Diagnostic, Severity};
use crate::types::{Block, SurfDoc};

/// Validate a parsed `SurfDoc` and return any diagnostics.
///
/// This function checks front matter completeness, required block attributes,
/// and block content constraints. It never modifies the document.
pub fn validate(doc: &SurfDoc) -> Vec<Diagnostic> {
    let mut diagnostics = Vec::new();

    // Front matter validation
    validate_front_matter(doc, &mut diagnostics);

    // Per-block validation
    for block in &doc.blocks {
        validate_block(block, &mut diagnostics);
    }

    // Validate ::app children
    for block in &doc.blocks {
        if let Block::App { children, .. } = block {
            for child in children {
                validate_block(child, &mut diagnostics);
            }
        }
    }

    // Cross-block validation: duplicate page routes
    validate_unique_page_routes(&doc.blocks, &mut diagnostics);

    // NOTE (0.10.0 open-core split): cross-model reference checking (V303)
    // and marketplace field-type semantics (V340-V343) moved to the private
    // surf-appcompile crate (validate_app_doc) — they are compile-to-app
    // rules, not document format rules.

    diagnostics
}

/// Check for duplicate `::page[route=...]` values within a document.
fn validate_unique_page_routes(blocks: &[Block], diagnostics: &mut Vec<Diagnostic>) {
    let mut seen: Vec<(&str, &crate::types::Span)> = Vec::new();
    for block in blocks {
        if let Block::Page { route, span, .. } = block {
            if let Some((_, first_span)) = seen.iter().find(|(r, _)| *r == route.as_str()) {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: format!(
                        "Duplicate page route \"{}\": first defined at line {}",
                        route, first_span.start_line
                    ),
                    span: Some(*span),
                    code: Some("V141".into()),
                    fix: None,
                });
            } else {
                seen.push((route.as_str(), span));
            }
        }
    }
}

fn validate_front_matter(doc: &SurfDoc, diagnostics: &mut Vec<Diagnostic>) {
    match &doc.front_matter {
        None => {
            diagnostics.push(Diagnostic {
                severity: Severity::Warning,
                message: "Missing front matter: no title specified".into(),
                span: None,
                code: Some("V001".into()),
                fix: None,
            });
            diagnostics.push(Diagnostic {
                severity: Severity::Warning,
                message: "Missing front matter: no doc_type specified".into(),
                span: None,
                code: Some("V002".into()),
                fix: None,
            });
        }
        Some(fm) => {
            if fm.title.is_none() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "Missing front matter field: title".into(),
                    span: None,
                    code: Some("V001".into()),
                    fix: None,
                });
            }
            if fm.doc_type.is_none() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "Missing front matter field: doc_type".into(),
                    span: None,
                    code: Some("V002".into()),
                    fix: None,
                });
            }
        }
    }
}

fn validate_block(block: &Block, diagnostics: &mut Vec<Diagnostic>) {
    match block {
        Block::Metric {
            label,
            value,
            span,
            ..
        } => {
            if label.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "Metric block is missing required attribute: label".into(),
                    span: Some(*span),
                    code: Some("V010".into()),
                    fix: None,
                });
            }
            if value.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "Metric block is missing required attribute: value".into(),
                    span: Some(*span),
                    code: Some("V011".into()),
                    fix: None,
                });
            }
        }

        Block::Figure { src, span, .. } => {
            if src.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "Figure block is missing required attribute: src".into(),
                    span: Some(*span),
                    code: Some("V020".into()),
                    fix: None,
                });
            }
        }

        Block::Data {
            headers,
            rows,
            span,
            ..
        } => {
            if !headers.is_empty() && rows.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "Data block has headers but zero data rows".into(),
                    span: Some(*span),
                    code: Some("V030".into()),
                    fix: None,
                });
            }
        }

        Block::Callout {
            content, span, ..
        } => {
            if content.trim().is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "Callout block has empty content".into(),
                    span: Some(*span),
                    code: Some("V040".into()),
                    fix: None,
                });
            }
        }

        Block::Code {
            content, span, ..
        } => {
            if content.trim().is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "Code block has empty content".into(),
                    span: Some(*span),
                    code: Some("V050".into()),
                    fix: None,
                });
            }
        }

        Block::Decision {
            content, span, ..
        } => {
            if content.trim().is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "Decision block has empty body".into(),
                    span: Some(*span),
                    code: Some("V060".into()),
                    fix: None,
                });
            }
        }

        Block::Tabs { tabs, span, .. } => {
            if tabs.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "Tabs block has no tab panels".into(),
                    span: Some(*span),
                    code: Some("V070".into()),
                    fix: None,
                });
            }
        }

        Block::Quote {
            content, span, ..
        } => {
            if content.trim().is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "Quote block has empty content".into(),
                    span: Some(*span),
                    code: Some("V080".into()),
                    fix: None,
                });
            }
        }

        Block::Cta {
            label,
            href,
            span,
            ..
        } => {
            if label.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "Cta block is missing required attribute: label".into(),
                    span: Some(*span),
                    code: Some("V090".into()),
                    fix: None,
                });
            }
            if href.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "Cta block is missing required attribute: href".into(),
                    span: Some(*span),
                    code: Some("V091".into()),
                    fix: None,
                });
            }
        }

        Block::HeroImage { src, span, .. } => {
            if src.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "HeroImage block is missing required attribute: src".into(),
                    span: Some(*span),
                    code: Some("V100".into()),
                    fix: None,
                });
            }
        }

        Block::Testimonial {
            content, span, ..
        } => {
            if content.trim().is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "Testimonial block has empty content".into(),
                    span: Some(*span),
                    code: Some("V110".into()),
                    fix: None,
                });
            }
        }

        Block::Faq { items, span, .. } => {
            if items.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "Faq block has no question/answer items".into(),
                    span: Some(*span),
                    code: Some("V120".into()),
                    fix: None,
                });
            }
        }

        Block::PricingTable {
            headers,
            rows,
            span,
            ..
        } => {
            if headers.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "PricingTable block has no headers (tier names)".into(),
                    span: Some(*span),
                    code: Some("V130".into()),
                    fix: None,
                });
            }
            if !headers.is_empty() && rows.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "PricingTable block has headers but zero feature rows".into(),
                    span: Some(*span),
                    code: Some("V131".into()),
                    fix: None,
                });
            }
        }

        Block::Page { route, span, .. } => {
            if route.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "Page block is missing required attribute: route".into(),
                    span: Some(*span),
                    code: Some("V140".into()),
                    fix: None,
                });
            }
        }

        Block::Nav { items, span, .. } => {
            if items.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "Nav block has no navigation items".into(),
                    span: Some(*span),
                    code: Some("V150".into()),
                    fix: None,
                });
            }
        }

        Block::App { name, span, .. } => {
            if name.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "App block is missing required attribute: name".into(),
                    span: Some(*span),
                    code: Some("V200".into()),
                    fix: None,
                });
            }
        }

        Block::Deploy { env, span, .. } => {
            if env.is_none() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "Deploy block is missing required attribute: env".into(),
                    span: Some(*span),
                    code: Some("V201".into()),
                    fix: None,
                });
            } else if let Some(e) = env {
                if !["develop", "staging", "production"].contains(&e.as_str()) {
                    diagnostics.push(Diagnostic {
                        severity: Severity::Warning,
                        message: format!("Deploy env \"{}\" is not one of: develop, staging, production", e),
                        span: Some(*span),
                        code: Some("V202".into()),
                        fix: None,
                    });
                }
            }
        }

        Block::InfraEnv { tier, span, .. } => {
            if tier.is_none() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "Env block is missing tier attribute".into(),
                    span: Some(*span),
                    code: Some("V203".into()),
                    fix: None,
                });
            } else if let Some(t) = tier {
                if !["required", "recommended", "optional", "defaults"].contains(&t.as_str()) {
                    diagnostics.push(Diagnostic {
                        severity: Severity::Warning,
                        message: format!("Env tier \"{}\" is not one of: required, recommended, optional, defaults", t),
                        span: Some(*span),
                        code: Some("V204".into()),
                        fix: None,
                    });
                }
            }
        }

        Block::Health { path, span, .. } => {
            if path.is_none() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "Health block is missing required attribute: path".into(),
                    span: Some(*span),
                    code: Some("V205".into()),
                    fix: None,
                });
            }
        }

        Block::Smoke { checks, span, .. } => {
            for (i, check) in checks.iter().enumerate() {
                if !["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"].contains(&check.method.as_str()) {
                    diagnostics.push(Diagnostic {
                        severity: Severity::Warning,
                        message: format!("Smoke check {} has unrecognized HTTP method: {}", i + 1, check.method),
                        span: Some(*span),
                        code: Some("V206".into()),
                        fix: None,
                    });
                }
            }
        }

        Block::Concurrency { hard_limit, soft_limit, span, .. } => {
            if let (Some(hard), Some(soft)) = (hard_limit, soft_limit) {
                if hard < soft {
                    diagnostics.push(Diagnostic {
                        severity: Severity::Warning,
                        message: format!("Concurrency hard_limit ({}) should be >= soft_limit ({})", hard, soft),
                        span: Some(*span),
                        code: Some("V207".into()),
                        fix: None,
                    });
                }
            }
        }

        Block::Volumes { entries, span, .. } => {
            for entry in entries {
                if entry.name.is_empty() || entry.mount.is_empty() {
                    diagnostics.push(Diagnostic {
                        severity: Severity::Warning,
                        message: "Volume entry must have both name and mount path".into(),
                        span: Some(*span),
                        code: Some("V208".into()),
                        fix: None,
                    });
                }
            }
        }

        Block::Model { name, fields, span, .. } => {
            if name.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "Model block is missing required attribute: name".into(),
                    span: Some(*span),
                    code: Some("V300".into()),
                    fix: None,
                });
            }
            if fields.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: format!("Model \"{}\" has no fields defined", name),
                    span: Some(*span),
                    code: Some("V301".into()),
                    fix: None,
                });
            }
            // Check for duplicate field names
            let mut seen_fields: Vec<&str> = Vec::new();
            for field in fields {
                if seen_fields.contains(&field.name.as_str()) {
                    diagnostics.push(Diagnostic {
                        severity: Severity::Error,
                        message: format!("Model \"{}\" has duplicate field name: {}", name, field.name),
                        span: Some(*span),
                        code: Some("V302".into()),
                        fix: None,
                    });
                } else {
                    seen_fields.push(&field.name);
                }
            }

        }

        Block::Route { path, span, .. } => {
            if path.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "Route block is missing required attribute: path".into(),
                    span: Some(*span),
                    code: Some("V310".into()),
                    fix: None,
                });
            } else if !path.starts_with('/') {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: format!("Route path \"{}\" should start with /", path),
                    span: Some(*span),
                    code: Some("V311".into()),
                    fix: None,
                });
            }
        }

        Block::Auth { roles, span, .. } => {
            if roles.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Warning,
                    message: "Auth block has no roles defined".into(),
                    span: Some(*span),
                    code: Some("V320".into()),
                    fix: None,
                });
            }
        }

        Block::Binding { source, target, span, .. } => {
            if source.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "Binding block is missing required attribute: source".into(),
                    span: Some(*span),
                    code: Some("V330".into()),
                    fix: None,
                });
            }
            if target.is_empty() {
                diagnostics.push(Diagnostic {
                    severity: Severity::Error,
                    message: "Binding block is missing required attribute: target".into(),
                    span: Some(*span),
                    code: Some("V331".into()),
                    fix: None,
                });
            }
        }

        Block::Details { .. } => {}
        Block::Divider { .. } => {}

        // Markdown, Tasks, Summary, Columns, Style, Site, Unknown — no required-field validation
        _ => {}
    }
}

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

    fn span() -> Span {
        Span {
            start_line: 1,
            end_line: 1,
            start_offset: 0,
            end_offset: 0,
        }
    }

    #[test]
    fn validate_empty_doc() {
        let doc = SurfDoc {
            front_matter: None,
            blocks: vec![],
            source: String::new(),
        };
        let diags = validate(&doc);
        // Should warn about missing title and doc_type
        assert!(
            diags.iter().any(|d| d.message.contains("title")),
            "Should warn about missing title"
        );
        assert!(
            diags.iter().any(|d| d.message.contains("doc_type")),
            "Should warn about missing doc_type"
        );
    }

    #[test]
    fn validate_complete_doc() {
        let doc = SurfDoc {
            front_matter: Some(FrontMatter {
                title: Some("Complete Doc".into()),
                doc_type: Some(DocType::Doc),
                ..FrontMatter::default()
            }),
            blocks: vec![Block::Markdown {
                content: "Hello".into(),
                span: span(),
            }],
            source: String::new(),
        };
        let diags = validate(&doc);
        assert!(
            diags.is_empty(),
            "Complete doc should have no diagnostics, got: {diags:?}"
        );
    }

    #[test]
    fn validate_missing_metric_label() {
        let doc = SurfDoc {
            front_matter: Some(FrontMatter {
                title: Some("Test".into()),
                doc_type: Some(DocType::Report),
                ..FrontMatter::default()
            }),
            blocks: vec![Block::Metric {
                label: String::new(),
                value: "$2K".into(),
                trend: None,
                unit: None,
                span: span(),
            }],
            source: String::new(),
        };
        let diags = validate(&doc);
        let metric_diags: Vec<_> = diags
            .iter()
            .filter(|d| d.message.contains("label"))
            .collect();
        assert_eq!(metric_diags.len(), 1);
        assert_eq!(metric_diags[0].severity, Severity::Error);
    }

    #[test]
    fn validate_missing_figure_src() {
        let doc = SurfDoc {
            front_matter: Some(FrontMatter {
                title: Some("Test".into()),
                doc_type: Some(DocType::Doc),
                ..FrontMatter::default()
            }),
            blocks: vec![Block::Figure {
                src: String::new(),
                caption: Some("Photo".into()),
                alt: None,
                width: None,
                span: span(),
            }],
            source: String::new(),
        };
        let diags = validate(&doc);
        let figure_diags: Vec<_> = diags
            .iter()
            .filter(|d| d.message.contains("src"))
            .collect();
        assert_eq!(figure_diags.len(), 1);
        assert_eq!(figure_diags[0].severity, Severity::Error);
    }

    #[test]
    fn validate_duplicate_page_routes() {
        let doc = SurfDoc {
            front_matter: Some(FrontMatter {
                title: Some("Test".into()),
                doc_type: Some(DocType::Doc),
                ..FrontMatter::default()
            }),
            blocks: vec![
                Block::Page {
                    route: "/".into(),
                    title: Some("Home v1".into()),
                    layout: None,
                    sidebar: false,
                    content: String::new(),
                    children: vec![],
                    span: Span { start_line: 1, end_line: 3, start_offset: 0, end_offset: 30 },
                },
                Block::Page {
                    route: "/about".into(),
                    title: Some("About".into()),
                    layout: None,
                    sidebar: false,
                    content: String::new(),
                    children: vec![],
                    span: Span { start_line: 4, end_line: 6, start_offset: 31, end_offset: 60 },
                },
                Block::Page {
                    route: "/".into(),
                    title: Some("Home v2".into()),
                    layout: None,
                    sidebar: false,
                    content: String::new(),
                    children: vec![],
                    span: Span { start_line: 7, end_line: 9, start_offset: 61, end_offset: 90 },
                },
            ],
            source: String::new(),
        };
        let diags = validate(&doc);
        let dup_diags: Vec<_> = diags
            .iter()
            .filter(|d| d.code.as_deref() == Some("V141"))
            .collect();
        assert_eq!(dup_diags.len(), 1, "Expected exactly 1 duplicate route diagnostic");
        assert!(dup_diags[0].message.contains("/"), "Should mention the duplicate route");
        assert_eq!(dup_diags[0].severity, Severity::Error);
    }

    #[test]
    fn validate_unique_page_routes_no_false_positive() {
        let doc = SurfDoc {
            front_matter: Some(FrontMatter {
                title: Some("Test".into()),
                doc_type: Some(DocType::Doc),
                ..FrontMatter::default()
            }),
            blocks: vec![
                Block::Page {
                    route: "/".into(),
                    title: Some("Home".into()),
                    layout: None,
                    sidebar: false,
                    content: String::new(),
                    children: vec![],
                    span: span(),
                },
                Block::Page {
                    route: "/about".into(),
                    title: Some("About".into()),
                    layout: None,
                    sidebar: false,
                    content: String::new(),
                    children: vec![],
                    span: span(),
                },
                Block::Page {
                    route: "/contact".into(),
                    title: Some("Contact".into()),
                    layout: None,
                    sidebar: false,
                    content: String::new(),
                    children: vec![],
                    span: span(),
                },
            ],
            source: String::new(),
        };
        let diags = validate(&doc);
        let dup_diags: Vec<_> = diags
            .iter()
            .filter(|d| d.code.as_deref() == Some("V141"))
            .collect();
        assert!(dup_diags.is_empty(), "No duplicate route diagnostics expected");
    }

    #[test]
    fn validate_empty_code() {
        let doc = SurfDoc {
            front_matter: Some(FrontMatter {
                title: Some("Test".into()),
                doc_type: Some(DocType::Doc),
                ..FrontMatter::default()
            }),
            blocks: vec![Block::Code {
                lang: Some("rust".into()),
                file: None,
                highlight: vec![],
                content: "   ".into(), // whitespace-only
                span: span(),
            }],
            source: String::new(),
        };
        let diags = validate(&doc);
        let code_diags: Vec<_> = diags
            .iter()
            .filter(|d| d.message.contains("Code block"))
            .collect();
        assert_eq!(code_diags.len(), 1);
        assert_eq!(code_diags[0].severity, Severity::Warning);
    }

}