refactor: comprehensive code quality, security, and release readiness improvements
Some checks failed
Lint & Test / test (push) Failing after 48s

Security: tighten CORS defaults, add webhook rate limiting, fix XSS in
automations, guard WebSocket JSON.parse, validate ADB address input,
seal debug exception leak, URL-encode WS tokens, CSS.escape in selectors.

Code quality: add Pydantic models for brightness/power endpoints, fix
thread safety and name uniqueness in DeviceStore, immutable update
pattern, split 6 oversized files into 16 focused modules, enable
TypeScript strictNullChecks (741→102 errors), type state variables,
add dom-utils helper, migrate 3 modules from inline onclick to event
delegation, ProcessorDependencies dataclass.

Performance: async store saves, health endpoint log level, command
palette debounce, optimized entity-events comparison, fix service
worker precache list.

Testing: expand from 45 to 293 passing tests — add store tests (141),
route tests (25), core logic tests (42), E2E flow tests (33), organize
into tests/api/, tests/storage/, tests/core/, tests/e2e/.

DevOps: CI test pipeline, pre-commit config, Dockerfile multi-stage
build with non-root user and health check, docker-compose improvements,
version bump to 0.2.0.

Docs: rewrite CLAUDE.md (202→56 lines), server/CLAUDE.md (212→76),
create contexts/server-operations.md, fix .js→.ts references, fix env
var prefix in README, rewrite INSTALLATION.md, add CONTRIBUTING.md and
.env.example.
This commit is contained in:
2026-03-22 00:38:28 +03:00
parent 07bb89e9b7
commit f2871319cb
115 changed files with 9808 additions and 5818 deletions

View File

@@ -12,7 +12,7 @@ import {
ICON_TARGET, ICON_AUTOMATION, ICON_CLOCK, ICON_WARNING, ICON_OK,
ICON_STOP, ICON_STOP_PLAIN, ICON_START, ICON_PAUSE, ICON_HELP, ICON_SCENE,
} from '../core/icons.ts';
import { loadScenePresets, renderScenePresetsSection } from './scene-presets.ts';
import { loadScenePresets, renderScenePresetsSection, initScenePresetDelegation } from './scene-presets.ts';
import { cardColorStyle } from '../core/card-colors.ts';
import { createFpsSparkline } from '../core/chart-utils.ts';
import type { Device, OutputTarget, ColorStripSource, ScenePreset, SyncClock, Automation } from '../types.ts';
@@ -57,7 +57,7 @@ function _getInterpolatedUptime(targetId: string): number | null {
function _cacheUptimeElements(): void {
_uptimeElements = {};
for (const id of _lastRunningIds) {
const el = document.querySelector(`[data-uptime-text="${id}"]`);
const el = document.querySelector(`[data-uptime-text="${CSS.escape(id)}"]`);
if (el) _uptimeElements[id] = el;
}
}
@@ -126,7 +126,7 @@ async function _initFpsCharts(runningTargetIds: string[]): Promise<void> {
if (!canvas) continue;
const actualH = _fpsHistory[id] || [];
const currentH = _fpsCurrentHistory[id] || [];
const fpsTarget = parseFloat(canvas.dataset.fpsTarget) || 30;
const fpsTarget = parseFloat(canvas.dataset.fpsTarget ?? '30') || 30;
_fpsCharts[id] = _createFpsChart(`dashboard-fps-${id}`, actualH, currentH, fpsTarget);
}
@@ -137,9 +137,9 @@ function _cacheMetricsElements(runningIds: string[]): void {
_metricsElements.clear();
for (const id of runningIds) {
_metricsElements.set(id, {
fps: document.querySelector(`[data-fps-text="${id}"]`),
errors: document.querySelector(`[data-errors-text="${id}"]`),
row: document.querySelector(`[data-target-id="${id}"]`),
fps: document.querySelector(`[data-fps-text="${CSS.escape(id)}"]`),
errors: document.querySelector(`[data-errors-text="${CSS.escape(id)}"]`),
row: document.querySelector(`[data-target-id="${CSS.escape(id)}"]`),
});
}
}
@@ -181,7 +181,7 @@ function _updateRunningMetrics(enrichedRunning: any[]): void {
// Update text values (use cached refs, fallback to querySelector)
const cached = _metricsElements.get(target.id);
const fpsEl = cached?.fps || document.querySelector(`[data-fps-text="${target.id}"]`);
const fpsEl = cached?.fps || document.querySelector(`[data-fps-text="${CSS.escape(target.id)}"]`);
if (fpsEl) {
const effFps = state.fps_effective;
const fpsTargetLabel = (effFps != null && effFps < fpsTarget)
@@ -192,13 +192,13 @@ function _updateRunningMetrics(enrichedRunning: any[]): void {
+ `<span class="dashboard-fps-avg">avg ${fpsActual}</span>`;
}
const errorsEl = cached?.errors || document.querySelector(`[data-errors-text="${target.id}"]`);
const errorsEl = cached?.errors || document.querySelector(`[data-errors-text="${CSS.escape(target.id)}"]`);
if (errorsEl) { errorsEl.innerHTML = `${errors > 0 ? ICON_WARNING : ICON_OK} ${formatCompact(errors)}`; (errorsEl as HTMLElement).title = String(errors); }
// Update health dot — prefer streaming reachability when processing
const isLed = target.target_type === 'led' || target.target_type === 'wled';
if (isLed) {
const row = cached?.row || document.querySelector(`[data-target-id="${target.id}"]`);
const row = cached?.row || document.querySelector(`[data-target-id="${CSS.escape(target.id)}"]`);
if (row) {
const dot = row.querySelector('.health-dot');
if (dot) {
@@ -217,7 +217,7 @@ function _updateRunningMetrics(enrichedRunning: any[]): void {
function _updateAutomationsInPlace(automations: Automation[]): void {
for (const a of automations) {
const card = document.querySelector(`[data-automation-id="${a.id}"]`);
const card = document.querySelector(`[data-automation-id="${CSS.escape(a.id)}"]`);
if (!card) continue;
const badge = card.querySelector('.dashboard-badge-active, .dashboard-badge-stopped');
if (badge) {
@@ -243,7 +243,7 @@ function _updateAutomationsInPlace(automations: Automation[]): void {
function _updateSyncClocksInPlace(syncClocks: SyncClock[]): void {
for (const c of syncClocks) {
const card = document.querySelector(`[data-sync-clock-id="${c.id}"]`);
const card = document.querySelector(`[data-sync-clock-id="${CSS.escape(c.id)}"]`);
if (!card) continue;
const speedEl = card.querySelector('.dashboard-clock-speed');
if (speedEl) speedEl.textContent = `${c.speed}x`;
@@ -292,7 +292,7 @@ function _renderPollIntervalSelect(): string {
return `<span class="dashboard-poll-wrap"><input type="range" class="dashboard-poll-slider" min="1" max="10" value="${sec}" oninput="changeDashboardPollInterval(this.value)" title="${t('dashboard.poll_interval')}"><span class="dashboard-poll-value">${sec}s</span></span>`;
}
let _pollDebounce: ReturnType<typeof setTimeout> | null = null;
let _pollDebounce: ReturnType<typeof setTimeout> | undefined = undefined;
export function changeDashboardPollInterval(value: string | number): void {
const label = document.querySelector('.dashboard-poll-value');
if (label) label.textContent = `${value}s`;
@@ -307,7 +307,7 @@ export function changeDashboardPollInterval(value: string | number): void {
}
function _getCollapsedSections(): Record<string, boolean> {
try { return JSON.parse(localStorage.getItem(DASHBOARD_COLLAPSED_KEY)) || {}; }
try { return JSON.parse(localStorage.getItem(DASHBOARD_COLLAPSED_KEY) ?? '{}') || {}; }
catch { return {}; }
}
@@ -315,7 +315,7 @@ export function toggleDashboardSection(sectionKey: string): void {
const collapsed = _getCollapsedSections();
collapsed[sectionKey] = !collapsed[sectionKey];
localStorage.setItem(DASHBOARD_COLLAPSED_KEY, JSON.stringify(collapsed));
const header = document.querySelector(`[data-dashboard-section="${sectionKey}"]`);
const header = document.querySelector(`[data-dashboard-section="${CSS.escape(sectionKey)}"]`);
if (!header) return;
const content = header.nextElementSibling;
const chevron = header.querySelector('.dashboard-section-chevron');
@@ -379,10 +379,10 @@ export async function loadDashboard(forceFullRender: boolean = false): Promise<v
try {
// Fire all requests in a single batch to avoid sequential RTTs
const [targets, automationsResp, devicesArr, cssArr, batchStatesResp, batchMetricsResp, scenePresets, syncClocksResp] = await Promise.all([
outputTargetsCache.fetch().catch(() => []),
outputTargetsCache.fetch().catch((): any[] => []),
fetchWithAuth('/automations').catch(() => null),
devicesCache.fetch().catch(() => []),
colorStripSourcesCache.fetch().catch(() => []),
devicesCache.fetch().catch((): any[] => []),
colorStripSourcesCache.fetch().catch((): any[] => []),
fetchWithAuth('/output-targets/batch/states').catch(() => null),
fetchWithAuth('/output-targets/batch/metrics').catch(() => null),
loadScenePresets(),
@@ -403,7 +403,7 @@ export async function loadDashboard(forceFullRender: boolean = false): Promise<v
// Build dynamic HTML (targets, automations)
let dynamicHtml = '';
let runningIds = [];
let runningIds: any[] = [];
if (targets.length === 0 && automations.length === 0 && scenePresets.length === 0 && syncClocks.length === 0) {
dynamicHtml = `<div class="dashboard-no-targets">${t('dashboard.no_targets')}</div>`;
} else {
@@ -518,9 +518,11 @@ export async function loadDashboard(forceFullRender: boolean = false): Promise<v
</div>
<div class="dashboard-dynamic">${dynamicHtml}</div>`;
await initPerfCharts();
// Event delegation for scene preset cards (attached once, works across innerHTML refreshes)
initScenePresetDelegation(container);
} else {
const dynamic = container.querySelector('.dashboard-dynamic');
if (dynamic.innerHTML !== dynamicHtml) {
if (dynamic && dynamic.innerHTML !== dynamicHtml) {
dynamic.innerHTML = dynamicHtml;
}
}
@@ -743,7 +745,7 @@ export async function dashboardStopAll(): Promise<void> {
if (!confirmed) return;
try {
const [allTargets, statesResp] = await Promise.all([
outputTargetsCache.fetch().catch(() => []),
outputTargetsCache.fetch().catch((): any[] => []),
fetchWithAuth('/output-targets/batch/states'),
]);
const statesData = statesResp.ok ? await statesResp.json() : { states: {} };
@@ -804,7 +806,7 @@ function _isDashboardActive(): boolean {
return (localStorage.getItem('activeTab') || 'dashboard') === 'dashboard';
}
let _eventDebounceTimer: ReturnType<typeof setTimeout> | null = null;
let _eventDebounceTimer: ReturnType<typeof setTimeout> | undefined = undefined;
function _debouncedDashboardReload(forceFullRender: boolean = false): void {
if (!_isDashboardActive()) return;
clearTimeout(_eventDebounceTimer);