Skip to main content

rustango_cms/api/
pages.rs

1//! `GET /api/v2/pages/` + `GET /api/v2/pages/{id}/`.
2//!
3//! Lists + retrieves published pages over JSON.
4//!
5//! Every surface here is viewer-aware. `detail` runs
6//! [`crate::view_restriction_guard`] and answers a denial with 401 / 403;
7//! `list` (and its `?child_of=` / `?descendant_of=` / `?ancestor_of=`
8//! filters), `find` and the `children` summaries all drop what the caller
9//! may not see via [`crate::view_restriction::denied_page_ids`]. `find`
10//! answers a gated page and a missing one identically, so it cannot be
11//! used to probe for hidden URLs.
12
13// Our extractors, not axum's: they refuse a malformed value in the same
14// JSON envelope as everything else. See `query::Query`.
15use crate::api::query::{Path, Query};
16use axum::http::{HeaderMap, StatusCode};
17use axum::response::{IntoResponse, Response};
18use axum::Json;
19use rustango::core::Column as _;
20use rustango::extractors::{SessionUser, Tenant};
21use rustango::sql::FetcherPool as _;
22use serde::Deserialize;
23
24use super::query as q;
25use crate::page::{Page, PageStatus};
26use crate::page_type::{find_handler, PageTypeHandler};
27use crate::page_type_model::PageType;
28
29/// Per-endpoint filters layered on top of [`crate::api::query::ListQuery`].
30#[derive(Debug, Default, Deserialize)]
31pub struct PageFilters {
32    /// `?type=cms_pages.HomePage` — handler type_name match.
33    #[serde(default, deserialize_with = "q::empty_string_as_none")]
34    pub r#type: Option<String>,
35    /// `?child_of=N` — direct children of page N.
36    #[serde(default, deserialize_with = "q::empty_as_none")]
37    pub child_of: Option<i64>,
38    /// `?descendant_of=N` — every descendant of page N (excluding N).
39    #[serde(default, deserialize_with = "q::empty_as_none")]
40    pub descendant_of: Option<i64>,
41    /// `?ancestor_of=N` — every ancestor of page N (excluding N).
42    #[serde(default, deserialize_with = "q::empty_as_none")]
43    pub ancestor_of: Option<i64>,
44    /// `?translation_of=N` — sibling locale variants of page N.
45    #[serde(default, deserialize_with = "q::empty_as_none")]
46    pub translation_of: Option<i64>,
47    /// `?locale=en` — restrict to a specific locale.
48    #[serde(default, deserialize_with = "q::empty_string_as_none")]
49    pub locale: Option<String>,
50    /// `?tag=release` — restrict to pages carrying this tag.
51    #[serde(default, deserialize_with = "q::empty_string_as_none")]
52    pub tag: Option<String>,
53    /// `?id_in=3,9,14` — fetch several pages by id in one request.
54    ///
55    /// Without it, hydrating a resolved menu (which returns `page_id`
56    /// per node and nothing else) costs one request per item. Unknown
57    /// and non-public ids are simply absent from the result rather than
58    /// an error, so a stale client id degrades to a missing row instead
59    /// of failing the whole batch. Bounded by `?limit=` like any list.
60    #[serde(default, deserialize_with = "q::empty_string_as_none")]
61    pub id_in: Option<String>,
62}
63
64/// Combined query string for `GET /api/v2/pages/`.
65#[derive(Debug, Default, Deserialize)]
66pub struct PageListQuery {
67    #[serde(flatten)]
68    pub list: q::ListQuery,
69    #[serde(flatten)]
70    pub filters: PageFilters,
71}
72
73/// Query string for `GET /api/v2/pages/find/`.
74#[derive(Debug, Default, Deserialize)]
75pub struct FindQuery {
76    /// Public URL path to resolve, e.g. `/about` (with or without a
77    /// trailing slash).
78    #[serde(default, deserialize_with = "q::empty_string_as_none")]
79    pub html_path: Option<String>,
80}
81
82/// Query for the page detail endpoint.
83#[derive(Default, Deserialize)]
84pub struct DetailQuery {
85    /// A signed preview token (from the admin mint endpoint).
86    /// When valid for this page id, the endpoint serves the page even
87    /// if it isn't published, so a decoupled frontend can render the
88    /// draft.
89    #[serde(default, deserialize_with = "q::empty_string_as_none")]
90    pub preview_token: Option<String>,
91    /// `?locale=fr` — return this locale's content. Overrides from
92    /// `cms_translation` are applied per field, so anything untranslated
93    /// falls back to canonical rather than blanking. An unknown or
94    /// inactive code falls back to the tenant default.
95    ///
96    /// Note this is a *content selector*, unlike the list endpoint's
97    /// `?locale=`, which is a legacy row filter over the deprecated
98    /// `locale_variant_of` column.
99    #[serde(default, deserialize_with = "q::empty_string_as_none")]
100    pub locale: Option<String>,
101    /// `?fields=title,seo_title` — same sparse selection the list
102    /// endpoints accept. It was list-only, so a client fetching one page
103    /// had no way to avoid pulling `extension`, `builder` and the whole
104    /// `children` array. `id` and `meta` are always kept.
105    #[serde(default, deserialize_with = "q::empty_string_as_none")]
106    pub fields: Option<String>,
107}
108
109/// `GET /api/v2/pages/`
110pub async fn list(
111    tenant: Tenant,
112    SessionUser(session_user): SessionUser,
113    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
114    crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
115    Query(qs): Query<PageListQuery>,
116) -> Response {
117    // #members — a public member outranks an admin session, matching
118    // `tree`, `menus::detail` and the public renderer.
119    let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
120    match list_inner(&tenant, viewer, &qs).await {
121        Ok(resp) => resp,
122        Err(e) => {
123            tracing::error!(target: "rustango_cms::api", error = %e, "pages list failed");
124            crate::api::error::ApiError::internal().into_response()
125        }
126    }
127}
128
129async fn list_inner(
130    tenant: &Tenant,
131    viewer: Option<&rustango::tenancy::auth::User>,
132    qs: &PageListQuery,
133) -> Result<Response, rustango::sql::ExecError> {
134    let pool = tenant.pool();
135    let (limit, offset) = q::paginate(&qs.list);
136    let fields = q::field_set(&qs.list);
137    let orderings = match q::parse_order_in(&qs.list, &PAGE_ORDER_FIELDS) {
138        Ok(v) => v,
139        Err(msg) => return Ok(crate::api::error::ApiError::bad_request(msg).into_response()),
140    };
141
142    // Load every public page once. Tenants stay small; downstream
143    // filters are applied in memory so the API can serve compound
144    // queries (descendant_of + locale + search + order) without
145    // composing one mega-WHERE clause.
146    //
147    // Public means `published` **or** `archived` (`PageStatus::is_public`),
148    // matching the renderer, the sitemap, the tree, the child summaries
149    // and the menu resolver. This was the last surface filtering to
150    // `published` alone, which made it describe a different site than
151    // every other endpoint: an archived page resolved at its URL, showed
152    // up in the tree and in a menu, and was absent here — so
153    // `?id_in=` could not even re-fetch a page a menu had just named.
154    let mut pages: Vec<Page> = Page::objects()
155        .where_(Page::status.is_in([
156            PageStatus::Published.as_str().to_owned(),
157            PageStatus::Archived.as_str().to_owned(),
158        ]))
159        // A deterministic base order. Without it the driver decides, and
160        // on Postgres an unrelated UPDATE moves a row to the end of the
161        // heap — so a client walking `?offset=` could see one page twice
162        // and miss another. `id` is unique, which is what the in-memory
163        // comparators below lack.
164        .order_by(&[("id", false)])
165        .fetch(pool)
166        .await?;
167
168    // Legacy per-locale variant trees were standalone copies of the whole
169    // site, so leaving them in returned it once per locale. Every other
170    // surface drops them (#275); this one did not.
171    //
172    // `?translation_of=` is the exception — it exists precisely to list
173    // those rows, so it opts out.
174    if qs.filters.translation_of.is_none() {
175        pages.retain(|p| p.locale_variant_of.is_none());
176    }
177
178    // #members — drop what this viewer may not see, *before* any filter
179    // runs. This endpoint applied no restrictions at all, so every gated
180    // page's title, SEO text and URL was public — and `?descendant_of=`
181    // against a member-only section dumped the lot, the very thing
182    // `tree/?root=` refuses. Batched and subtree-aware via `path`, so a
183    // gated ancestor takes its descendants with it.
184    let triples: Vec<(i64, String, i64)> = pages
185        .iter()
186        .map(|p| {
187            (
188                p.id.get().copied().unwrap_or_default(),
189                p.path.clone(),
190                p.page_type_id,
191            )
192        })
193        .collect();
194    let denied = crate::view_restriction::denied_page_ids(pool, viewer, &triples).await;
195    if !denied.is_empty() {
196        pages.retain(|p| !denied.contains(&p.id.get().copied().unwrap_or_default()));
197    }
198
199    // ----- type filter --------------------------------------------------
200    if let Some(type_name) = qs.filters.r#type.as_deref().filter(|s| !s.is_empty()) {
201        // `cms_page_type.type_name` stores the bare handler name and
202        // keeps `app_label` in its own column, so the dotted form the
203        // doc comment advertises (`cms_pages.HomePage`) could never
204        // match. Accept both rather than making the documentation wrong.
205        let bare = type_name.rsplit('.').next().unwrap_or(type_name);
206        if let Some(pt) = lookup_page_type(pool, bare).await? {
207            let pt_id = pt.id.get().copied().unwrap_or_default();
208            pages.retain(|p| p.page_type_id == pt_id);
209        } else {
210            pages.clear();
211        }
212    }
213
214    // #changes — `?updated_since=` so a polling client can ask for only
215    // what moved, instead of re-fetching the collection and diffing it.
216    let updated_since = match crate::api::query::parse_updated_since(&qs.list) {
217        Ok(v) => v,
218        Err(msg) => return Ok(crate::api::error::ApiError::bad_request(msg).into_response()),
219    };
220    if let Some(since) = updated_since {
221        pages.retain(|p| p.updated_at.get().copied().is_some_and(|t| t >= since));
222    }
223
224    // ----- explicit id set ----------------------------------------------
225    if let Some(raw) = qs.filters.id_in.as_deref() {
226        // An *unknown* id is deliberately absent rather than an error, so
227        // one stale id costs a batch one row instead of all of them. A
228        // segment that is not a number at all is a different thing: it
229        // was never an id, so it cannot be stale, and dropping it made a
230        // client's own bug look like a deleted page — the worst possible
231        // reading, on the endpoint whose whole job is hydrating a list of
232        // ids a menu just handed over.
233        let mut wanted = std::collections::HashSet::new();
234        for seg in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
235            match seg.parse::<i64>() {
236                Ok(id) => {
237                    wanted.insert(id);
238                }
239                Err(_) => {
240                    return Ok(crate::api::error::ApiError::bad_request(format!(
241                        "`id_in` expects comma-separated integers; `{seg}` is not one",
242                    ))
243                    .into_response())
244                }
245            }
246        }
247        pages.retain(|p| p.id.get().copied().is_some_and(|id| wanted.contains(&id)));
248    }
249
250    // ----- tree filters -------------------------------------------------
251    if let Some(parent_id) = qs.filters.child_of {
252        pages.retain(|p| p.parent_id == Some(parent_id));
253    }
254    // The anchors are resolved against the *visible* set, not the whole
255    // table. Looking them up unrestricted would let a caller pivot off a
256    // page they cannot see: the anchor's path is all `?descendant_of=`
257    // needs, so an unfiltered lookup re-opened the leak the filter above
258    // just closed.
259    if let Some(root_id) = qs.filters.descendant_of {
260        if let Some(prefix) = visible_path(&pages, root_id) {
261            pages.retain(|p| p.path != prefix && p.path.starts_with(&prefix));
262        } else {
263            pages.clear();
264        }
265    }
266    if let Some(leaf_id) = qs.filters.ancestor_of {
267        if let Some(path) = visible_path(&pages, leaf_id) {
268            let ancestor_paths: std::collections::HashSet<String> = ancestor_paths_of(&path);
269            pages.retain(|p| ancestor_paths.contains(&p.path));
270        } else {
271            pages.clear();
272        }
273    }
274
275    // ----- translation_of (locale-variant siblings) ---------------------
276    if let Some(canon_id) = qs.filters.translation_of {
277        // The *other* translations, not the anchor — asking for a page's
278        // translations and getting the page back is the only useful
279        // answer.
280        pages.retain(|p| p.locale_variant_of == Some(canon_id));
281    }
282
283    // ----- locale -------------------------------------------------------
284    if let Some(code) = qs.filters.locale.as_deref().filter(|s| !s.is_empty()) {
285        // Resolve through the shared helper: it honours `active` and
286        // falls back to the tenant default on an unknown code, which is
287        // what `tree`, `detail` and `menus` all do. This used to query
288        // `cms_locale` directly with no `active` filter and *empty the
289        // list* on an unknown code — two divergences from every other
290        // endpoint in one branch.
291        let locale = crate::translation::resolve_locale(pool, Some(code)).await?;
292        if let Some(loc) = locale {
293            let loc_id = loc.id.get().copied().unwrap_or_default();
294            if loc.is_default {
295                // Canonical content lives on the page row; default-locale
296                // filter is a no-op (every page is "in" the default).
297            } else {
298                // For non-default locales, a page is "in" the locale if
299                // it's a `locale_variant_of` chain rooted in that locale.
300                // V1 ships a simpler proxy: only return rows explicitly
301                // marked as variants. Future revisions can join the
302                // translation table to surface partially-translated rows.
303                pages.retain(|p| {
304                    p.locale_variant_of.is_some() && {
305                        // Fetch the canonical's locale would require a join;
306                        // for v1 we accept the variant rows themselves and
307                        // leave canonical filtering as a follow-up.
308                        let _ = loc_id;
309                        true
310                    }
311                });
312            }
313        }
314    }
315
316    // ----- tag ----------------------------------------------------------
317    if let Some(raw) = qs.filters.tag.as_deref().filter(|s| !s.is_empty()) {
318        let tagged: std::collections::HashSet<i64> = crate::page_tag::pages_with_tag(pool, raw)
319            .await?
320            .into_iter()
321            .collect();
322        pages.retain(|p| p.id.get().copied().is_some_and(|id| tagged.contains(&id)));
323    }
324
325    // ----- search -------------------------------------------------------
326    // Capture the raw needle so the promotion-pinning step below can run
327    // off the same value the title/slug/url_path filter uses.
328    let search_needle = qs.list.search.as_deref().filter(|s| !s.trim().is_empty());
329    // #408 — relevance-ranked search. An installed external backend
330    // (Elasticsearch) takes priority; else Postgres full-text; else
331    // (None) the substring filter below. The ranked hit list also drives
332    // result order (relevance by default).
333    let mut fts_ordered = false;
334    if let Some(needle) = search_needle {
335        crate::search_promotion::log_public_query(pool, needle, offset);
336        let ranked = if let Some(b) = crate::search::backend() {
337            Some(b.search(&tenant.org.slug, needle, 1000).await)
338        } else {
339            crate::search::search_page_ids(pool, needle, 1000).await
340        };
341        // A ranked hit OR a substring match (#702): the ranked backend finds
342        // stemmed words but not a partial word, slug fragment or URL path,
343        // so it adds to the substring match every backend runs rather than
344        // replacing it. Ranked hits lead, in rank order; substring-only
345        // hits follow in their existing order (the sort is stable).
346        let rank: Option<std::collections::HashMap<i64, usize>> =
347            ranked.map(|r| r.iter().enumerate().map(|(i, id)| (*id, i)).collect());
348        let n = crate::api::search::fold(needle);
349        pages.retain(|p| {
350            rank.as_ref()
351                .is_some_and(|r| p.id.get().copied().is_some_and(|id| r.contains_key(&id)))
352                || crate::api::search::contains_folded(&p.title, &n)
353                || crate::api::search::contains_folded(&p.slug, &n)
354                || crate::api::search::contains_folded(&p.url_path, &n)
355        });
356        if let Some(rank) = &rank {
357            pages.sort_by_key(|p| {
358                p.id.get()
359                    .copied()
360                    .and_then(|id| rank.get(&id).copied())
361                    .unwrap_or(usize::MAX)
362            });
363            fts_ordered = true;
364        }
365    }
366
367    // ----- ordering -----------------------------------------------------
368    // FTS already ordered by relevance; an explicit ?order= still wins.
369    // Drop specs naming a field this endpoint cannot sort on, *before*
370    // deciding whether an ordering was requested. `parse_order` accepts
371    // any name and `compare_pages` skipped unknown ones per pair, so
372    // `random` reshuffles per request, so an offset into it is not a
373    // second page — it is a fresh shuffle with rows skipped. Refuse the
374    // combination rather than quietly returning overlapping garbage.
375    if orderings.iter().any(|o| o.random) && offset > 0 {
376        return Ok(crate::api::error::ApiError::bad_request(
377            "`order=random` cannot be paged — omit `offset`, or order by a field",
378        )
379        .into_response());
380    }
381
382    if fts_ordered && orderings.is_empty() {
383        // keep the relevance order from the FTS hit list
384    } else if orderings.iter().any(|o| o.random) {
385        // Random is one-shot per request; cheap on bounded list size.
386        use rand::seq::SliceRandom as _;
387        pages.shuffle(&mut rand::rng());
388    } else if !orderings.is_empty() {
389        pages.sort_by(|a, b| compare_pages(a, b, &orderings));
390    } else {
391        // Default: most recently published first, then title.
392        pages.sort_by(|a, b| {
393            b.published_at
394                .cmp(&a.published_at)
395                .then_with(|| a.title.cmp(&b.title))
396                // Unique tiebreaker: `sort_by` is stable, so without one
397                // tied rows keep the fetch order and paging is only as
398                // stable as the driver happens to be.
399                .then_with(|| a.id.get().cmp(&b.id.get()))
400        });
401    }
402
403    // ----- search promotions (#289) -------------------------------------
404    // After the search filter + ordering settle, pin editor-promoted
405    // pages to the front of the list. Skipped when the request didn't
406    // include a search needle (no query to look up), when no
407    // SearchQuery row matches the normalized form (visitor's query
408    // hasn't been logged + promoted), or when the query has no
409    // promotions attached.
410    //
411    // Promotion order: pages are inserted in `sort_order` ascending,
412    // de-duplicated against whatever was already at the head of the
413    // filtered list (a page that organically ranked first AND was
414    // promoted stays where the promotion put it, doesn't appear
415    // twice).
416    if let Some(needle) = search_needle {
417        if let Ok(Some(q)) = crate::search_promotion::find_by_query(pool, needle).await {
418            let query_id = q.id.get().copied().unwrap_or_default();
419            if query_id != 0 {
420                if let Ok(promos) =
421                    crate::search_promotion::promotions_for_query(pool, query_id).await
422                {
423                    // Pull each promoted page out of the filtered list
424                    // (preserving its full Page row — we still want
425                    // status, published_at, etc. as ranked) and reinsert
426                    // at the front in promotion order. Promoted pages
427                    // that aren't in the filtered result set (because
428                    // they failed the type/locale/tag/search filter)
429                    // stay dropped; the promotion table doesn't
430                    // override the visitor's filter scope.
431                    let mut pinned: Vec<Page> = Vec::with_capacity(promos.len());
432                    for p in &promos {
433                        if let Some(pos) = pages
434                            .iter()
435                            .position(|page| page.id.get().copied() == Some(p.page_id))
436                        {
437                            pinned.push(pages.remove(pos));
438                        }
439                    }
440                    // Splice pinned to the front in promotion order.
441                    for (i, page) in pinned.into_iter().enumerate() {
442                        pages.insert(i, page);
443                    }
444                }
445            }
446        }
447    }
448
449    // ----- pagination ---------------------------------------------------
450    let total_count = pages.len();
451    let window: Vec<&Page> = pages.iter().skip(offset).take(limit).collect();
452
453    // #408 — a fuzzy "did you mean?" when an FTS search matched nothing
454    // but a near-match title exists (Postgres + pg_trgm only; None
455    // otherwise). Only offered for FTS-backed searches that came up empty.
456    // #408 — the suggestion comes from a similarity query that joins
457    // nothing and spans `published + archived`, so left alone it will
458    // happily name a member-only or archived page by title. Confirm the
459    // suggested title actually belongs to something this caller can see
460    // before offering it. One extra query, and only on a zero-hit search.
461    let did_you_mean = match (fts_ordered, total_count, search_needle) {
462        (true, 0, Some(needle)) => match crate::search::did_you_mean(pool, needle, 0.3).await {
463            Some(title) => visible_title(pool, viewer, &title).await,
464            None => None,
465        },
466        _ => None,
467    };
468
469    // ----- serialize ----------------------------------------------------
470    let type_names = page_type_names(pool).await?;
471    let mut items = Vec::with_capacity(window.len());
472    for p in window {
473        let mut obj = serialize_summary(p, &type_names);
474        // Validated against the first serialized row rather than a
475        // hand-written list, so it cannot drift from what we return.
476        if let Err(msg) = q::validate_fields(fields.as_ref(), &obj) {
477            return Ok(crate::api::error::ApiError::bad_request(msg).into_response());
478        }
479        q::apply_fields(&mut obj, fields.as_ref());
480        items.push(serde_json::Value::Object(obj));
481    }
482
483    let envelope = q::ListEnvelope {
484        meta: q::ListMeta {
485            did_you_mean,
486            ..q::ListMeta::paged(total_count, limit, offset)
487        },
488        items,
489    };
490    Ok(Json(envelope).into_response())
491}
492
493/// `GET /api/v2/pages/{id}/`
494pub async fn detail(
495    tenant: Tenant,
496    SessionUser(session_user): SessionUser,
497    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
498    crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
499    headers: HeaderMap,
500    Path(id): Path<i64>,
501    Query(qs): Query<DetailQuery>,
502) -> Response {
503    // #members — gate against a public member OR an admin (member wins).
504    let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
505    // #430 — a valid preview token for THIS page unlocks draft access.
506    let allow_draft = qs
507        .preview_token
508        .as_deref()
509        .and_then(|t| crate::preview_token::verify(&tenant.org.slug, t, chrono::Utc::now().timestamp()))
510        == Some(id);
511    match detail_inner(
512        &tenant,
513        viewer,
514        &headers,
515        id,
516        allow_draft,
517        qs.locale.as_deref(),
518        qs.fields.as_deref(),
519    )
520    .await
521    {
522        Ok(resp) => resp,
523        Err(e) => {
524            tracing::error!(target: "rustango_cms::api", error = %e, "page detail failed");
525            crate::api::error::ApiError::internal().into_response()
526        }
527    }
528}
529
530/// `GET /api/v2/pages/find/?html_path=/about` — resolve a public URL
531/// path to its page and 302-redirect to the detail endpoint. Resolves **published** pages only; view
532/// restrictions are enforced by the detail endpoint the client follows
533/// to (`find` itself doesn't pre-check them).
534pub async fn find(
535    tenant: Tenant,
536    SessionUser(session_user): SessionUser,
537    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
538    crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
539    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
540    Query(qs): Query<FindQuery>,
541) -> Response {
542    let Some(html_path) = qs.html_path.filter(|p| !p.is_empty()) else {
543        return crate::api::error::ApiError::bad_request("missing `html_path` query parameter")
544            .into_response();
545    };
546    let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
547    let carry = carried_query(raw_query.as_deref());
548    match find_inner(&tenant, viewer, &html_path, &carry).await {
549        Ok(resp) => resp,
550        Err(e) => {
551            tracing::error!(target: "rustango_cms::api", error = %e, "page find failed");
552            crate::api::error::ApiError::internal().into_response()
553        }
554    }
555}
556
557/// The part of `find/`'s own query string that the detail URL should
558/// inherit, rendered as `?a=b&c=d` (or empty).
559///
560/// A client resolves its route with `find/` and lets `fetch` follow the
561/// 302 — that is the whole point of answering with a redirect. But the
562/// `Location` named only the id, so every other parameter was dropped in
563/// flight: `find/?html_path=/&locale=fr` returned the **English** page,
564/// and a SPA had no way to ask for anything else in one hop. Worse, it
565/// looked like it had worked; only `meta.locale` gave it away.
566///
567/// `html_path` is consumed here and must not travel. Everything else is
568/// forwarded verbatim, including parameters this endpoint knows nothing
569/// about — the detail endpoint ignores names it does not recognise, and
570/// hard-coding a list here would silently drop the next one added.
571fn carried_query(raw: Option<&str>) -> String {
572    let Some(raw) = raw.filter(|r| !r.is_empty()) else {
573        return String::new();
574    };
575    let kept: Vec<&str> = raw
576        .split('&')
577        .filter(|pair| !pair.is_empty())
578        .filter(|pair| {
579            let name = pair.split('=').next().unwrap_or("");
580            name != "html_path"
581        })
582        .collect();
583    if kept.is_empty() {
584        String::new()
585    } else {
586        format!("?{}", kept.join("&"))
587    }
588}
589
590async fn find_inner(
591    tenant: &Tenant,
592    viewer: Option<&rustango::tenancy::auth::User>,
593    html_path: &str,
594    carry: &str,
595) -> Result<Response, rustango::sql::ExecError> {
596    let pool = tenant.pool();
597    // url_path is stored without a trailing slash (e.g. "/about"); accept
598    // either form from callers by trying the path and its slash-variant.
599    let mut rows: Vec<Page> = Page::objects()
600        .where_(Page::url_path.eq(html_path))
601        .fetch(pool)
602        .await?;
603    if rows.is_empty() {
604        let alt = if let Some(stripped) = html_path.strip_suffix('/') {
605            stripped.to_owned()
606        } else {
607            format!("{html_path}/")
608        };
609        rows = Page::objects()
610            .where_(Page::url_path.eq(alt))
611            .fetch(pool)
612            .await?;
613    }
614    // `is_public()`, not `Published`: `list`, `tree` and `detail` all
615    // serve archived pages, and the tree hands out a `detail_url` for
616    // one. Matching on `Published` alone left `find` as the single
617    // endpoint that 404'd a page the rest of the API was happy to
618    // return — the same contradiction archived pages already caused on
619    // `detail`, one endpoint over.
620    let hit = rows
621        .into_iter()
622        .find(|p| PageStatus::str_is_public(&p.status));
623
624    // #members — a gated page must be indistinguishable from a missing
625    // one. Redirecting for one and 404-ing for the other turned this
626    // endpoint into an oracle: an anonymous caller could walk URLs and
627    // learn both which member-only pages exist and their ids, straight
628    // out of the `Location` header.
629    let id = match hit {
630        Some(p) => {
631            let pid = p.id.get().copied().unwrap_or_default();
632            let denied = crate::view_restriction::denied_page_ids(
633                pool,
634                viewer,
635                &[(pid, p.path.clone(), p.page_type_id)],
636            )
637            .await;
638            if denied.contains(&pid) {
639                None
640            } else {
641                Some(pid)
642            }
643        }
644        None => None,
645    };
646    match id {
647        // 302 Found → detail endpoint (which enforces view restrictions).
648        Some(id) => Ok((
649            StatusCode::FOUND,
650            [(
651                axum::http::header::LOCATION,
652                format!("/api/v2/pages/{id}/{carry}"),
653            )],
654        )
655            .into_response()),
656        // `not_found` appends " not found", so this must be the noun
657        // alone — and it must be the *same* noun the detail endpoint
658        // uses, because a gated page and a missing one are deliberately
659        // indistinguishable here.
660        None => Ok(crate::api::error::ApiError::not_found("page").into_response()),
661    }
662}
663
664async fn detail_inner(
665    tenant: &Tenant,
666    viewer: Option<&rustango::tenancy::auth::User>,
667    headers: &HeaderMap,
668    id: i64,
669    allow_draft: bool,
670    locale_code: Option<&str>,
671    fields: Option<&str>,
672) -> Result<Response, rustango::sql::ExecError> {
673    let pool = tenant.pool();
674    let Some(page) = lookup_page(pool, id).await? else {
675        return Ok(crate::api::error::ApiError::not_found("page").into_response());
676    };
677    // Public means `published` **or** `archived` — the same
678    // `PageStatus::is_public` test the renderer and sitemap use. Serving
679    // only `published` here made `detail` 404 pages that `tree` and
680    // `children` list *and* hand out a `detail_url` for, so every
681    // archived node advertised a dead link. Drafts still 404 unless a
682    // valid preview token unlocked them (#430).
683    let is_public = PageStatus::str_is_public(&page.status);
684    if !is_public && !allow_draft {
685        return Ok(crate::api::error::ApiError::not_found("page").into_response());
686    }
687    // Honour view restrictions — the same decision the public renderer
688    // makes, reported the way a JSON client can act on.
689    //
690    // The HTML path answers a denial with `303 → /members/login`, which
691    // is right for a browser and useless here: `fetch()` follows it and
692    // the caller ends up with a login page under status 200, with no
693    // signal that it is unauthenticated. So the API renders the same
694    // `Denial` as a status code instead.
695    if let Some(denial) =
696        crate::view_restriction_guard::decide(tenant, &page, viewer, headers).await
697    {
698        use crate::view_restriction_guard::Denial;
699        return Ok(match denial {
700            Denial::NeedsLogin => crate::api::error::ApiError::unauthenticated(),
701            Denial::Forbidden => crate::api::error::ApiError::forbidden(),
702            Denial::NeedsPassword { .. } => crate::api::error::ApiError::password_required(),
703        }
704        .into_response());
705    }
706
707    // #75 — an alias serves the source's content under its own URL. The
708    // gating above ran against the alias row (its own restrictions), and
709    // only the *content* is borrowed. Without this, detail returned the
710    // stale title copied at creation, no `extension` and no `builder`,
711    // while `tree` and the renderer all showed the source's live content.
712    let mut alias_owned = None;
713    if let Some(source_id) = page.alias_of {
714        match lookup_page(pool, source_id).await? {
715            Some(src) => alias_owned = Some(crate::page::alias_hybrid(&page, &src)),
716            None => tracing::warn!(
717                target: "rustango_cms::api",
718                alias_id = ?page.id.get().copied(),
719                source_id,
720                "alias source missing — serving the alias row verbatim",
721            ),
722        }
723    }
724    let page = alias_owned.as_ref().unwrap_or(&page);
725
726    let type_name = page_type_names(pool)
727        .await?
728        .get(&page.page_type_id)
729        .cloned()
730        .unwrap_or_default();
731    // Default locale resolves to `None` — canonical content already is
732    // the default-locale content, so the overlay would be a wasted query.
733    let locale = crate::translation::resolve_locale(pool, locale_code)
734        .await
735        .ok()
736        .flatten();
737    // Only a non-default locale needs an overlay — canonical content
738    // already *is* the default-locale content.
739    let locale_id = locale
740        .as_ref()
741        .filter(|l| !l.is_default)
742        .and_then(|l| l.id.get().copied());
743    let mut obj =
744        detail_object_with_type(pool, page, &type_name, None, None, locale_id, viewer).await;
745
746    echo_locale(&mut obj, locale.as_ref());
747
748    // Sparse selection, matching the list endpoints.
749    let keep = fields.map(|raw| -> std::collections::HashSet<String> {
750        raw.split(',')
751            .map(str::trim)
752            .filter(|s| !s.is_empty())
753            .map(str::to_owned)
754            .collect()
755    });
756    q::apply_fields(&mut obj, keep.as_ref());
757
758    Ok(Json(serde_json::Value::Object(obj)).into_response())
759}
760
761/// Return `title` only if some published page with that title is visible
762/// to `viewer`.
763///
764/// Used to vet a search suggestion before echoing it back — otherwise the
765/// "did you mean?" hint becomes a way to enumerate the titles of pages the
766/// caller is not allowed to see.
767async fn visible_title(
768    pool: &rustango::sql::Pool,
769    viewer: Option<&rustango::tenancy::auth::User>,
770    title: &str,
771) -> Option<String> {
772    let matches: Vec<Page> = Page::objects()
773        .where_(Page::title.eq(title.to_owned()))
774        .where_(Page::status.eq(PageStatus::Published.as_str().to_owned()))
775        .fetch(pool)
776        .await
777        .ok()?;
778    if matches.is_empty() {
779        return None;
780    }
781    let triples: Vec<(i64, String, i64)> = matches
782        .iter()
783        .map(|p| {
784            (
785                p.id.get().copied().unwrap_or_default(),
786                p.path.clone(),
787                p.page_type_id,
788            )
789        })
790        .collect();
791    let denied = crate::view_restriction::denied_page_ids(pool, viewer, &triples).await;
792    triples
793        .iter()
794        .any(|(id, _, _)| !denied.contains(id))
795        .then(|| title.to_owned())
796}
797
798/// The materialized path of `id`, but only if it survived filtering.
799///
800/// Returning `None` for "gated" and for "absent" alike is deliberate: a
801/// filter that behaved differently would answer "does this page exist?"
802/// for pages the caller may not see.
803fn visible_path(pages: &[Page], id: i64) -> Option<String> {
804    pages
805        .iter()
806        .find(|p| p.id.get().copied() == Some(id))
807        .map(|p| p.path.clone())
808}
809
810/// Echo the locale a detail body was built in as `meta.locale`. An
811/// unknown or inactive code falls back to the tenant default silently, so
812/// without this a client cannot tell `?locale=fr` from `?locale=fr-typo`.
813/// Every page detail body carries it, so the page URL's negotiated JSON
814/// stays equal to `/api/v2/pages/{id}/`.
815pub(crate) fn echo_locale(
816    obj: &mut serde_json::Map<String, serde_json::Value>,
817    locale: Option<&crate::locale::Locale>,
818) {
819    if let Some(meta) = obj.get_mut("meta").and_then(|m| m.as_object_mut()) {
820        meta.insert(
821            "locale".to_owned(),
822            locale.map_or(serde_json::Value::Null, |l| serde_json::Value::String(l.code.clone())),
823        );
824    }
825}
826
827/// Build the canonical page-detail object.
828///
829/// Shared by `GET /api/v2/pages/{id}/` and the public `Accept`-negotiated
830/// JSON view, so the two are byte-identical by construction rather than
831/// by discipline — the whole reason the editor's JSON preview can be
832/// trusted to show what a client will actually receive.
833///
834/// The two `Option` parameters are the preview seam. `None` loads from
835/// the database, which is what the saved-row API path wants; `Some(_)`
836/// substitutes *virtual* values built from unsaved editor form state.
837/// Callers that already hold the registry row pass `type_name` directly
838/// to skip the full `cms_page_type` scan `page_type_names` performs.
839///
840/// `locale_id` localizes the result. `None` (or the default locale)
841/// returns canonical content; `Some(id)` overlays that locale's
842/// `cms_translation` rows — scalars (`title`, `seo_*`, extension fields),
843/// per-leaf StreamField overrides, and page-builder text leaves. Every
844/// JSON surface shares this, so localizing here localizes the v2 endpoint
845/// and the `Accept`-negotiated page view together.
846///
847/// Note this deliberately performs **no** access control *on the page
848/// itself*: the published check and `view_restriction_guard::enforce`
849/// live in the callers, because a draft preview must bypass exactly
850/// those gates. `viewer` is used only to filter the `children` listing —
851/// see `child_summaries`.
852pub async fn detail_object_with_type(
853    pool: &rustango::sql::Pool,
854    page: &Page,
855    type_name: &str,
856    extension_override: Option<serde_json::Value>,
857    builder_override: Option<serde_json::Value>,
858    locale_id: Option<i64>,
859    viewer: Option<&rustango::tenancy::auth::User>,
860) -> serde_json::Map<String, serde_json::Value> {
861    let id = page.id.get().copied().unwrap_or_default();
862    // #75 — per-type extension rows and builder documents live against
863    // the *source* for an alias; the alias row has none of its own. Same
864    // resolution the renderer applies (`extension_page_id`).
865    let content_id = page.alias_of.unwrap_or(id);
866    let mut type_names = std::collections::HashMap::new();
867    type_names.insert(page.page_type_id, type_name.to_owned());
868    let mut obj = serialize_summary(page, &type_names);
869
870    // Extension fields via the registered handler. `load_extension`
871    // is opt-in per handler; the default returns `Value::Null`.
872    let handler: Option<Box<dyn PageTypeHandler>> = find_handler(type_name);
873    if let Some(h) = handler {
874        // #442 — expose this page's routable sub-URL patterns so API
875        // consumers can resolve/reverse them client-side. Omitted when
876        // the page type declares none.
877        let routes = h.routes();
878        if !routes.is_empty() {
879            let arr: Vec<serde_json::Value> = routes
880                .iter()
881                .map(|r| serde_json::json!({ "name": r.name, "pattern": r.pattern.as_str() }))
882                .collect();
883            obj.insert("routes".to_owned(), serde_json::Value::Array(arr));
884        }
885        match extension_override {
886            Some(ext) => {
887                if !ext.is_null() {
888                    obj.insert("extension".to_owned(), ext);
889                }
890            }
891            None => match h.load_extension(pool, content_id).await {
892                Ok(ext) if !ext.is_null() => {
893                    obj.insert("extension".to_owned(), ext);
894                }
895                Ok(_) => {}
896                Err(e) => {
897                    tracing::warn!(
898                        target: "rustango_cms::api",
899                        page_id = id,
900                        error = %e,
901                        "load_extension failed in api detail",
902                    );
903                }
904            },
905        }
906    }
907
908    // #572 — page-builder body. When the page type has a published schema
909    // (code type with a UI body, or a UI-created type), expose the filled,
910    // lazily-upgraded values so headless clients render the UI-defined body.
911    // Values only — clients render; no server-side zone HTML here.
912    //
913    // The compiled schema is kept so the localization pass below can reach
914    // the builder's text leaves — they are keyed `builder.<path>`, which
915    // the flat scalar overlay cannot address.
916    let mut compiled_schema = None;
917    match builder_override {
918        Some(values) => {
919            obj.insert("builder".to_owned(), values);
920            if locale_id.is_some() {
921                compiled_schema = crate::page_builder::values::values_for(
922                    pool,
923                    content_id,
924                    page.page_type_id,
925                    None,
926                )
927                .await
928                .map(|(_, c)| c);
929            }
930        }
931        None => {
932            if let Some((values, compiled)) =
933                crate::page_builder::values::values_for(pool, content_id, page.page_type_id, None)
934                    .await
935            {
936                obj.insert("builder".to_owned(), values);
937                compiled_schema = Some(compiled);
938            }
939        }
940    }
941
942    if let Some(lid) = locale_id {
943        localize_detail_object(pool, id, type_name, lid, &mut obj, compiled_schema.as_ref()).await;
944    }
945
946    // Direct children, so a client can walk the site from any page without
947    // first fetching the whole tree. One level only — `/api/v2/pages/tree/`
948    // is the endpoint for depth.
949    obj.insert(
950        "children".to_owned(),
951        serde_json::Value::Array(child_summaries(pool, page, viewer, locale_id).await),
952    );
953
954    obj
955}
956
957/// Most children a detail response will inline.
958///
959/// `tree` caps itself at `MAX_NODES` and says so via `meta.truncated`;
960/// `children` had no equivalent, so a flat blog's homepage returned every
961/// one of its posts on every request — including on each
962/// `Accept: application/json` render of `/`. Clients that need the whole
963/// set have `/api/v2/pages/?child_of=`, which is paged.
964pub const MAX_CHILDREN: usize = 100;
965
966/// Summaries of a page's **direct** children — `id, title, slug, url,
967/// has_children`.
968///
969/// One query covers both levels: children *and* grandchildren, sliced by
970/// `depth`, so `has_children` costs nothing extra. It filters on `path`
971/// rather than `parent_id` because `cms_page` indexes `path` and does not
972/// index `parent_id` (`migrations/0001_cms_initial.json`).
973///
974/// `viewer` gates the listing: without it a page whose child subtree is
975/// member-only would publish those titles and URLs to anonymous callers,
976/// which is exactly what the restriction is for. This is the *only* thing
977/// `detail_object_with_type` uses the viewer for — the page itself is
978/// gated by its callers.
979async fn child_summaries(
980    pool: &rustango::sql::Pool,
981    page: &Page,
982    viewer: Option<&rustango::tenancy::auth::User>,
983    locale_id: Option<i64>,
984) -> Vec<serde_json::Value> {
985    // An unsaved preview row has no id and therefore no children yet.
986    let Some(&parent_id) = page.id.get() else {
987        return Vec::new();
988    };
989    if page.path.is_empty() {
990        return Vec::new();
991    }
992
993    // Match the public renderer, not `list`: `archived` still resolves to
994    // a real URL (`PageStatus::is_public`), so omitting it would advertise
995    // fewer children than the site actually serves.
996    let statuses = [
997        PageStatus::Published.as_str().to_owned(),
998        PageStatus::Archived.as_str().to_owned(),
999    ];
1000    let mut rows: Vec<Page> = match Page::objects()
1001        .where_(Page::path.like(crate::tree::descendants_like(&page.path)))
1002        .where_(Page::depth.is_in([page.depth + 1, page.depth + 2]))
1003        .where_(Page::status.is_in(statuses))
1004        .order_by(&[("path", false)])
1005        .fetch(pool)
1006        .await
1007    {
1008        Ok(rows) => rows,
1009        Err(e) => {
1010            tracing::warn!(
1011                target: "rustango_cms::api",
1012                page_id = parent_id,
1013                error = %e,
1014                "child summaries lookup failed",
1015            );
1016            return Vec::new();
1017        }
1018    };
1019
1020    // Error pages are routing furniture, not site structure — excluded
1021    // here exactly as `tree` and `auto_menu` exclude them. Without this a
1022    // 404 handler parented under Home showed up as one of its children.
1023    let error_tid = crate::error_pages::error_page_type_id(pool).await;
1024    rows.retain(|p| error_tid.is_none_or(|tid| p.page_type_id != tid));
1025
1026    // #members — drop what the viewer may not see, before anything is
1027    // counted, so `has_children` never advertises a gated subtree either.
1028    let triples: Vec<(i64, String, i64)> = rows
1029        .iter()
1030        .map(|p| {
1031            (
1032                p.id.get().copied().unwrap_or_default(),
1033                p.path.clone(),
1034                p.page_type_id,
1035            )
1036        })
1037        .collect();
1038    let denied = crate::view_restriction::denied_page_ids(pool, viewer, &triples).await;
1039
1040    let visible: Vec<&Page> = rows
1041        .iter()
1042        .filter(|p| !denied.contains(&p.id.get().copied().unwrap_or_default()))
1043        // Legacy per-locale variant trees are not children of this page in
1044        // any sense a client cares about (#275) — `feed` and the tree
1045        // endpoint drop them too.
1046        .filter(|p| p.locale_variant_of.is_none())
1047        .collect();
1048
1049    let mut grandchildren: std::collections::HashSet<i64> = std::collections::HashSet::new();
1050    for p in visible.iter().filter(|p| p.depth == page.depth + 2) {
1051        if let Some(pid) = p.parent_id {
1052            grandchildren.insert(pid);
1053        }
1054    }
1055
1056    let mut children: Vec<&&Page> = visible
1057        .iter()
1058        .filter(|p| p.depth == page.depth + 1)
1059        .collect();
1060    // Same ordering the rendered site uses (`sort_order, id`), not the
1061    // `path` order the query returned — see the note in `api::tree`.
1062    children.sort_by_key(|p| (p.sort_order, p.id.get().copied().unwrap_or_default()));
1063    if children.is_empty() {
1064        return Vec::new();
1065    }
1066
1067    // Localized titles for the whole set in one query, never per child.
1068    let translations = match locale_id {
1069        Some(lid) => {
1070            let ids: Vec<i64> = children.iter().filter_map(|p| p.id.get().copied()).collect();
1071            crate::translation::fetch_for_pages(pool, &ids, lid)
1072                .await
1073                .unwrap_or_default()
1074        }
1075        None => std::collections::HashMap::new(),
1076    };
1077
1078    children
1079        .into_iter()
1080        .take(MAX_CHILDREN)
1081        .map(|p| {
1082            let id = p.id.get().copied().unwrap_or_default();
1083            let title = translations
1084                .get(&id)
1085                .and_then(|m| m.get("title"))
1086                .filter(|s| !s.is_empty())
1087                .cloned()
1088                .unwrap_or_else(|| p.title.clone());
1089            serde_json::json!({
1090                "id": id,
1091                "title": title,
1092                "slug": p.slug,
1093                "url": if p.url_path.is_empty() { "/" } else { p.url_path.as_str() },
1094                "has_children": grandchildren.contains(&id),
1095                "detail_url": format!("/api/v2/pages/{id}/"),
1096            })
1097        })
1098        .collect()
1099}
1100
1101/// Overlay one locale's `cms_translation` rows onto a built detail object.
1102///
1103/// Three storage shapes, three mechanisms — a single flat overlay cannot
1104/// cover them, which is why the HTML renderer needs three calls too:
1105///
1106/// * **scalars** (`title`, `seo_*`, extension columns, and the legacy
1107///   whole-body stream blob) — [`crate::translation::overlay_translations`],
1108///   which replaces only keys the object already carries and recurses into
1109///   `extension`, matching on its `page_id`.
1110/// * **StreamField leaves** keyed `<field>.<uuid>.<name>` —
1111///   [`crate::block::translate::apply_translatable_overrides`], per stream
1112///   field, since dotted paths address block contents the flat overlay skips.
1113/// * **page-builder leaves** keyed `builder.<path>` —
1114///   [`crate::page_builder::values::apply_builder_translations`].
1115///
1116/// One `fetch_for_pages` query feeds all three. Missing or empty overrides
1117/// leave canonical content in place, so a partially-translated page degrades
1118/// per field rather than blanking.
1119async fn localize_detail_object(
1120    pool: &rustango::sql::Pool,
1121    page_id: i64,
1122    type_name: &str,
1123    locale_id: i64,
1124    obj: &mut serde_json::Map<String, serde_json::Value>,
1125    compiled: Option<&crate::page_builder::compile::CompiledSchema>,
1126) {
1127    let by_page = crate::translation::fetch_for_pages(pool, &[page_id], locale_id)
1128        .await
1129        .unwrap_or_default();
1130    let Some(here) = by_page.get(&page_id) else {
1131        return; // nothing translated for this page in this locale
1132    };
1133
1134    let mut value = serde_json::Value::Object(std::mem::take(obj));
1135    crate::translation::overlay_translations(&mut value, &by_page);
1136
1137    // Per-leaf stream overrides. Which extension fields are streams comes
1138    // from the handler's declared widgets rather than sniffing whether a
1139    // string happens to parse as a JSON array — that heuristic corrupts a
1140    // prose field whose text is something like "[1,2]".
1141    if let Some(h) = find_handler(type_name) {
1142        let stream_fields: Vec<String> = h
1143            .widgets(pool, page_id)
1144            .await
1145            .unwrap_or_default()
1146            .into_iter()
1147            .filter(|w| w.kind == crate::widget::WidgetKind::Stream)
1148            .map(|w| w.name)
1149            .collect();
1150        if let Some(ext) = value.get_mut("extension") {
1151            for name in stream_fields {
1152                if let Some(raw) = ext.get(&name).cloned() {
1153                    let localized =
1154                        crate::block::translate::apply_translatable_overrides(&name, &raw, here);
1155                    if let Some(m) = ext.as_object_mut() {
1156                        m.insert(name, localized);
1157                    }
1158                }
1159            }
1160        }
1161    }
1162
1163    if let (Some(compiled), Some(builder)) = (compiled, value.get_mut("builder")) {
1164        if let Some(map) = builder.as_object_mut() {
1165            crate::page_builder::values::apply_builder_translations(compiled, map, here);
1166        }
1167    }
1168
1169    if let serde_json::Value::Object(m) = value {
1170        *obj = m;
1171    }
1172}
1173
1174// ---------------------------------------------------------------
1175// helpers
1176// ---------------------------------------------------------------
1177
1178async fn lookup_page(
1179    pool: &rustango::sql::Pool,
1180    id: i64,
1181) -> Result<Option<Page>, rustango::sql::ExecError> {
1182    let mut rows: Vec<Page> = Page::objects().where_(Page::id.eq(id)).fetch(pool).await?;
1183    Ok(rows.pop())
1184}
1185
1186async fn lookup_page_type(
1187    pool: &rustango::sql::Pool,
1188    type_name: &str,
1189) -> Result<Option<PageType>, rustango::sql::ExecError> {
1190    let mut rows: Vec<PageType> = PageType::objects()
1191        .where_(PageType::type_name.eq(type_name.to_owned()))
1192        .fetch(pool)
1193        .await?;
1194    Ok(rows.pop())
1195}
1196
1197/// Build a `{ page_type_id → type_name }` lookup so each row can
1198/// emit its symbolic type in the response without an N+1.
1199pub(crate) async fn page_type_names(
1200    pool: &rustango::sql::Pool,
1201) -> Result<std::collections::HashMap<i64, String>, rustango::sql::ExecError> {
1202    let rows: Vec<PageType> = PageType::objects().fetch(pool).await?;
1203    Ok(rows
1204        .into_iter()
1205        .filter_map(|pt| pt.id.get().copied().map(|id| (id, pt.type_name)))
1206        .collect())
1207}
1208
1209fn serialize_summary(
1210    p: &Page,
1211    type_names: &std::collections::HashMap<i64, String>,
1212) -> serde_json::Map<String, serde_json::Value> {
1213    let id = p.id.get().copied().unwrap_or_default();
1214    let type_name = type_names.get(&p.page_type_id).cloned().unwrap_or_default();
1215    let mut obj = serde_json::Map::new();
1216    obj.insert("id".to_owned(), serde_json::json!(id));
1217    obj.insert(
1218        "meta".to_owned(),
1219        serde_json::json!({
1220            "type": type_name,
1221            "detail_url": format!("/api/v2/pages/{id}/"),
1222            "html_url": p.url_path,
1223            "slug": p.slug,
1224            "depth": p.depth,
1225            "parent_id": p.parent_id,
1226            "alias_of": p.alias_of,
1227            "first_published_at": p.published_at,
1228            "updated_at": p.updated_at.get().copied(),
1229        }),
1230    );
1231    obj.insert("title".to_owned(), serde_json::json!(p.title));
1232    // The same `url` key tree nodes and child summaries use. It is also
1233    // at `meta.html_url` for compatibility, but a client should not need
1234    // a different accessor per endpoint to read one field — and unlike
1235    // `html_url`, this normalizes the root's empty `url_path` to "/",
1236    // as the other two shapes already did.
1237    obj.insert(
1238        "url".to_owned(),
1239        serde_json::json!(if p.url_path.is_empty() {
1240            "/"
1241        } else {
1242            p.url_path.as_str()
1243        }),
1244    );
1245    obj.insert("seo_title".to_owned(), serde_json::json!(p.seo_title));
1246    obj.insert(
1247        "seo_description".to_owned(),
1248        serde_json::json!(p.seo_description),
1249    );
1250    obj.insert("robots_index".to_owned(), serde_json::json!(p.robots_index));
1251    obj.insert(
1252        "sitemap_priority".to_owned(),
1253        serde_json::json!(p.sitemap_priority),
1254    );
1255    obj.insert(
1256        "show_in_menus".to_owned(),
1257        serde_json::json!(p.show_in_menus),
1258    );
1259    obj
1260}
1261
1262/// Build the set of ancestor paths for `path` (excluding `path` itself).
1263/// Mirrors [`crate::tree::MaterializedPath::ancestors`] without needing a
1264/// `MaterializedPath` value.
1265fn ancestor_paths_of(path: &str) -> std::collections::HashSet<String> {
1266    let mut out = std::collections::HashSet::new();
1267    let mut acc = String::new();
1268    for seg in path.split('/').filter(|s| !s.is_empty()) {
1269        acc.push_str(seg);
1270        acc.push('/');
1271        if acc != path {
1272            out.insert(acc.clone());
1273        }
1274    }
1275    out
1276}
1277
1278/// Fields `?order=` accepts on this endpoint. Anything else is a `400`
1279/// — kept next to `compare_pages`, which must handle exactly these.
1280const PAGE_ORDER_FIELDS: [&str; 8] = [
1281    "title",
1282    "slug",
1283    "url_path",
1284    "depth",
1285    "sort_order",
1286    "published_at",
1287    "updated_at",
1288    "created_at",
1289];
1290
1291fn compare_pages(a: &Page, b: &Page, specs: &[q::OrderSpec]) -> std::cmp::Ordering {
1292    for spec in specs {
1293        let ord = match spec.field.as_str() {
1294            "title" => a.title.cmp(&b.title),
1295            "slug" => a.slug.cmp(&b.slug),
1296            "url_path" => a.url_path.cmp(&b.url_path),
1297            "depth" => a.depth.cmp(&b.depth),
1298            "sort_order" => a.sort_order.cmp(&b.sort_order),
1299            "published_at" => a.published_at.cmp(&b.published_at),
1300            "updated_at" => a.updated_at.get().cmp(&b.updated_at.get()),
1301            "created_at" => a.created_at.get().cmp(&b.created_at.get()),
1302            _ => continue,
1303        };
1304        if ord != std::cmp::Ordering::Equal {
1305            return if spec.descending { ord.reverse() } else { ord };
1306        }
1307    }
1308    // Same reason as the default ordering: a unique last resort, so two
1309    // rows tied on every requested key still page deterministically.
1310    a.id.get().cmp(&b.id.get())
1311}
1312
1313#[cfg(test)]
1314mod tests {
1315    use super::carried_query;
1316
1317    #[test]
1318    fn the_resolved_path_is_not_carried_onto_the_detail_url() {
1319        // `html_path` is what `find/` consumed; repeating it on the
1320        // detail URL would be noise at best.
1321        assert_eq!(carried_query(Some("html_path=%2Fabout")), "");
1322        assert_eq!(carried_query(None), "");
1323        assert_eq!(carried_query(Some("")), "");
1324    }
1325
1326    #[test]
1327    fn everything_else_survives_the_redirect() {
1328        // The bug this exists for: a SPA resolving its route with
1329        // `?locale=fr` followed the 302 and got English back.
1330        assert_eq!(carried_query(Some("html_path=%2F&locale=fr")), "?locale=fr");
1331        assert_eq!(
1332            carried_query(Some("locale=fr&html_path=%2F&fields=title")),
1333            "?locale=fr&fields=title",
1334        );
1335    }
1336
1337    #[test]
1338    fn a_parameter_this_endpoint_never_heard_of_is_still_forwarded() {
1339        // Hard-coding an allowlist here would silently drop whatever the
1340        // detail endpoint gains next; it ignores names it doesn't know.
1341        assert_eq!(carried_query(Some("html_path=%2F&whatever=1")), "?whatever=1");
1342    }
1343
1344    #[test]
1345    fn values_are_forwarded_verbatim_not_re_encoded() {
1346        // Re-encoding risks double-escaping a token that already is.
1347        assert_eq!(
1348            carried_query(Some("html_path=%2Fx&preview_token=7.123.ab%2Fcd")),
1349            "?preview_token=7.123.ab%2Fcd",
1350        );
1351    }
1352}