refactor(sfm): move the page's JavaScript out of sfm_webapp.html into sfm/static/ (no code change)

Stack-wide rule since 2026-11-02 (terra-view docs/tmi-stack.md, Terra-View's
rule 4): no inline JavaScript, because a test cannot load it.  This page's tests
had to regex their code out of the HTML.  Batch 2 edits both of the page's
scripts, so they come out first, verbatim:

- sfm/static/device_routing.js: the tested routing rules (157 lines)
- sfm/static/sfm_webapp.js: the rest of the page (2,274 lines)

The page loads them with <script src="static/..."> where the inline scripts
were, so load order and the onclick handlers are unchanged.  Verified: putting
the files back inside those tags reproduces the old sfm_webapp.html byte for
byte, and a jsdom page check (served at http://sfm.local/, /static from disk,
no network) gives identical output before and after.

The server serves sfm/static/ at /static/, with Cache-Control: no-cache so a
browser revalidates (a cheap 304) and a new SFM never runs a cached old
script.  Opened from disk, the page needs its static/ folder beside it.

Tests: the routing tests load the file instead of regexing the HTML; new
test_webapp_static pins no inline <script> in the page and the /static route
(through the whole app, middleware included).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-11-02 16:17:44 -05:00
1 parent f98c4ff129
commit 2b886c4f39
6 files changed
+2517 -2444

No files matched your search

+15
View File
@@ -57,6 +57,7 @@ try:
from fastapi import Body, FastAPI, File, HTTPException, Query, Response, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
import uvicorn
except ImportError:
@@ -118,6 +119,20 @@ app.add_middleware(
)
class _PageScripts(StaticFiles):
"""sfm/static/: the web page's JavaScript (no inline JS -- a stack-wide rule,
2026-11-02). `no-cache` makes the browser revalidate on every load, a cheap
304, so a page served by a new SFM never runs an old SFM's cached script."""
async def get_response(self, path, scope):
response = await super().get_response(path, scope)
response.headers["Cache-Control"] = "no-cache"
return response
app.mount("/static", _PageScripts(directory=str(Path(__file__).parent / "static")), name="static")
# ── DB ────────────────────────────────────────────────────────────────────────
# Shared SeismoDb instance. Path can be overridden by --db-path at startup,
# or defaults to bridges/captures/seismo_relay.db relative to the repo root.
+2 -2435
View File
File diff suppressed because it is too large. Load diff
+157
View File
@@ -0,0 +1,157 @@
/* <device-routing> */
// Every rule that decides where a /device/ request goes, or whether a
// series-specific control is live. Pure functions -- no DOM, no fetch -- so
// tests/test_webapp_device_routing.py runs them in Node (phase 1c, 2026-10-29).
// A control follows the unit's own /device/info answer, never a typed serial
// alone: 0xA2 is CONFIRM ERASE on a MiniMate and ends a call-home on a Micromate.
const SERIES_BY_PREFIX = [['UM', 4], ['BE', 3], ['BA', 3]]; // sfm/device_access/series.py
function normSerial(serial) { return String(serial || '').trim().toUpperCase(); }
function seriesFromSerial(serial) {
const s = normSerial(serial);
for (const [prefix, series] of SERIES_BY_PREFIX) {
if (s.startsWith(prefix) && s.length > prefix.length) return series;
}
return null;
}
function unitQuery(unit) {
const parts = [];
const s = normSerial(unit.serial);
if (s) parts.push(`serial=${encodeURIComponent(s)}`);
parts.push(`host=${encodeURIComponent(unit.host || '')}`);
parts.push(`tcp_port=${encodeURIComponent(unit.tcpPort)}`);
return parts.join('&');
}
// action -> [method, path, needs a serial (no legacy equivalent)]
const DEVICE_ROUTES = {
info: ['GET', '/device/info', false],
status: ['GET', '/device/monitor/status', false],
settings: ['GET', '/device/settings', true],
events: ['GET', '/device/events', false],
download: ['POST', '/device/events/download', true],
start: ['POST', '/device/monitor/start', false],
stop: ['POST', '/device/monitor/stop', false],
hangup: ['POST', '/device/hangup', true],
storage_range: ['GET', '/device/events/storage_range', false],
index: ['GET', '/device/events/index', false],
erase: ['POST', '/device/events/erase', false],
rescue: ['POST', '/device/rescue', false],
blind_stop: ['POST', '/device/stop_monitoring_blind', false],
slow_drip: ['POST', '/device/stop_monitoring_slow_drip', false],
call_home_read: ['GET', '/device/call_home', false],
call_home_write: ['POST', '/device/call_home', false],
config_write: ['POST', '/device/config', false],
event_waveform: ['GET', '/device/event/{index}/waveform', false],
event_file: ['GET', '/device/event/{index}/blastware_file', false],
};
function deviceUrl(action, unit, params = {}) {
const route = DEVICE_ROUTES[action];
if (!route) throw new Error(`unknown device action: ${action}`);
const [method, template, needsSerial] = route;
if (needsSerial && !normSerial(unit.serial)) return null;
const rest = { ...params };
let path = template;
if (path.includes('{index}')) { // the legacy per-event routes
if (rest.index === undefined) throw new Error(`${action} needs params.index`);
path = path.replace('{index}', encodeURIComponent(rest.index));
delete rest.index;
}
// Hang-up releases whatever line is held at the address: no serial.
let query = action === 'hangup' ? unitQuery({ ...unit, serial: '' }) : unitQuery(unit);
for (const [k, v] of Object.entries(rest)) query += `&${k}=${encodeURIComponent(v)}`;
return { method, path: `${path}?${query}` };
}
function confirmedSeries(unit) {
const c = unit.confirmed;
if (!c) return null;
const typed = normSerial(unit.serial);
if (!typed) return c.series; // a legacy identify, no serial typed
return typed === normSerial(c.serial) ? c.series : null;
}
function controlsFor(unit) {
const series = confirmedSeries(unit);
const serialMode = Boolean(normSerial(unit.serial));
return {
startStop: serialMode && (series === 3 || series === 4),
hangup: series === 4,
diagnostics: series === 3,
callHomeRead: series === 3,
configWrite: false,
callHomeWrite: false,
reasons: { configWrite: 'Coming in phase 5 (#46)', callHomeWrite: 'Coming in phase 4' },
};
}
function changeSummary(body) {
const id8 = String(body.audit_id || '').slice(0, 8);
if (body.outcome === 'dry_run') {
const subs = ((body.plan || {}).steps || []).map(s => s.sub).join(', ');
return `${body.action}: dry run — would send ${subs}`;
}
if (body.outcome === 'skipped') return `${body.action}: already ${body.state_before} — nothing sent`;
if (body.outcome === 'sent' && body.verified === 'ok') {
return `${body.action}: confirmed — ${body.state_before} → ${body.state_after} (audit ${id8})`;
}
return `${body.action}: ${body.outcome}, ${body.verified} (audit ${id8})`;
}
// What a chip and the peaks bar show for an event, from either shape: the
// shared EventRef (serial mode) or the legacy event (host/port mode).
function eventView(ev) {
const label = typeof ev.timestamp === 'string' ? ev.timestamp.replace('T', ' ')
: (ev.timestamp && ev.timestamp.display) || `Event ${ev.index}`;
let peaks = null;
if (ev.peaks_ips || ev.peak_vector_sum_ips != null) {
const p = ev.peaks_ips || {};
peaks = { tran: p.tran ?? null, vert: p.vert ?? null, long: p.long ?? null,
pvs: ev.peak_vector_sum_ips ?? null, micPsi: null };
} else if (ev.peak_values) {
const pv = ev.peak_values;
peaks = { tran: pv.tran_in_s ?? null, vert: pv.vert_in_s ?? null, long: pv.long_in_s ?? null,
pvs: pv.peak_vector_sum ?? null, micPsi: pv.micl_psi ?? null };
}
return { label, title: ev.record_type || '', peaks };
}
// What the Config tab's serial-mode Read shows for a UnitSettings reply.
function settingsRows(st) {
const dash = v => (v == null || v === '' ? '—' : v);
const hi = st.histogram_interval_s;
const rows = [
['Setup Name', dash(st.setup_name)],
['Record Mode', dash(st.record_mode)],
['Sample Rate', st.sample_rate != null ? `${st.sample_rate} sps` : '—'],
['Record Time', st.record_time_s != null ? `${st.record_time_s.toFixed(2)} s` : '—'],
['Histogram Interval', hi == null ? '—' : hi < 60 ? `${hi} s` : `${hi / 60} min`],
['Geo Trigger', st.geo_trigger_ips != null ? `${st.geo_trigger_ips.toFixed(4)} in/s` : '—'],
];
const notes = Object.entries(st.notes || {});
if (!notes.length) rows.push(['Notes', '—']);
for (const [k, v] of notes) rows.push([`Note: ${k}`, dash(v)]);
return rows;
}
// The legacy per-index routes (Load / Save / Download, prev/next, the arrow
// keys) address events by position on the MiniMate path: live only for a list
// loaded without a serial that has events.
function perIndexLive({ bySerial, count }) { return !bySerial && count > 0; }
// A unit's own string (setup name, project, an error naming a serial) placed
// into markup must stay text.
function escapeHtml(v) {
return String(v ?? '').replace(/[&<>"']/g,
c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
function downloadSummary(body) {
if (body.inserted === false) return `already stored — ${body.stored_filename}`;
return `stored ${body.stored_filename}, ${body.filesize} bytes, check: ${(body.detail || {}).check}`;
}
/* </device-routing> */
File diff suppressed because it is too large. Load diff
+10 -9
View File
@@ -21,6 +21,9 @@ from pathlib import Path
import pytest
PAGE = Path(__file__).resolve().parent.parent / "sfm" / "sfm_webapp.html"
STATIC = PAGE.parent / "static"
ROUTING_JS = STATIC / "device_routing.js" # the page's routing rules, loaded by <script src>
PAGE_JS = STATIC / "sfm_webapp.js" # the rest of the page's script
NODE = shutil.which("node")
pytestmark = pytest.mark.skipif(NODE is None, reason="node is not installed; the page-logic tests need it")
@@ -29,9 +32,7 @@ EXPORTS = ["seriesFromSerial", "unitQuery", "deviceUrl", "confirmedSeries", "con
def _block() -> str:
m = re.search(r"/\* <device-routing> \*/(.*?)/\* </device-routing> \*/", PAGE.read_text(), re.S)
assert m, "no device-routing block in sfm_webapp.html"
return m.group(1)
return ROUTING_JS.read_text()
def run(*cases):
@@ -162,11 +163,12 @@ def test_the_block_touches_no_dom():
def test_the_page_scripts_parse_together(tmp_path):
"""The page's inline scripts share one global scope: a syntax slip, or a name
declared in both, breaks the whole page. Joined, they must pass node --check."""
scripts = re.findall(r"<script>(.*?)</script>", PAGE.read_text(), re.S)
"""The page's scripts share one global scope: a syntax slip, or a name declared
in both, breaks the whole page. Joined in load order, they must pass node --check."""
srcs = re.findall(r'<script src="(static/[^"]+)"></script>', PAGE.read_text())
assert srcs == ["static/device_routing.js", "static/sfm_webapp.js"]
js = tmp_path / "page.js"
js.write_text("\n;\n".join(scripts))
js.write_text("\n;\n".join((PAGE.parent / s).read_text() for s in srcs))
r = subprocess.run([NODE, "--check", str(js)], capture_output=True, text=True, timeout=30)
assert r.returncode == 0, r.stderr
@@ -174,8 +176,7 @@ def test_the_page_scripts_parse_together(tmp_path):
def test_every_device_url_is_built_by_deviceUrl():
"""One place builds /device/ URLs, so the series rules cannot be bypassed:
outside the device-routing block the page holds no hand-built device path."""
src = PAGE.read_text()
outside = re.sub(r"/\* <device-routing> \*/.*?/\* </device-routing> \*/", "", src, flags=re.S)
outside = PAGE.read_text() + PAGE_JS.read_text()
hand_built = [m.group(0) for m in re.finditer(r"(`\$\{api\(\)\}/device/[^`]*`|'/device/[^']*'|\"/device/[^\"]*\")", outside)]
assert hand_built == [], hand_built
+59
View File
@@ -0,0 +1,59 @@
"""The SFM page's JavaScript lives in sfm/static/, served at /static/ (2026-11-02).
Stack-wide rule: no inline JavaScript -- inline code cannot be loaded by a test,
so it breaks where only a user clicking finds it. The page's two scripts were
moved out verbatim; this pins that none comes back, and that the server serves
them so a browser always revalidates (a new SFM never runs the old page's JS).
"""
from __future__ import annotations
import asyncio
import re
from pathlib import Path
import pytest
SFM_DIR = Path(__file__).resolve().parent.parent / "sfm"
PAGE = SFM_DIR / "sfm_webapp.html"
SCRIPTS = ["device_routing.js", "sfm_webapp.js"]
def _get(path: str):
"""One GET through the whole app (middleware included), without an HTTP client."""
from sfm.server import app
msgs = []
async def receive():
return {"type": "http.request", "body": b"", "more_body": False}
async def send(message):
msgs.append(message)
scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET",
"scheme": "http", "path": path, "raw_path": path.encode(), "root_path": "",
"query_string": b"", "headers": [(b"host", b"sfm.local")],
"server": ("sfm.local", 80), "client": ("127.0.0.1", 1)}
asyncio.run(app(scope, receive, send))
start = next(m for m in msgs if m["type"] == "http.response.start")
headers = {k.decode().lower(): v.decode() for k, v in start["headers"]}
return start["status"], headers, b"".join(m.get("body", b"") for m in msgs if m["type"] == "http.response.body")
def test_the_page_has_no_inline_javascript():
html = PAGE.read_text()
tags = re.findall(r"<script([^>]*)>(.*?)</script>", html, re.S)
assert tags and all("src=" in attrs and not body.strip() for attrs, body in tags), \
"an inline <script> is back in sfm_webapp.html -- put it in sfm/static/"
assert re.findall(r'<script src="static/([^"]+)"></script>', html) == SCRIPTS
@pytest.mark.parametrize("name", SCRIPTS)
def test_the_page_scripts_are_served_from_static(name):
status, headers, body = _get(f"/static/{name}")
assert status == 200
assert "javascript" in headers["content-type"]
assert headers["cache-control"] == "no-cache"
assert body == (SFM_DIR / "static" / name).read_bytes()
def test_a_missing_static_file_is_a_404():
assert _get("/static/nope.js")[0] == 404