# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """Serving the built page, and saying so plainly when it is not built. ``StaticFiles`` raises at construction when its directory is missing, so mounting it unconditionally would make the whole app fail to start on a fresh clone -- and in CI, where pytest runs without ever invoking ``pnpm build``. The branch is therefore explicit: built, or a 503 that names the command to run. "Not built yet" is a normal state with an obvious fix, and it deserves a sentence rather than a traceback. No new dependency. Starlette's ``StaticFiles`` is anyio-based and needs no ``aiofiles``, which is verified rather than assumed: this repository's runtime pins are exactly six packages and adding a seventh would trip the freshness gate. """ from __future__ import annotations from typing import TYPE_CHECKING, Final from fastapi import FastAPI, Response, status from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles if TYPE_CHECKING: from pathlib import Path INDEX: Final = "index.html" ASSETS: Final = "assets" BUILD_COMMAND: Final = "pnpm --dir web install && pnpm --dir web build" NOT_BUILT: Final = ( "
The management page has not been built yet. Run:" f"
{BUILD_COMMAND}"
)
def is_built(dist: Path) -> bool:
"""Whether there is a built page to serve.
Args:
dist: The directory ``vite build`` writes into.
Returns:
True when both halves of a vite build are there. Both, because
mounting StaticFiles on a missing ``assets/`` raises exactly the way
a missing ``dist/`` does, and a half-built directory should answer
"not built" rather than take the app down with it.
"""
return (dist / INDEX).is_file() and (dist / ASSETS).is_dir()
def install(app: FastAPI, dist: Path) -> None:
"""Serve the built page, or explain its absence, at every unclaimed path.
Registered last, after every API route, so the catch-all cannot shadow
them. The catch-all exists because the page routes client-side: a reload
on a sub-view asks this server for a path only the browser knows about.
Args:
app: The FastAPI application to serve from.
dist: The directory ``vite build`` writes into.
"""
if is_built(dist):
# Hashed filenames under /assets, so they are safe to cache and are
# the only paths that must not fall through to index.html.
app.mount(f"/{ASSETS}", StaticFiles(directory=dist / ASSETS), name=ASSETS)
@app.get("/{_path:path}", response_class=HTMLResponse)
async def page(_path: str, response: Response) -> str:
if not is_built(dist):
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
return NOT_BUILT
return (dist / INDEX).read_text(encoding="utf-8")