Files
seismo-relay/sfm/static/device_routing.js
T
serversdownandClaude Opus 5.5 2b886c4f39 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
2026-11-02 16:17:44 -05:00

158 lines
7.2 KiB
JavaScript

/* <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> */