Skip to main content

fusion_stack/
docs.rs

1//! The API reference and changelog pages, as the PHP package's `DocsController` serves them at
2//! `api.docs.path`: Scalar (or Redoc) over the OpenAPI document of each offered version, and
3//! the changelog rendered from each version's changes.
4
5use laravel::http::{Request, Response};
6use serde_json::{Map, Value, json};
7
8use crate::errors::{ApiError, ApiErrorCode};
9use crate::versioning::{ApiVersion, HEADER, VersionChange};
10use crate::{State, time};
11
12const SCALAR_CSS: &str = include_str!("../resources/docs/scalar.css");
13
14/// Which page renders the reference.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum Renderer {
17    /// Scalar, which switches between versions itself.
18    Scalar,
19    /// Redoc, which shows one version, with a select to reload the page with another.
20    Redoc,
21}
22
23/// `api.docs` in the PHP package. Mount the pages with [`routes`].
24#[derive(Clone)]
25pub struct Docs {
26    pub(crate) path: String,
27    renderer: Renderer,
28    scalar_url: String,
29    scalar_config: Map<String, Value>,
30    redoc_url: String,
31    pub(crate) lint_fails: bool,
32}
33
34impl Default for Docs {
35    fn default() -> Self {
36        Self {
37            path: "docs".to_owned(),
38            renderer: Renderer::Scalar,
39            scalar_url: "https://cdn.jsdelivr.net/npm/@scalar/api-reference".to_owned(),
40            scalar_config: Map::new(),
41            redoc_url: "https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js".to_owned(),
42            lint_fails: false,
43        }
44    }
45}
46
47impl Docs {
48    /// The defaults: Scalar at `/docs`.
49    #[must_use]
50    pub fn new() -> Self {
51        Self::default()
52    }
53
54    /// Where [`routes`] mounts the pages (`api.docs.path`, `docs`).
55    #[must_use]
56    pub fn path(mut self, path: &str) -> Self {
57        path.trim_matches('/').clone_into(&mut self.path);
58        self
59    }
60
61    /// Which page renders the reference (`api.docs.renderer`).
62    #[must_use]
63    pub const fn renderer(mut self, renderer: Renderer) -> Self {
64        self.renderer = renderer;
65        self
66    }
67
68    /// Where Scalar is loaded from (`api.docs.scalar.url`).
69    #[must_use]
70    pub fn scalar_url(mut self, url: &str) -> Self {
71        url.clone_into(&mut self.scalar_url);
72        self
73    }
74
75    /// Options for `Scalar.createApiReference` (`api.docs.scalar.config`), such as `theme`.
76    /// Without a `theme` or `customCss`, the reference uses Fusion Stack's colours. Scalar's
77    /// developer toolbar and AI assistant are off unless set here.
78    #[must_use]
79    pub fn scalar_config(mut self, config: Map<String, Value>) -> Self {
80        self.scalar_config = config;
81        self
82    }
83
84    /// Whether `api:docs:lint` exits with an error when anything has no description, for CI
85    /// (`api.docs.lint` set to `fail`). It only warns by default.
86    #[must_use]
87    pub const fn lint_fails(mut self, fails: bool) -> Self {
88        self.lint_fails = fails;
89        self
90    }
91
92    /// Where Redoc is loaded from (`api.docs.redoc.url`).
93    #[must_use]
94    pub fn redoc_url(mut self, url: &str) -> Self {
95        url.clone_into(&mut self.redoc_url);
96        self
97    }
98}
99
100/// Registers the reference at `/{path}`, each version's document at `/{path}/openapi.json`, and
101/// the changelog at `/{path}/changelog`. Wrap the call in a group to add middleware, such as
102/// authentication.
103pub fn routes(route: &mut laravel::routing::Router) {
104    let path = crate::STATE.get().map_or_else(
105        || Docs::default().path,
106        |state| state.config.docs.path.clone(),
107    );
108    route.prefix(&format!("/{path}")).group(|route| {
109        route.get("/", reference);
110        route.get("/openapi.json", openapi);
111        route.get("/changelog", changelog);
112    });
113}
114
115/// A version the docs offer.
116struct Offered {
117    version: ApiVersion,
118    label: String,
119    latest: bool,
120}
121
122/// A document the reference lists.
123struct Document {
124    title: String,
125    slug: String,
126    url: String,
127    default: bool,
128}
129
130fn state() -> laravel::Result<&'static State> {
131    crate::STATE.get().map(AsRef::as_ref).ok_or_else(|| {
132        ApiError::new(
133            ApiErrorCode::ServerError,
134            "Fusion Stack is not registered as a service provider.",
135        )
136        .into_error()
137    })
138}
139
140/// The released versions that are not retired, newest first, or `None` while versioning is off.
141fn offered(state: &State) -> Option<Vec<Offered>> {
142    let registry = state.registry.as_ref()?;
143    let now = time::now();
144    Some(
145        registry
146            .history()
147            .into_iter()
148            .filter(|(version, _)| {
149                !registry.is_unreleased(version) && !registry.is_retired(version, now)
150            })
151            .map(|(version, _)| {
152                let latest = *version == registry.latest;
153                // Short enough for Scalar's switcher, which truncates longer labels.
154                let note = if latest {
155                    Some("latest".to_owned())
156                } else {
157                    registry.deprecation(version).map(|deprecation| {
158                        deprecation.sunset.map_or_else(
159                            || "deprecated".to_owned(),
160                            |sunset| format!("sunset {}", time::date(sunset)),
161                        )
162                    })
163                };
164                Offered {
165                    version: version.clone(),
166                    label: note
167                        .map_or_else(|| version.to_string(), |note| format!("{version} ({note})")),
168                    latest,
169                }
170            })
171            .collect(),
172    )
173}
174
175fn url(request: &Request, state: &State, page: &str) -> String {
176    let base = format!("{}/{}", request.origin(), state.config.docs.path);
177    if page.is_empty() {
178        base
179    } else {
180        format!("{base}/{page}")
181    }
182}
183
184fn title(state: &State) -> String {
185    state
186        .config
187        .openapi
188        .title
189        .clone()
190        .or_else(|| std::env::var("APP_NAME").ok())
191        .filter(|title| !title.is_empty())
192        .unwrap_or_else(|| "API reference".to_owned())
193}
194
195/// `2026-11-30.atlas` as `2026-11-30-atlas`, for Scalar's URLs and the Redoc select.
196fn slug(version: &str) -> String {
197    let mut slug = String::new();
198    for character in version.to_lowercase().chars() {
199        if character.is_alphanumeric() {
200            slug.push(character);
201        } else if !slug.is_empty() && !slug.ends_with('-') {
202            slug.push('-');
203        }
204    }
205    slug.trim_end_matches('-').to_owned()
206}
207
208/// The reference page.
209///
210/// # Errors
211///
212/// When Fusion Stack is not registered.
213pub async fn reference(request: Request) -> laravel::Result<Response> {
214    let state = state()?;
215    let openapi = url(&request, state, "openapi.json");
216    let documents: Vec<Document> = match offered(state) {
217        None => vec![Document {
218            title: title(state),
219            slug: "api".to_owned(),
220            url: openapi,
221            default: true,
222        }],
223        Some(versions) => versions
224            .into_iter()
225            .map(|entry| Document {
226                slug: slug(&entry.version.to_string()),
227                url: format!(
228                    "{openapi}?version={}",
229                    query_value(&entry.version.to_string())
230                ),
231                title: entry.label,
232                default: entry.latest,
233            })
234            .collect(),
235    };
236    Ok(match state.config.docs.renderer {
237        Renderer::Scalar => scalar(state, &documents),
238        Renderer::Redoc => redoc(&request, state, &documents),
239    })
240}
241
242/// The OpenAPI document for `?version=`, or the latest, with a link to the changelog.
243///
244/// # Errors
245///
246/// A 404 for a version the docs do not offer.
247pub async fn openapi(request: Request) -> laravel::Result<Response> {
248    let state = state()?;
249    let version = match offered(state) {
250        None => None,
251        Some(versions) => {
252            let query = crate::query_string::parse(request.uri().query().unwrap_or_default());
253            match query.get("version").and_then(Value::as_str) {
254                None => None,
255                Some(requested) => {
256                    let named = state.registry.as_ref().and_then(|r| r.named(requested));
257                    if !versions
258                        .iter()
259                        .any(|entry| Some(&entry.version) == named.as_ref())
260                    {
261                        return Err(ApiError::new(
262                            ApiErrorCode::NotFound,
263                            format!("The docs do not offer API version [{requested}]."),
264                        )
265                        .into_error());
266                    }
267                    Some(requested.to_owned())
268                }
269            }
270        }
271    };
272    let mut document = crate::openapi::generate(version.as_deref())
273        .map_err(|message| ApiError::new(ApiErrorCode::NotFound, message).into_error())?;
274    if state.registry.is_some()
275        && let Some(info) = document.get_mut("info").and_then(Value::as_object_mut)
276    {
277        let link = format!(
278            "[Changelog]({}): what changed in each version.",
279            url(&request, state, "changelog")
280        );
281        let description = info
282            .get("description")
283            .and_then(Value::as_str)
284            .unwrap_or_default();
285        info.insert(
286            "description".into(),
287            json!(format!("{description}\n\n{link}").trim()),
288        );
289    }
290    let mut http = laravel::axum::http::Response::new(laravel::axum::body::Body::from(
291        serde_json::to_vec(&document).unwrap_or_default(),
292    ));
293    http.headers_mut().insert(
294        laravel::http::header::CONTENT_TYPE,
295        laravel::http::HeaderValue::from_static("application/json"),
296    );
297    Ok(Response::from_http(http))
298}
299
300/// The changelog page.
301///
302/// # Errors
303///
304/// A 404 while versioning is off.
305pub async fn changelog(request: Request) -> laravel::Result<Response> {
306    let state = state()?;
307    if state.registry.is_none() {
308        return Err(ApiError::new(
309            ApiErrorCode::NotFound,
310            "The API has no versions, so it has no changelog.",
311        )
312        .into_error());
313    }
314    let html = markdown_to_html(&markdown(false));
315    let back = escape(&url(&request, state, ""));
316    Ok(page(
317        &format!("Changelog · {}", title(state)),
318        &format!(
319            r#"<style>
320  :root {{ color-scheme: light dark; --fg: #1c1326; --muted: #5f5468; --line: #efe4db; --code: #fbf6f2; --link: #c2410c; --bg: #ffffff; }}
321  @media (prefers-color-scheme: dark) {{ :root {{ --fg: #f6eefb; --muted: #b3a6c0; --line: #2a2035; --code: #1d1528; --link: #ff8a5c; --bg: #140e1c; }} }}
322  html {{ background: var(--bg); }}
323  body {{ font: 16px/1.65 system-ui, sans-serif; color: var(--fg); max-width: 46rem; margin: 2.5rem auto; padding: 0 1.25rem; }}
324  h1 {{ letter-spacing: -0.02em; }}
325  h2 {{ margin-top: 2rem; padding-top: 1rem; border-top: 1px solid var(--line); letter-spacing: -0.01em; }}
326  li {{ color: var(--muted); }}
327  code {{ font: 0.875em ui-monospace, monospace; color: var(--fg); background: var(--code); padding: 0.1em 0.35em; border-radius: 4px; }}
328  a {{ color: var(--link); text-underline-offset: 3px; }}
329</style>
330<nav><a href="{back}">← API reference</a></nav>
331{html}"#
332        ),
333    ))
334}
335
336/// The changelog as Markdown: each released version's breaking changes, newest first, as the
337/// PHP package's `api:changelog` writes it. `unreleased` also lists versions newer than the
338/// latest. Empty while versioning is off or Fusion Stack is not registered.
339#[must_use]
340pub fn markdown(unreleased: bool) -> String {
341    let Some(registry) = crate::STATE.get().and_then(|state| state.registry.as_ref()) else {
342        return String::new();
343    };
344    let now = time::now();
345    let history: Vec<_> = registry
346        .history()
347        .into_iter()
348        .filter(|(version, _)| unreleased || !registry.is_unreleased(version))
349        .collect();
350    let guide = registry
351        .upgrade_guide_url
352        .as_ref()
353        .map(|url| format!(" See the [upgrade guide]({url})."))
354        .unwrap_or_default();
355    let mut lines = vec![
356        "# Changelog".to_owned(),
357        String::new(),
358        format!(
359            "Breaking changes in each API version, newest first. Requests choose a version with the `{}` header.{guide}",
360            header_name()
361        ),
362    ];
363    let oldest = history.len().saturating_sub(1);
364    for (index, (version, changes)) in history.iter().enumerate() {
365        lines.extend([String::new(), format!("## {version}"), String::new()]);
366        let status = registry.status(version, now);
367        if !status.is_empty() {
368            let mut characters = status.chars();
369            let first = characters
370                .next()
371                .map(|c| c.to_uppercase().collect::<String>());
372            lines.extend([
373                format!("_{}{}._", first.unwrap_or_default(), characters.as_str()),
374                String::new(),
375            ]);
376        }
377        if changes.is_empty() {
378            lines.push(
379                if index == oldest {
380                    "The first version."
381                } else {
382                    "No breaking changes."
383                }
384                .to_owned(),
385            );
386            continue;
387        }
388        for change in *changes {
389            lines.push(format!("- {}", describe(change.as_ref(), version)));
390        }
391    }
392    lines.join("\n") + "\n"
393}
394
395/// `Api-Version`, as the header is written.
396fn header_name() -> String {
397    HEADER
398        .split('-')
399        .map(|part| {
400            let mut characters = part.chars();
401            characters
402                .next()
403                .map(|first| first.to_uppercase().chain(characters).collect::<String>())
404                .unwrap_or_default()
405        })
406        .collect::<Vec<_>>()
407        .join("-")
408}
409
410/// The change's description, or what it does to routes when it has none.
411fn describe(change: &dyn VersionChange, version: &ApiVersion) -> String {
412    if !change.description().is_empty() {
413        return change.description().to_owned();
414    }
415    let route = |pattern: &&str| {
416        if pattern.contains('*') {
417            format!("`{pattern}`")
418        } else {
419            (*pattern).to_owned()
420        }
421    };
422    let legacy: Vec<&str> = change
423        .legacy_handlers()
424        .into_iter()
425        .map(|(pattern, _)| pattern)
426        .collect();
427    let parts: Vec<String> = change
428        .added_routes()
429        .iter()
430        .map(|r| format!("Added {}", route(r)))
431        .chain(
432            change
433                .removed_routes()
434                .iter()
435                .map(|r| format!("Removed {}", route(r))),
436        )
437        .chain(
438            change
439                .unavailable_to_older_versions()
440                .iter()
441                .map(|r| format!("{} is unavailable to versions before {version}", route(r))),
442        )
443        .chain(legacy.iter().map(|r| {
444            format!(
445                "{} changed; versions before {version} keep the previous behaviour",
446                route(r)
447            )
448        }))
449        .collect();
450    if parts.is_empty() {
451        "A breaking change.".to_owned()
452    } else {
453        parts.join("; ")
454    }
455}
456
457/// Markdown as HTML, dropping raw HTML and links to anything but web and mail addresses, as
458/// the PHP package renders it with `html_input: strip` and `allow_unsafe_links: false`.
459fn markdown_to_html(markdown: &str) -> String {
460    use pulldown_cmark::{Event, Parser, Tag};
461
462    let events = Parser::new(markdown).filter_map(|event| match event {
463        Event::Html(_) | Event::InlineHtml(_) => None,
464        Event::Start(Tag::Link {
465            link_type,
466            dest_url,
467            title,
468            id,
469        }) => {
470            let lower = dest_url.to_lowercase();
471            let unsafe_link = ["javascript:", "vbscript:", "file:", "data:"]
472                .iter()
473                .any(|scheme| lower.starts_with(scheme));
474            Some(Event::Start(Tag::Link {
475                link_type,
476                dest_url: if unsafe_link { "".into() } else { dest_url },
477                title,
478                id,
479            }))
480        }
481        event => Some(event),
482    });
483    let mut html = String::new();
484    pulldown_cmark::html::push_html(&mut html, events);
485    html
486}
487
488fn scalar(state: &State, documents: &[Document]) -> Response {
489    let options = &state.config.docs.scalar_config;
490    // The page is the application's own, so Scalar's toolbar and AI assistant, which promote
491    // Scalar's services, are off unless the application turns them on.
492    let mut configuration = Map::new();
493    configuration.insert("showDeveloperTools".into(), json!("never"));
494    configuration.insert("agent".into(), json!({ "disabled": true }));
495    if !options.contains_key("theme") && !options.contains_key("customCss") {
496        configuration.insert("theme".into(), json!("none"));
497        configuration.insert("customCss".into(), json!(SCALAR_CSS));
498    }
499    for (key, value) in options {
500        configuration.insert(key.clone(), value.clone());
501    }
502    configuration.insert(
503        "sources".into(),
504        Value::Array(
505            documents
506                .iter()
507                .map(|document| {
508                    json!({ "title": document.title, "slug": document.slug, "url": document.url, "default": document.default })
509                })
510                .collect(),
511        ),
512    );
513    configuration.insert("metaData".into(), json!({ "title": title(state) }));
514    let script = escape(&state.config.docs.scalar_url);
515    let configuration = json_in_html(&Value::Object(configuration));
516    page(
517        &title(state),
518        &format!(
519            "<div id=\"app\"></div>\n<script src=\"{script}\"></script>\n<script>Scalar.createApiReference('#app', {configuration})</script>"
520        ),
521    )
522}
523
524/// Redoc shows one document, so a select reloads the page with another version.
525fn redoc(request: &Request, state: &State, documents: &[Document]) -> Response {
526    let query = crate::query_string::parse(request.uri().query().unwrap_or_default());
527    let requested = query.get("version").and_then(Value::as_str).map(slug);
528    let selected = documents
529        .iter()
530        .position(|document| Some(&document.slug) == requested.as_ref())
531        .or_else(|| documents.iter().position(|document| document.default))
532        .unwrap_or(0);
533    let options: String = documents
534        .iter()
535        .enumerate()
536        .map(|(index, document)| {
537            format!(
538                "<option value=\"{}\"{}>{}</option>",
539                escape(&document.slug),
540                if index == selected { " selected" } else { "" },
541                escape(&document.title)
542            )
543        })
544        .collect();
545    let switcher = if state.registry.is_none() {
546        String::new()
547    } else {
548        format!(
549            "<label>Version <select onchange=\"location.search = '?version=' + encodeURIComponent(this.value)\">{options}</select></label>\n<a href=\"{}\">Changelog</a>",
550            escape(&url(request, state, "changelog"))
551        )
552    };
553    let url = json_in_html(&json!(documents.get(selected).map(|d| d.url.as_str())));
554    let script = escape(&state.config.docs.redoc_url);
555    page(
556        &title(state),
557        &format!(
558            r#"<style>
559  body {{ margin: 0; }}
560  header {{ display: flex; gap: 1.25rem; align-items: center; padding: 0.6rem 1.25rem; border-bottom: 1px solid #efe4db; font: 14px system-ui, sans-serif; color: #1c1326; }}
561  header a {{ color: #c2410c; }}
562  header strong {{ margin-right: auto; }}
563</style>
564<header><strong>{}</strong>{switcher}</header>
565<div id="redoc"></div>
566<script src="{script}"></script>
567<script>Redoc.init({url}, {{}}, document.getElementById('redoc'))</script>"#,
568            escape(&title(state))
569        ),
570    )
571}
572
573fn page(title: &str, body: &str) -> Response {
574    let mut http = laravel::axum::http::Response::new(laravel::axum::body::Body::from(format!(
575        "<!doctype html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <title>{}</title>\n</head>\n<body>\n{body}\n</body>\n</html>",
576        escape(title)
577    )));
578    http.headers_mut().insert(
579        laravel::http::header::CONTENT_TYPE,
580        laravel::http::HeaderValue::from_static("text/html; charset=utf-8"),
581    );
582    Response::from_http(http)
583}
584
585/// JSON safe inside a `<script>` element, as PHP's `JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS`.
586/// These characters appear only inside JSON strings, so escaping them everywhere is safe.
587fn json_in_html(value: &Value) -> String {
588    serde_json::to_string(value)
589        .unwrap_or_default()
590        .replace('<', "\\u003C")
591        .replace('>', "\\u003E")
592        .replace('&', "\\u0026")
593        .replace('\'', "\\u0027")
594}
595
596/// HTML-escapes text, as Laravel's `e()`.
597fn escape(text: &str) -> String {
598    text.replace('&', "&amp;")
599        .replace('<', "&lt;")
600        .replace('>', "&gt;")
601        .replace('"', "&quot;")
602        .replace('\'', "&#039;")
603}
604
605/// A query string value, with the characters that would end it encoded.
606fn query_value(value: &str) -> String {
607    value
608        .replace('%', "%25")
609        .replace('&', "%26")
610        .replace('#', "%23")
611        .replace('+', "%2B")
612        .replace(' ', "%20")
613}
614
615#[cfg(test)]
616mod tests {
617    use super::*;
618
619    #[test]
620    fn slugs_versions_for_scalar() {
621        assert_eq!(slug("2026-11-30.atlas"), "2026-11-30-atlas");
622        assert_eq!(slug("2026-06-01"), "2026-06-01");
623    }
624
625    #[test]
626    fn strips_raw_html_and_unsafe_links() {
627        let html = markdown_to_html(
628            "<script>alert(1)</script>\n\n- a <img src=x onerror=alert(1)> [x](javascript:alert(1)) [y](https://e.org)",
629        );
630        assert!(!html.contains("<script>"), "{html}");
631        assert!(!html.contains("<img"), "{html}");
632        assert!(!html.contains("javascript:"), "{html}");
633        assert!(html.contains(r#"<a href="https://e.org">y</a>"#), "{html}");
634    }
635
636    #[test]
637    fn keeps_json_inside_script_elements() {
638        assert_eq!(
639            json_in_html(&json!({ "css": "</style><b>'&'" })),
640            r#"{"css":"\u003C/style\u003E\u003Cb\u003E\u0027\u0026\u0027"}"#
641        );
642    }
643}