chrome: serve Web Awesome under a version-stamped path, fix the brand ramp

Three fixes found by driving a real page, not by reading the code.

Its autoloader works out where to fetch components from by finding the
<script> whose src *ends with* "webawesome.loader.js". The cache-busting
`?v=` defeated that match, so it fell back to the site root and every
component 404'd - a page that merely looks unstyled, with nothing in the
browser console and only 404s in the server log to say why. Web Awesome now
lives at /chrome/wa-<version>/, which removes the query string and, because
component filenames are stable across releases, also busts caches properly
on an upgrade. There are regression tests for both halves.

The brand ramp pointed at yellow but buttons came out brown: Web Awesome
picks step 50 for a loud fill because that is the darkest point that still
carries white text, and yellow-50 is #b45f04. The services have always used
bright yellow with dark text, so the fill/on pair is now set explicitly
rather than taken from the ramp.

TemplateResponse's old (name, context) signature is gone in Starlette 1.7,
and the error handler was returning its 404 page with an HTTP 200.

Also adds the import map for Preact/hooks/htm to the shell. hooks.module.js
carries a bare "preact" specifier internally, so the map is required rather
than a convenience, and it belongs here once instead of in every service.
strings_json() hands an island its translations with `<` escaped.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Michał Kopeć 2026-10-04 13:31:18 +02:00
parent f6c8fe3d36
commit ee4c37b51b
4 changed files with 119 additions and 4 deletions

View file

@ -9,6 +9,7 @@ service's business.
from __future__ import annotations
import json
from pathlib import Path
from fastapi import FastAPI, Request
@ -25,6 +26,18 @@ from .health import health_router
#: /static so a service can never shadow a shell asset by accident.
CHROME_STATIC_PATH = "/chrome"
#: Web Awesome is served under a path carrying its version.
#:
#: Two reasons, both learned the hard way. Its autoloader works out where to
#: fetch components from by finding the <script> whose src *ends with*
#: "webawesome.loader.js", so a `?v=` cache-buster on that URL defeats the
#: detection and every component 404s against the site root. And because the
#: component filenames are stable across releases, an upgrade would otherwise
#: serve new bytes under URLs browsers have already cached. Putting the
#: version in the path solves both: no query string, and a new path on every
#: upgrade.
WA_PATH = f"{CHROME_STATIC_PATH}/wa-{WEBAWESOME_VERSION}"
class Chrome:
def __init__(
@ -46,6 +59,8 @@ class Chrome:
self.subtitle = subtitle
self.translations = i18n.Translations(locales_dir)
# Registered before the /chrome mount, which would otherwise swallow it.
app.mount(WA_PATH, StaticFiles(directory=STATIC_DIR / "wa"), name="wa")
app.mount(
CHROME_STATIC_PATH, StaticFiles(directory=STATIC_DIR), name="chrome-static"
)
@ -66,6 +81,7 @@ class Chrome:
asset=self.asset,
chrome_asset=self.chrome_asset,
wa_version=WEBAWESOME_VERSION,
wa_base=WA_PATH,
)
app.include_router(health_router(service, version))
@ -80,6 +96,18 @@ class Chrome:
def chrome_asset(self, path: str) -> str:
return f"{CHROME_STATIC_PATH}/{path.lstrip('/')}?v={self.asset_version}"
# --- handing strings to client-side code --------------------------------
def strings_json(self, request: Request, keys: tuple[str, ...]) -> str:
"""Translations for an island, serialised for a <script> tag.
`<` is escaped so a translation containing `</script>` cannot close
the tag it is embedded in. Invisible to JSON.parse.
"""
locale = self.translations.locale_for(request)
payload = self.translations.subset(keys, locale)
return json.dumps(payload, ensure_ascii=False).replace("<", "\\u003c")
# --- rendering ----------------------------------------------------------
def context(self, request: Request, **extra: object) -> dict[str, object]:

View file

@ -27,6 +27,23 @@
--wa-color-brand-10: var(--wa-color-yellow-10);
--wa-color-brand-05: var(--wa-color-yellow-05);
/* The "loud" brand surface - solid buttons, the active toggle, focus.
*
* Overridden rather than taken from the ramp. Web Awesome picks step 50
* for a loud fill because that is the darkest point that still carries
* white text, which for yellow is #b45f04 - a brown. The services have
* always used bright yellow with DARK text on it, so the pair is set
* explicitly: step 80 for the fill, near-black for what sits on it.
*
* These rules are deliberately unlayered. Web Awesome's own theme lives
* in @layer wa-theme, and unlayered declarations beat layered ones, so
* this wins without !important and without raising specificity.
*/
--wa-color-brand-fill-loud: var(--wa-color-yellow-80);
--wa-color-brand-on-loud: var(--wa-color-neutral-10);
--wa-color-brand-border-loud: var(--wa-color-yellow-70);
--wa-color-focus: var(--wa-color-yellow-70);
/* Corner radius: the services settled on 14px long before WA arrived. */
--wa-border-radius-m: 10px;
--wa-border-radius-l: 14px;

View file

@ -16,7 +16,7 @@
import list to keep in sync with the markup.
#}
<!doctype html>
<html lang="{{ lang }}" data-theme="system">
<html lang="{{ lang }}" data-theme="system" data-webawesome="{{ wa_base }}/">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
@ -37,12 +37,28 @@
})();
</script>
<link rel="stylesheet" href="{{ chrome_asset('wa/styles/webawesome.css') }}">
<link rel="stylesheet" href="{{ wa_base }}/styles/webawesome.css">
<link rel="stylesheet" href="{{ chrome_asset('tokens.css') }}">
<link rel="stylesheet" href="{{ chrome_asset('chrome.css') }}">
{% block head %}{% endblock %}
<script type="module" src="{{ chrome_asset('wa/webawesome.loader.js') }}"></script>
{#
Preact, hooks and htm are vendored here rather than per service, and
mapped so a page can `import { h } from "preact"`. hooks.module.js
carries a bare "preact" specifier internally, so the map is required,
not a convenience. See D-0016 for why there is no bundler.
#}
<script type="importmap">
{
"imports": {
"preact": "{{ chrome_asset('vendor/preact.module.js') }}",
"preact/hooks": "{{ chrome_asset('vendor/hooks.module.js') }}",
"htm": "{{ chrome_asset('vendor/htm.module.js') }}"
}
}
</script>
<script type="module" src="{{ wa_base }}/webawesome.loader.js"></script>
<script type="module" src="{{ chrome_asset('theme.js') }}"></script>
</head>
<body>

View file

@ -58,7 +58,7 @@ def test_page_extends_the_shell(client):
html = client.get("/").text
assert '<p id="x">hello</p>' in html # the service's content
assert "Test Service" in html # the shell's header
assert "wa/webawesome.loader.js" in html # Web Awesome is wired up
assert "webawesome.loader.js" in html # Web Awesome is wired up
assert 'data-theme="system"' in html
@ -185,3 +185,57 @@ def test_unauthenticated_mode_must_be_asked_for_explicitly():
def test_webawesome_is_vendored():
assert WEBAWESOME_VERSION.count(".") == 2
def test_preact_is_mapped_for_islands(client):
html = client.get("/").text
assert '"preact":' in html and "vendor/preact.module.js" in html
assert '"preact/hooks":' in html, "hooks has a bare 'preact' import; the map is required"
assert client.get("/chrome/vendor/preact.module.js").status_code == 200
def test_strings_json_cannot_break_out_of_its_script_tag(tmp_path):
locales = tmp_path / "locales"
locales.mkdir()
(locales / "pl.json").write_text('{"evil": "</script><img src=x>"}', "utf-8")
app = FastAPI()
ui = Chrome(app, service="t", version="1", title="T", locales_dir=locales)
class R:
cookies = {"lang": "pl"}
headers = {}
blob = ui.strings_json(R(), ("evil",))
assert "</script>" not in blob
import json as _json
assert _json.loads(blob)["evil"] == "</script><img src=x>"
def test_webawesome_loader_url_has_no_query_string(client):
"""Its autoloader finds its own base path with src.endsWith(...).
A `?v=` here makes every component 404 against the site root, which is
silent in the server log of a page that merely looks unstyled.
"""
import re
html = client.get("/").text
src = re.search(r'src="([^"]*webawesome\.loader\.js[^"]*)"', html).group(1)
assert "?" not in src
assert client.get(src).status_code == 200
def test_webawesome_path_carries_its_version(client):
from chrome import WEBAWESOME_VERSION
html = client.get("/").text
assert f"/chrome/wa-{WEBAWESOME_VERSION}/" in html
assert f'data-webawesome="/chrome/wa-{WEBAWESOME_VERSION}/"' in html
def test_a_component_resolves_under_the_versioned_path(client):
from chrome import WEBAWESOME_VERSION
r = client.get(f"/chrome/wa-{WEBAWESOME_VERSION}/components/button/button.js")
assert r.status_code == 200