devpage-core 0.3.2

devpage's core: documents, rendering, link checking, comments and designs, with no I/O runtime
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
1141
1142
1143
1144
1145
1146
//! What a request is answered with: a page, a redirect, a file's bytes, a
//! design's or a slide's PNG, a widget's module, or why there is none.
//! Decided here from the documents alone, so every route is tested without
//! a socket; the HTTP server only turns an [`Answer`] into a response — its
//! headers, the file's bytes read, the PNGs it names drawn.

use std::path::PathBuf;

use devpage_design::Theme;

use crate::check::Preview;
use crate::designs::Designs;
use crate::document::{self, Document, Kind};
use crate::folder::{Folder, Owner, ServedFolder, lexical};
use crate::page;
use crate::widgets::{self, Compiled, Modules, Widgets};

/// What a request is answered with.
#[derive(Debug, PartialEq)]
pub enum Answer {
    /// A rendered page: a document, a page of one, or a design's canvas
    /// page.
    Html(String),
    /// A reply from an extension's route: its `body`, sent as `mime` with HTTP
    /// `status`.
    Extension {
        body: String,
        mime: String,
        status: u16,
    },
    /// Elsewhere: an address, mount prefix included.
    Redirect(String),
    /// A file of the served folder, sent as it is.
    File(PathBuf),
    /// The PNG of the design at `design`, a path in the served folder.
    DesignPng { design: String, theme: Theme },
    /// Slide `n` of the deck whose page is at `page` — the deck's own
    /// address, without the mount prefix, as Chrome asks the server for it;
    /// `deck` is its file.
    SlidePng {
        page: String,
        n: usize,
        deck: PathBuf,
    },
    /// A widget's module, compiled; `immutable` when asked for at its current
    /// address, since what answers that never changes.
    Module { js: String, immutable: bool },
    /// A module that throws why a widget's module can't be had — it, or a
    /// helper it imports, doesn't compile — so the page shows it in the
    /// widget's place.
    ModuleError(String),
    /// 404, and why.
    NotFound(String),
    /// 404 for an address with nothing at it: `why`, for an agent, and the
    /// `page` a browser is shown instead — the nearest site's `404.md`, or
    /// devpage's own.
    Missing { why: String, page: String },
    /// 400, and why.
    BadRequest(String),
    /// 500, and why.
    Failed(String),
}

/// What decides an answer: the served folder with its entry document, its
/// widget modules, its design store, the problems each page lists and
/// whether comments are on.
/// Every address it answers with is under the served folder's mount, which
/// the documents carry.
pub struct Answers<'a> {
    /// The served folder, with its entry document.
    folder: &'a Folder,
    /// The served folder's widget modules, compiled.
    modules: &'a Modules,
    /// The design store: each design resolved, with its problems and its PNG.
    designs: &'a Designs,
    /// `None` for the Chrome that shoots slides: its pages list no problems.
    preview: Option<&'a Preview>,
    /// Whether pages show comment threads and offer to start one; off with
    /// `devpage --no-comments`.
    comments: bool,
}

impl<'a> Answers<'a> {
    /// Answers from `folder`, its widget `modules`, its design store
    /// `designs` and the `preview` that finds each page's problems — or
    /// none, and no page lists any — with comments shown or not.
    pub fn new(
        folder: &'a Folder,
        modules: &'a Modules,
        designs: &'a Designs,
        preview: Option<&'a Preview>,
        comments: bool,
    ) -> Self {
        Self {
            folder,
            modules,
            designs,
            preview,
            comments,
        }
    }

    /// `/` leads to the entry document as its file says now — or, while the
    /// file is invalid, shows why.
    pub fn home(&self) -> Answer {
        match self.folder.entry_error() {
            Some(error) => page::invalid(&self.folder.entry(), self.folder.entry_file(), &error)
                .map_or_else(
                    || Answer::NotFound("/ is not part of the served folder".to_string()),
                    Answer::Html,
                ),
            None => self.redirect(self.folder.entry().entry()),
        }
    }

    /// `path` — relative to the served folder, already decoded — asked with
    /// `query`. A document file opens as its kind; a Markdown file becomes a
    /// page of its nearest site, or a doc of one chapter; `<design>.png` and
    /// `<deck>/<n>.png` name PNGs, unless a real file of that name is there;
    /// anything else in the served folder is sent as it is.
    pub fn path(&self, path: &str, query: Option<&str>) -> Answer {
        if let Some(reply) = crate::extensions::route(path, self.folder.served()) {
            return match reply {
                Ok(value) => Answer::Extension {
                    body: value["body"].as_str().unwrap_or_default().into(),
                    mime: value["mime"].as_str().unwrap_or("text/plain").into(),
                    status: value["status"].as_u64().unwrap_or(200) as u16,
                },
                Err(error) => Answer::Failed(format!("{error:#}")),
            };
        }
        let pairs = || query.into_iter().flat_map(|query| query.split('&'));
        let print = pairs().any(|pair| pair == "print");
        // A design's theme, as `?theme=` names it.
        let theme = pairs()
            .find_map(|pair| pair.strip_prefix("theme="))
            .map(|name| Theme::named(name).ok_or(name));
        let entry = self.folder.entry();
        let file_at = |path: &str| entry.served.file_at(path);
        let outside = || self.missing(path);
        let real = file_at(path);

        if real.is_none()
            && let Some(design) = path.strip_suffix(".png").filter(|p| p.ends_with(".design"))
        {
            // A design that isn't a file in the served folder is like any
            // other path that isn't: 404, never its problems.
            if file_at(design).is_none() {
                return outside();
            }
            return match theme {
                None => Answer::DesignPng {
                    design: design.to_string(),
                    theme: Theme::Light,
                },
                Some(Ok(theme)) => Answer::DesignPng {
                    design: design.to_string(),
                    theme,
                },
                Some(Err(other)) => {
                    Answer::BadRequest(format!("theme: expected light or dark, found \"{other}\""))
                }
            };
        }
        if real.is_none()
            && let Some((deck, n)) = path.strip_suffix(".png").and_then(|p| p.rsplit_once('/'))
            && let Some(file) = file_at(deck).filter(|file| {
                file.extension()
                    .is_some_and(|ext| ext == "yml" || ext == "yaml")
            })
        {
            return self.slide(deck, &file, n);
        }
        let Some(file) = real else {
            return self.code(path).unwrap_or_else(outside);
        };
        if path.ends_with(".design") {
            // An address that names a theme shows it; any other `theme` is
            // passed over.
            return Answer::Html(page::canvas(
                self.folder.served(),
                path,
                theme.and_then(Result::ok),
            ));
        }
        let served = &entry.served;
        if document::kind_of(&file).is_some() {
            return match Document::load(&file, served) {
                Ok(document) => self.show(&document, print),
                Err(error) => page::invalid(&entry, &file, &format!("{error:#}"))
                    .map_or_else(outside, Answer::Html),
            };
        }
        if let Some(binding) = crate::extensions::for_file(&file, self.folder)
            .iter()
            .find(|b| b.owns(&file))
        {
            return match binding.view(&file) {
                Ok(view) if view["layout"] == "workspace" => {
                    let document = self
                        .folder
                        .owner(&file)
                        .and_then(|o| o.document.ok())
                        .map(std::sync::Arc::new)
                        .unwrap_or_else(|| self.folder.entry());
                    let widgets = Widgets::of(&document, self.modules);
                    Answer::Html(page::workspace(
                        &document,
                        &widgets,
                        &file,
                        view["title"].as_str().unwrap_or("Workspace"),
                        view["content"].as_str().unwrap_or_default(),
                        self.comments,
                    ))
                }
                Ok(_) => {
                    Answer::Failed("Extension file views must use the host workspace layout".into())
                }
                Err(e) => Answer::Failed(format!("{e:#}")),
            };
        }
        if file.extension().is_none_or(|ext| ext != "md") {
            return Answer::File(file);
        }
        let source = match std::fs::read_to_string(&file) {
            Ok(source) => source,
            Err(error) => return Answer::Failed(error.to_string()),
        };
        // A site is never printed: in print mode a Markdown file is a doc of
        // one chapter, whatever site holds it — what `devpage pdf` prints. A
        // page of a site whose file is invalid shows why, until it is fixed.
        match self.folder.owner(&file) {
            Some(Owner {
                document: Ok(site), ..
            }) if !print => {
                // Rendered once: the preview judges the content the page shows.
                let widgets = Widgets::of(&site, self.modules);
                let rendered = page::content(&widgets, &file, source);
                let found = self.problems(&site, &widgets, std::slice::from_ref(&rendered));
                page::page(&site, &widgets, &rendered, self.comments, &found)
                    .map_or_else(outside, Answer::Html)
            }
            Some(Owner {
                file: site,
                document: Err(error),
            }) if !print => page::invalid(&entry, &site, &format!("{error:#}"))
                .map_or_else(outside, Answer::Html),
            owner => match Document::load(&file, served) {
                Ok(mut doc) => {
                    // A page keeps its site's widgets when printed on its own.
                    if let Some(Owner {
                        document: Ok(site), ..
                    }) = owner
                    {
                        doc.widgets = site.widgets;
                        doc.extensions = site.extensions;
                    }
                    self.show(&doc, print)
                }
                Err(error) => Answer::Failed(format!("{error:#}")),
            },
        }
    }

    /// `path`, with nothing at it — or nothing that is shown: why, and the
    /// page a browser is shown. Inside a site, in that site's frame: the
    /// `404.md` beside its document file, or devpage's own page; outside any
    /// site, devpage's own page alone. devpage's own offers the file the
    /// address most likely meant, when there is one.
    fn missing(&self, path: &str) -> Answer {
        let entry = self.folder.entry();
        let served = &entry.served;
        let address = format!("{}/{}", served.mount(), path.trim_start_matches('/'));
        let would_be = lexical(&served.path().join(path.trim_start_matches('/')));
        let meant = meant(served, path)
            .and_then(|file| entry.url(&file))
            .or_else(|| crate::code::at(self.folder, &would_be)?.closest(&would_be));
        let site = served
            .contains(&would_be)
            .then(|| self.folder.owner(&would_be))
            .flatten();
        let page = match site {
            Some(Owner {
                document: Ok(site), ..
            }) => {
                let widgets = Widgets::of(&site, self.modules);
                served
                    .file(&site.base.join("404.md"))
                    .and_then(|file| {
                        let source = std::fs::read_to_string(&file).ok()?;
                        page::missing(&site, &widgets, &page::content(&widgets, &file, source))
                    })
                    .or_else(|| page::nothing_at(&site, &widgets, &address, meant.as_deref()))
            }
            _ => None,
        }
        .unwrap_or_else(|| page::nothing_at_alone(&entry, &address, meant.as_deref()));
        let why = match &meant {
            Some(meant) => format!("nothing at {address} — did you mean {meant}?"),
            None => format!("nothing at {address}"),
        };
        Answer::Missing { why, page }
    }

    /// `path`'s page of a code reference, in its site's frame: `None` when
    /// no code reference has a page there.
    fn code(&self, path: &str) -> Option<Answer> {
        let served = self.folder.served();
        let would_be = lexical(&served.path().join(path.trim_start_matches('/')));
        let index = crate::code::at(self.folder, &would_be)?;
        let page = index.page(&would_be)?;
        let Owner {
            document: Ok(site), ..
        } = self.folder.owner(&would_be)?
        else {
            return None;
        };
        let widgets = Widgets::of(&site, self.modules);
        let rendered = page::content(&widgets, &would_be, index.markdown(&page));
        page::generated(
            &site,
            &widgets,
            &rendered,
            &index.listed(&page),
            &index.problems(),
        )
        .map(Answer::Html)
    }

    /// `/__devpage/system-widgets/<name>`: a system widget, compiled from
    /// the TSX built into the binary.
    pub fn system_widget(&self, name: &str, query: Option<&str>) -> Answer {
        module(
            widgets::system_module(self.modules, name, version(query)),
            || format!("{name} is not a system widget"),
        )
    }

    /// `/__devpage/widgets/<path>`: a project widget or a helper it imports,
    /// compiled from the served folder.
    pub fn widget(&self, path: &str, query: Option<&str>) -> Answer {
        module(
            widgets::project_module(self.folder, self.modules, path, version(query)),
            || format!("{path} is not part of the served folder"),
        )
    }

    /// `<deck>/<n>.png`: slide `n` of the deck at `file` — or why there is
    /// none: the file isn't a deck, or has no slide `n`. One address per
    /// slide: `2`, never `02`.
    fn slide(&self, deck: &str, file: &std::path::Path, n: &str) -> Answer {
        let document = match Document::load(file, self.folder.served()) {
            Ok(document) if matches!(document.kind, Kind::Slides { .. }) => document,
            _ => return Answer::NotFound(format!("{deck} is not a deck")),
        };
        let Kind::Slides { slides, .. } = &document.kind else {
            unreachable!()
        };
        let count = slides.len();
        match n
            .parse::<usize>()
            .ok()
            .filter(|i| (1..=count).contains(i) && i.to_string() == n)
        {
            Some(n) => Answer::SlidePng {
                page: document.entry(),
                n,
                deck: document.path(),
            },
            None => Answer::NotFound(format!(
                "{deck} has {count} slide{}",
                if count == 1 { "" } else { "s" }
            )),
        }
    }

    /// The problems `pages` of `document` list above themselves: none
    /// without a preview, which then looks for none.
    fn problems(
        &self,
        document: &Document,
        widgets: &Widgets,
        pages: &[page::Rendered],
    ) -> Vec<crate::problem::Problem> {
        self.preview.map_or_else(Vec::new, |preview| {
            preview.problems(self.folder, document, widgets, self.designs, pages)
        })
    }

    /// A document as its kind: a site opens on its root page. Printed, a
    /// page lists no problems, so none are looked for.
    /// Each page's content is rendered once, for the preview to judge and
    /// the frame to show.
    fn show(&self, document: &Document, print: bool) -> Answer {
        let widgets = Widgets::of(document, self.modules);
        let found = |pages: &[page::Rendered]| {
            if print {
                Vec::new()
            } else {
                self.problems(document, &widgets, pages)
            }
        };
        match &document.kind {
            Kind::Site { .. } | Kind::Design => self.redirect(document.entry()),
            Kind::Doc { chapters, pdf } => {
                let chapters: Vec<_> = chapters
                    .iter()
                    .map(|chapter| page::read(&widgets, chapter))
                    .collect();
                Answer::Html(page::doc(
                    document,
                    &widgets,
                    &chapters,
                    pdf,
                    print,
                    self.comments,
                    &found(&chapters),
                ))
            }
            Kind::Slides { slides, .. } => {
                let slides: Vec<_> = slides
                    .iter()
                    .map(|slide| page::read(&widgets, &slide.file))
                    .collect();
                Answer::Html(page::slides(
                    document,
                    &widgets,
                    &slides,
                    print,
                    self.comments,
                    &found(&slides),
                ))
            }
        }
    }

    /// A redirect to `address`, an address of the served folder's — under
    /// its mount already.
    fn redirect(&self, address: String) -> Answer {
        Answer::Redirect(address)
    }
}

/// The file an address with nothing at it most likely meant: the page it
/// names without `.md`, or ending `.html` for `.md`, or the `README.md` of
/// the folder it names.
fn meant(served: &ServedFolder, path: &str) -> Option<PathBuf> {
    let path = path.trim_matches('/');
    if path.is_empty() {
        return None;
    }
    let page = path.strip_suffix(".html").unwrap_or(path);
    [format!("{page}.md"), format!("{path}/README.md")]
        .iter()
        .find_map(|candidate| served.file_at(candidate))
}

/// The `v` a module's address was asked with, if any.
fn version(query: Option<&str>) -> Option<&str> {
    query?.split('&').find_map(|pair| pair.strip_prefix("v="))
}

/// A module request's answer: the module, a module that throws why it
/// can't be had, or — when there is none — 404 with `missing`.
fn module(requested: Option<Result<Compiled, String>>, missing: impl FnOnce() -> String) -> Answer {
    match requested {
        Some(Ok(Compiled { js, current })) => Answer::Module {
            js,
            immutable: current,
        },
        Some(Err(why)) => Answer::ModuleError(format!(
            "throw new Error({});",
            serde_json::to_string(&why).unwrap_or_default()
        )),
        None => Answer::NotFound(missing()),
    }
}

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

    /// A served folder with a site, a deck, a loose page, an invalid doc and
    /// a YAML file that isn't a document — and a secret beside it, outside.
    fn served(name: &str) -> PathBuf {
        let top =
            std::env::temp_dir().join(format!("devpage-answer-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&top);
        let dir = top.join("served");
        std::fs::create_dir_all(dir.join("docs/guide")).unwrap();
        std::fs::create_dir_all(dir.join("notes")).unwrap();
        std::fs::write(top.join("secret.md"), "# Secret\n").unwrap();
        std::fs::write(dir.join("docs/README.md"), "# Home\n").unwrap();
        std::fs::write(dir.join("docs/guide/step.md"), "# Step\n").unwrap();
        std::fs::write(
            dir.join("docs/devpage.yml"),
            "kind: site\ntitle: Docs\nroot: README.md\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("notes/talk.yml"),
            "kind: slides\ntitle: Talk\nslides: [one.md]\n",
        )
        .unwrap();
        std::fs::write(dir.join("notes/one.md"), "# One\n").unwrap();
        std::fs::write(dir.join("notes/loose.md"), "# Loose\n").unwrap();
        std::fs::write(
            dir.join("notes/broken.yml"),
            "kind: doc\ntitle: B\nchapters: [gone.md]\n",
        )
        .unwrap();
        std::fs::write(dir.join("notes/ci.yml"), "on: push\n").unwrap();
        std::fs::write(dir.join("notes/screen.design"), "").unwrap();
        dir.canonicalize().unwrap()
    }

    /// The documents of `dir` with `entry` as the entry document: what
    /// answers are made from.
    struct Served {
        folder: Folder,
        modules: Modules,
        designs: Designs,
        preview: std::sync::Arc<Preview>,
    }

    impl Served {
        fn new(dir: &std::path::Path, entry: &str) -> Self {
            Self::mounted(dir, entry, "")
        }

        /// The same, its served folder under `mount`.
        fn mounted(dir: &std::path::Path, entry: &str, mount: &str) -> Self {
            let served = crate::folder::ServedFolder::new(dir)
                .unwrap()
                .mounted(mount);
            Self {
                folder: Folder::new(std::sync::Arc::new(
                    Document::load(&dir.join(entry), &served).unwrap(),
                )),
                modules: Modules::default(),
                designs: Designs::new(&served),
                preview: crate::check::testing::preview(),
            }
        }

        fn at(&self) -> Answers<'_> {
            Answers::new(
                &self.folder,
                &self.modules,
                &self.designs,
                Some(&self.preview),
                true,
            )
        }
    }

    fn html(answer: Answer) -> String {
        match answer {
            Answer::Html(html) => html,
            other => panic!("not a page: {other:?}"),
        }
    }

    #[test]
    fn answers_a_folder_without_git_by_what_each_file_is() {
        let dir = served("kinds");
        assert!(!dir.join(".git").exists());
        let served = Served::new(&dir, "docs");
        let answers = served.at();

        assert_eq!(answers.home(), Answer::Redirect("/docs/README.md".into()));
        let page = html(answers.path("docs/guide/step.md", None));
        assert!(
            page.contains("<nav id=\"devpage-nav\" data-sidebar="),
            "a page of its nearest site"
        );
        assert!(page.contains("Step · Docs"), "{page}");

        let deck = html(answers.path("notes/talk.yml", None));
        assert!(deck.contains("Talk"), "a document file opens as its kind");
        assert!(!deck.contains("<nav id=\"devpage-nav\" data-sidebar="));

        let loose = html(answers.path("notes/loose.md", None));
        assert!(
            !loose.contains("<nav id=\"devpage-nav\" data-sidebar="),
            "in no site: a doc of one chapter"
        );
        assert!(loose.contains("Loose"));

        let broken = html(answers.path("notes/broken.yml", None));
        assert!(broken.contains("not a valid document"), "{broken}");
        assert!(
            broken.contains("chapter gone.md does not exist"),
            "{broken}"
        );

        assert_eq!(
            answers.path("docs/devpage.yml", None),
            Answer::Redirect("/docs/README.md".into()),
            "a site opens on its root page"
        );
        assert_eq!(
            answers.path("notes/ci.yml", None),
            Answer::File(dir.join("notes/ci.yml"))
        );
        let canvas = html(answers.path("notes/screen.design", None));
        assert!(
            canvas.contains(r#"<canvas class="design" src="/notes/screen.design""#),
            "a design opens on its canvas page: {canvas}"
        );
    }

    #[test]
    fn a_page_of_a_site_prints_as_a_doc_of_one_chapter() {
        let dir = served("print");
        let served = Served::new(&dir, "docs");
        let answers = served.at();
        let page = html(answers.path("docs/guide/step.md", Some("print")));
        assert!(
            page.contains("<body class=\"doc print\" data-build="),
            "{page}"
        );
        assert!(page.contains("@page { size: A4;"), "{page}");
        assert!(
            !page.contains("<nav id=\"devpage-nav\" data-sidebar="),
            "{page}"
        );
        let on_screen = html(answers.path("docs/guide/step.md", Some("x=1&y")));
        assert!(
            on_screen.contains("<nav id=\"devpage-nav\" data-sidebar="),
            "still a site page on screen"
        );
    }

    #[test]
    fn a_sites_title_links_to_its_own_root_page() {
        let dir = served("titles");
        std::fs::create_dir_all(dir.join("other")).unwrap();
        std::fs::write(dir.join("other/index.md"), "# Index\n").unwrap();
        std::fs::write(dir.join("other/page.md"), "# Page\n").unwrap();
        std::fs::write(
            dir.join("other/devpage.yml"),
            "kind: site\ntitle: Other\nroot: index.md\n",
        )
        .unwrap();
        let served = Served::new(&dir, "docs");
        let answers = served.at();
        assert!(
            html(answers.path("other/page.md", None))
                .contains("<a class=\"document-title\" href=\"/other/index.md\">Other</a>")
        );
        assert!(
            html(answers.path("docs/guide/step.md", None))
                .contains("<a class=\"document-title\" href=\"/docs/README.md\">Docs</a>")
        );
    }

    #[test]
    fn nothing_outside_the_served_folder_is_answered() {
        let dir = served("outside");
        crate::folder::symlink(&dir.join("../secret.md"), &dir.join("docs/escape.md")).unwrap();
        let served = Served::new(&dir, "docs");
        let answers = served.at();
        for path in [
            "../secret.md",
            "docs/escape.md",
            "docs/missing.md",
            "../secret.md.design.png",
            "missing.design.png",
            "../secret.md/1.png",
        ] {
            // What is outside is neither sent nor shown on the page instead.
            match answers.path(path, None) {
                Answer::Missing { page, .. } => assert!(!page.contains("Secret"), "{path}"),
                other => panic!("{path}: {other:?}"),
            }
        }
    }

    /// The why and the page of an address with nothing at it.
    fn missing(answer: Answer) -> (String, String) {
        match answer {
            Answer::Missing { why, page } => (why, page),
            other => panic!("not missing: {other:?}"),
        }
    }

    #[test]
    fn a_missing_page_is_shown_in_its_sites_frame_offering_what_it_meant() {
        let dir = served("missing");
        let served = Served::new(&dir, "docs/devpage.yml");
        let answers = served.at();

        let (why, page) = missing(answers.path("docs/guide/step", None));
        assert_eq!(
            why,
            "nothing at /docs/guide/step — did you mean /docs/guide/step.md?"
        );
        assert!(page.contains("<h1>Page not found</h1>"), "{page}");
        assert!(page.contains(r#"<a href="/docs/guide/step.md">"#), "{page}");
        assert!(page.contains(r#"class="document-title""#), "{page}");
        assert!(
            page.contains(r#"<a href="/docs/README.md">Go to Docs</a>"#),
            "{page}"
        );

        let (why, _) = missing(answers.path("docs/guide/step.html", None));
        assert!(why.ends_with("did you mean /docs/guide/step.md?"), "{why}");
        let (why, _) = missing(answers.path("docs/", None));
        assert!(why.ends_with("did you mean /docs/README.md?"), "{why}");
        let (why, _) = missing(answers.path("docs/nope", None));
        assert_eq!(why, "nothing at /docs/nope");

        // In no site, the page is alone, in the served document's theme.
        let (_, page) = missing(answers.path("notes/nope", None));
        assert!(page.contains(r#"<body class="missing""#), "{page}");
        assert!(page.contains("Go to Docs"), "{page}");

        // The address is whatever was asked for: it is never markup.
        let (_, page) = missing(answers.path("docs/<b>x", None));
        assert!(page.contains("/docs/&lt;b&gt;x"), "{page}");
        assert!(!page.contains("<b>x"), "{page}");
    }

    /// A served folder with a crate beside a site whose code reference reads
    /// it.
    fn with_code(name: &str) -> PathBuf {
        let dir = served(name);
        std::fs::create_dir_all(dir.join("lib/src")).unwrap();
        std::fs::write(dir.join("lib/Cargo.toml"), "[package]\nname = \"my-lib\"\n").unwrap();
        std::fs::write(
            dir.join("lib/src/lib.rs"),
            "//! The library.\n\n/// Holds entries.\npub struct Store {\n    /// How many.\n    pub count: usize,\n}\n\nimpl Store {\n    /// Reads one.\n    pub fn read(&self) -> u8 { 0 }\n}\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("docs/devpage.yml"),
            "kind: site\ntitle: Docs\nroot: README.md\nextensions:\n  code:\n    config:\n      rust:\n        files: [\"../lib/src/**/*.rs\"]\n",
        )
        .unwrap();
        dir
    }

    #[test]
    fn a_code_reference_page_is_shown_in_its_sites_frame_from_the_code_now() {
        let dir = with_code("code-page");
        let served = Served::new(&dir, "docs/devpage.yml");
        let answers = served.at();
        let store = html(answers.path("docs/reference/rust/my_lib/Store", None));
        assert!(store.contains("<title>Store · Docs</title>"), "{store}");
        assert!(store.contains(r#"class="document-title""#), "{store}");
        assert!(store.contains("Holds entries."), "{store}");
        assert!(store.contains("Structure"), "{store}");
        assert!(
            store.contains(r#"href="/docs/reference/rust/my_lib/Store/read""#),
            "{store}"
        );
        let read = html(answers.path("docs/reference/rust/my_lib/Store/read", None));
        assert!(read.contains("Reads one."), "{read}");
        assert!(store.contains(r#"href="/lib/src/lib.rs""#), "{store}");
        let crates = html(answers.path("docs/reference/rust", None));
        assert!(
            crates.contains(r#"href="/docs/reference/rust/my_lib""#),
            "{crates}"
        );

        let (why, _) = missing(answers.path("docs/reference/rust/my_lib/Stor", None));
        assert!(
            why.ends_with("did you mean /docs/reference/rust/my_lib/Store?"),
            "{why}"
        );

        // A save is read again: the page says what the code says now.
        let file = dir.join("lib/src/lib.rs");
        let source = std::fs::read_to_string(&file).unwrap();
        std::fs::write(&file, source.replace("Holds entries.", "Keeps entries.")).unwrap();
        assert!(crate::code::changed(served.folder.served(), &[file]));
        let store = html(answers.path("docs/reference/rust/my_lib/Store", None));
        assert!(store.contains("Keeps entries."), "{store}");
    }

    #[test]
    fn a_saved_gitignored_file_stays_out_of_the_code_reference() {
        let dir = with_code("code-ignored");
        std::fs::write(dir.join("lib/.gitignore"), "src/ignored.rs\n").unwrap();
        let lib = dir.join("lib/src/lib.rs");
        let source = std::fs::read_to_string(&lib).unwrap();
        std::fs::write(&lib, format!("{source}pub mod ignored;\n")).unwrap();
        let ignored = dir.join("lib/src/ignored.rs");
        std::fs::write(&ignored, "pub fn hidden() {}\n").unwrap();
        let served = Served::new(&dir, "docs/devpage.yml");
        let answers = served.at();
        let address = "docs/reference/rust/my_lib/ignored/hidden";
        assert!(matches!(
            answers.path(address, None),
            Answer::Missing { .. }
        ));
        std::fs::write(&ignored, "pub fn hidden() {}\npub fn more() {}\n").unwrap();
        crate::code::changed(served.folder.served(), std::slice::from_ref(&ignored));
        assert!(matches!(
            answers.path(address, None),
            Answer::Missing { .. }
        ));
    }

    #[test]
    fn a_query_saved_broken_is_a_problem_and_the_last_that_compiled_keeps_reading() {
        let dir = with_code("code-query");
        let query = dir.join("docs/rust.scm");
        std::fs::write(&query, include_str!("code/rust.scm")).unwrap();
        std::fs::write(
            dir.join("docs/devpage.yml"),
            "kind: site\ntitle: Docs\nroot: README.md\nextensions:\n  code:\n    config:\n      rust:\n        files: [\"../lib/src/**/*.rs\"]\n        query: rust.scm\n",
        )
        .unwrap();
        let served = Served::new(&dir, "docs/devpage.yml");
        let answers = served.at();
        std::fs::write(&query, "(function_item) @item.function\n(bogus) @x\n").unwrap();
        assert!(crate::code::changed(
            served.folder.served(),
            std::slice::from_ref(&query)
        ));
        let store = html(answers.path("docs/reference/rust/my_lib/Store", None));
        assert!(store.contains("Holds entries."), "{store}");
        assert!(
            store.contains("docs/rust.scm:2: query doesn't compile: NodeType error"),
            "{store}"
        );
    }

    #[test]
    fn a_sites_404_md_is_shown_where_it_has_nothing_its_links_at_their_addresses() {
        let dir = served("missing-custom");
        std::fs::write(dir.join("docs/404.md"), "# Lost\n\n[Step](guide/step.md)\n").unwrap();
        let served = Served::mounted(&dir, "docs/devpage.yml", "/m");
        let answers = served.at();
        let (why, page) = missing(answers.path("docs/a/b/gone", None));
        assert_eq!(why, "nothing at /m/docs/a/b/gone");
        assert!(page.contains("<title>Lost · Docs</title>"), "{page}");
        assert!(page.contains(r#"href="/m/docs/guide/step.md""#), "{page}");
        assert!(!page.contains("Page not found"), "{page}");
        // Outside the site, devpage's own page is shown.
        let (_, page) = missing(answers.path("notes/gone", None));
        assert!(page.contains("Page not found"), "{page}");
        // At its own address, it is a page of the site like any other.
        assert!(html(answers.path("docs/404.md", None)).contains("Lost"));
    }

    #[test]
    fn answers_a_folder_reached_through_a_symbolic_link() {
        let dir = served("symlinked");
        let link = dir.parent().unwrap().join("link");
        crate::folder::symlink(&dir, &link).unwrap();
        let link = link.canonicalize().unwrap();
        let served = Served::new(&link, "docs");
        let answers = served.at();
        assert!(html(answers.path("docs/guide/step.md", None)).contains("Step"));
        assert!(matches!(
            answers.path("notes/ci.yml", None),
            Answer::File(_)
        ));
    }

    #[test]
    fn a_slide_png_names_a_slide_of_a_deck_or_why_there_is_none() {
        let dir = served("slide-png");
        let served = Served::new(&dir, "docs");
        let answers = served.at();
        assert_eq!(
            answers.path("notes/talk.yml/1.png", None),
            Answer::SlidePng {
                page: "/notes/talk.yml".into(),
                n: 1,
                deck: dir.join("notes/talk.yml"),
            }
        );
        for (path, reason) in [
            ("notes/talk.yml/2.png", "notes/talk.yml has 1 slide"),
            ("notes/talk.yml/0.png", "notes/talk.yml has 1 slide"),
            ("notes/talk.yml/01.png", "notes/talk.yml has 1 slide"),
            ("notes/talk.yml/one.png", "notes/talk.yml has 1 slide"),
            ("docs/devpage.yml/1.png", "docs/devpage.yml is not a deck"),
            ("notes/ci.yml/1.png", "notes/ci.yml is not a deck"),
            ("notes/broken.yml/1.png", "notes/broken.yml is not a deck"),
            ("notes/gone.yml/1.png", "nothing at /notes/gone.yml/1.png"),
        ] {
            match answers.path(path, None) {
                Answer::NotFound(why) | Answer::Missing { why, .. } => {
                    assert!(why.contains(reason), "{path}: {why}")
                }
                other => panic!("{path}: {other:?}"),
            }
        }
    }

    #[test]
    fn a_design_png_takes_its_theme_from_the_address() {
        let dir = served("design-png");
        let served = Served::new(&dir, "docs");
        let answers = served.at();
        let png = |query| answers.path("notes/screen.design.png", query);
        assert_eq!(
            png(None),
            Answer::DesignPng {
                design: "notes/screen.design".into(),
                theme: Theme::Light
            }
        );
        assert_eq!(
            png(Some("theme=dark")),
            Answer::DesignPng {
                design: "notes/screen.design".into(),
                theme: Theme::Dark
            }
        );
        assert_eq!(
            png(Some("theme=blue")),
            Answer::BadRequest("theme: expected light or dark, found \"blue\"".into())
        );
        // A real file of that name is sent as it is.
        std::fs::write(dir.join("notes/screen.design.png"), "png").unwrap();
        assert!(matches!(png(None), Answer::File(_)));
    }

    #[test]
    fn every_address_it_answers_with_carries_the_mount_prefix() {
        let dir = served("mount");
        let served = Served::mounted(&dir, "docs", "/d/6f1c/v/3");
        let answers = served.at();
        assert_eq!(
            answers.home(),
            Answer::Redirect("/d/6f1c/v/3/docs/README.md".into())
        );
        assert_eq!(
            answers.path("docs/devpage.yml", None),
            Answer::Redirect("/d/6f1c/v/3/docs/README.md".into())
        );
        let canvas = html(answers.path("notes/screen.design", None));
        assert!(
            canvas.contains(r#"src="/d/6f1c/v/3/notes/screen.design""#),
            "{canvas}"
        );
        // Unmounted, the same answers are today's addresses.
        assert_eq!(
            Served::new(&dir, "docs").at().home(),
            Answer::Redirect("/docs/README.md".into())
        );
    }

    #[test]
    fn an_edited_gitignored_served_doc_is_served_fresh() {
        let dir = served("ignored-fresh");
        std::fs::write(dir.join(".gitignore"), "/drafts/\n").unwrap();
        std::fs::create_dir_all(dir.join("drafts")).unwrap();
        std::fs::write(
            dir.join("drafts/plan.yml"),
            "kind: doc\ntitle: Plan\nchapters: [a.md]\n",
        )
        .unwrap();
        std::fs::write(dir.join("drafts/a.md"), "# First draft\n").unwrap();
        let served = Served::new(&dir, "docs");
        let answers = served.at();
        let page = html(answers.path("drafts/plan.yml", None));
        assert!(page.contains("First draft"), "{page}");

        // The watcher never hears of a gitignored file, and nothing has to:
        // every request reads the document as its files say now.
        std::fs::write(
            dir.join("drafts/plan.yml"),
            "kind: doc\ntitle: Renamed plan\nchapters: [a.md]\n",
        )
        .unwrap();
        std::fs::write(dir.join("drafts/a.md"), "# Second draft\n").unwrap();
        let page = html(answers.path("drafts/plan.yml", None));
        assert!(page.contains("Renamed plan"), "{page}");
        assert!(page.contains("Second draft"), "{page}");
        assert!(!page.contains("First draft"), "{page}");
    }

    #[test]
    fn a_design_opens_on_its_canvas_page_in_the_theme_its_address_names() {
        let dir = served("canvas-theme");
        let served = Served::new(&dir, "docs");
        let answers = served.at();
        let page = |query| html(answers.path("notes/screen.design", query));
        let chosen = r#"<script>document.documentElement.dataset.theme="dark"</script>"#;
        assert!(page(Some("theme=dark")).contains(chosen));
        assert!(!page(None).contains("dataset.theme=\"dark\""));
        assert!(!page(Some("theme=blue")).contains("dataset.theme=\"blue\""));
        assert!(page(None).contains("<title>screen</title>"));
    }

    /// The module `answer` is, and whether it is immutable.
    fn module(answer: Answer) -> (String, bool) {
        match answer {
            Answer::Module { js, immutable } => (js, immutable),
            other => panic!("not a module: {other:?}"),
        }
    }

    /// The module that throws, that `answer` is.
    fn thrown(answer: Answer) -> String {
        match answer {
            Answer::ModuleError(js) => js,
            other => panic!("not a module that throws: {other:?}"),
        }
    }

    #[test]
    fn widgets_are_answered_compiled_for_the_document_they_belong_to() {
        let dir = served("widget-modules");
        std::fs::create_dir_all(dir.join("docs/widgets")).unwrap();
        std::fs::create_dir_all(dir.join("notes/parts")).unwrap();
        std::fs::write(
            dir.join("docs/devpage.yml"),
            "kind: site\ntitle: Docs\nroot: README.md\nwidgets: widgets\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("docs/widgets/Card.tsx"),
            "import { label } from \"./label\";\nexport default () => <Callout>{label}</Callout>;",
        )
        .unwrap();
        std::fs::write(
            dir.join("docs/widgets/label.ts"),
            "export const label = 'x';",
        )
        .unwrap();
        std::fs::write(dir.join("docs/widgets/Broken.tsx"), "export default (").unwrap();
        // Another document's widgets compose with that document's names.
        std::fs::write(
            dir.join("notes/talk.yml"),
            "kind: slides\ntitle: Talk\nslides: [one.md]\nwidgets: parts\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("notes/parts/Pill.tsx"),
            "export default () => <i>p</i>;",
        )
        .unwrap();
        std::fs::write(
            dir.join("notes/parts/Row.tsx"),
            "export default () => <Pill />;",
        )
        .unwrap();
        let served = Served::new(&dir, "docs");
        let answers = served.at();

        // A system widget: immutable at its current address only.
        let tabs = widgets::system_address("Tabs", "");
        let (path, query) = tabs.split_once('?').unwrap();
        let name = path.rsplit('/').next().unwrap();
        let (system, immutable) = module(answers.system_widget(name, Some(query)));
        assert!(system.contains("export const __devpageUses"), "{system}");
        assert!(immutable);
        assert_eq!(module(answers.system_widget(name, None)), (system, false));
        assert_eq!(
            answers.system_widget("Nope.tsx", None),
            Answer::NotFound("Nope.tsx is not a system widget".into())
        );

        // The address a page names a project widget by is the one it is
        // immutable at; the helper it imports is named by its own address.
        let page = html(answers.path("docs/README.md", None));
        let card = page
            .split("\"Card\":\"")
            .nth(1)
            .and_then(|rest| rest.split('"').next())
            .unwrap()
            .to_string();
        let asked = |address: &str| {
            let (path, query) = address.split_once('?').unwrap_or((address, ""));
            let path = path.strip_prefix("/__devpage/widgets/").unwrap();
            answers.widget(path, Some(query).filter(|q| !q.is_empty()))
        };
        let (compiled, immutable) = module(asked(&card));
        assert!(immutable, "{card}");
        let label = Modules::default()
            .snapshot(served.folder.served(), &dir.join("docs/widgets/label.ts"))
            .address(
                &dir.join("docs/widgets/label.ts"),
                Widgets::of(&served.folder.entry(), &Modules::default()).names(),
            );
        assert!(compiled.contains(&format!("\"{label}\"")), "{compiled}");
        assert!(
            compiled.contains("__devpageUses = [\"Callout\"]"),
            "{compiled}"
        );
        let (helper, immutable) = module(asked(&label));
        assert!(immutable && helper.contains("label"), "{helper}");
        // Any other version answers with the current module, never immutable.
        for stale in [
            "/__devpage/widgets/docs/widgets/Card.tsx?v=0123456789abcdef",
            "/__devpage/widgets/docs/widgets/Card.tsx",
        ] {
            assert_eq!(module(asked(stale)), (compiled.clone(), false), "{stale}");
        }
        // An import without an extension finds the `.ts` beside it.
        let (helper, _) = module(answers.widget("docs/widgets/label", None));
        assert!(helper.contains("label"), "{helper}");

        let broken = thrown(answers.widget("docs/widgets/Broken.tsx", None));
        assert!(
            broken.starts_with("throw new Error(\"docs/widgets/Broken.tsx does not compile:"),
            "{broken}"
        );
        let (row, _) = module(answers.widget("notes/parts/Row.tsx", None));
        assert!(row.contains("__devpageUses = [\"Pill\"]"), "{row}");

        for outside in ["../secret.md", "docs/widgets/Gone.tsx"] {
            assert_eq!(
                answers.widget(outside, None),
                Answer::NotFound(format!("{outside} is not part of the served folder"))
            );
        }
    }

    #[test]
    fn a_widget_whose_helper_does_not_compile_throws_naming_the_helper() {
        let dir = served("widget-broken-helper");
        std::fs::create_dir_all(dir.join("docs/widgets")).unwrap();
        std::fs::write(
            dir.join("docs/devpage.yml"),
            "kind: site\ntitle: Docs\nroot: README.md\nwidgets: widgets\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("docs/widgets/Card.tsx"),
            "import { frame } from \"./frame\";\nexport default () => <i>{frame}</i>;",
        )
        .unwrap();
        // Reached through a second helper: the error is transitive.
        std::fs::write(
            dir.join("docs/widgets/frame.ts"),
            "export { inner as frame } from \"./inner\";",
        )
        .unwrap();
        std::fs::write(dir.join("docs/widgets/inner.ts"), "export const inner = (").unwrap();
        let served = Served::new(&dir, "docs");
        let thrown = thrown(served.at().widget("docs/widgets/Card.tsx", None));
        assert!(
            thrown.starts_with("throw new Error(\"docs/widgets/inner.ts does not compile:"),
            "{thrown}"
        );
    }
}