Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions test/app-shell.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import * as assert from 'node:assert/strict';
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { describe, it } from 'node:test';
import { runInNewContext } from 'node:vm';

function extractHeadInitScript(html: string): string {
const match = html.match(/<head>[\s\S]*?<script>([\s\S]*?)<\/script>[\s\S]*?<\/head>/i);
assert.ok(match && match[1], 'Expected inline theme initialization script in <head>');
return match[1];
}

function runThemeInit(options: {
storedTheme?: string | null;
storedFontSize?: string | null;
prefersDark?: boolean;
throwStorage?: boolean;
}) {
const html = readFileSync('src/app.html', 'utf8');
const script = extractHeadInitScript(html);

const classes = new Set<string>();
const dataset: Record<string, string> = {};

const context = {
localStorage: {
getItem(key: string) {
if (options.throwStorage) {
throw new Error('SecurityError: storage disabled');
}
if (key === 'fleet-theme') return options.storedTheme ?? null;
if (key === 'fleet-font-size') return options.storedFontSize ?? null;
return null;
}
},
window: {
matchMedia() {
return { matches: Boolean(options.prefersDark) };
}
},
document: {
documentElement: {
dataset,
classList: {
add(cls: string) {
if (/\s/.test(cls)) throw new Error('InvalidCharacterError');
classes.add(cls);
},
toggle(cls: string, force?: boolean) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

classList.toggle mock omits whitespace validation present in classList.add: classList.add() throws InvalidCharacterError when cls contains whitespace, matching real browser DOMTokenList behavior, but classList.toggle() does not. If the inline script in src/app.html passes a malformed value with spaces to classList.toggle(), this mock will silently accept it instead of catching the runtime exception in the malformed-values test.

Suggested change
toggle(cls: string, force?: boolean) {
toggle(cls: string, force?: boolean) {
if (/\s/.test(cls)) throw new Error('InvalidCharacterError');
if (force === undefined) {

if (force === undefined) {
if (classes.has(cls)) classes.delete(cls);
else classes.add(cls);
} else if (force) {
classes.add(cls);
} else {
classes.delete(cls);
}
}
}
}
}
};

runInNewContext(script, context);
return { dataset, classes };
}

describe('app.html zero-FOUC initialization script', () => {
it('applies explicit dark and light stored themes', () => {
const dark = runThemeInit({ storedTheme: 'dark', prefersDark: false });
assert.equal(dark.dataset.theme, 'dark');
assert.ok(dark.classes.has('dark'));
assert.ok(!dark.classes.has('light'));

const light = runThemeInit({ storedTheme: 'light', prefersDark: true });
assert.equal(light.dataset.theme, 'light');
assert.ok(light.classes.has('light'));
assert.ok(!light.classes.has('dark'));
});

it('falls back to prefers-color-scheme when unset or set to system', () => {
const sysDark = runThemeInit({ storedTheme: 'system', prefersDark: true });
assert.equal(sysDark.dataset.theme, 'dark');
assert.ok(sysDark.classes.has('dark'));

const unsetLight = runThemeInit({ storedTheme: null, prefersDark: false });
assert.equal(unsetLight.dataset.theme, 'light');
assert.ok(unsetLight.classes.has('light'));
});

it('never throws when localStorage throws SecurityError or contains malformed values', () => {
const res = runThemeInit({ throwStorage: true, prefersDark: true });
assert.ok(res);

const malformed = runThemeInit({
storedTheme: 'unexpected-value',
storedFontSize: 'bad value with spaces',
prefersDark: true
});
assert.equal(malformed.dataset.theme, 'dark');
assert.equal(malformed.dataset.fontSize, undefined);
});
});

describe('static production build output (when build/ exists)', () => {
it('contains valid SPA entrypoints and no leaked /nix/store paths', () => {
if (!existsSync('build/index.html')) return;

const indexHtml = readFileSync('build/index.html', 'utf8');
const fallbackHtml = readFileSync('build/200.html', 'utf8');
assert.match(indexHtml, /<!doctype html>/i);
assert.match(fallbackHtml, /<!doctype html>/i);

const files = readdirSync('build', { recursive: true });
assert.ok(files.some((f) => String(f).startsWith('_app/')));

for (const rel of files) {
const path = `build/${String(rel)}`;
if (/\.(html|js|css|json)$/.test(path)) {
const content = readFileSync(path, 'utf8');
assert.doesNotMatch(content, /\/nix\/store\//, `Unexpected Nix store reference in ${path}`);
}
}
});
});
133 changes: 133 additions & 0 deletions test/attention.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import * as assert from 'node:assert/strict';
import { afterEach, describe, it } from 'node:test';
import {
buildServiceAttention,
fetchAttentionFeed,
parseAttentionFeed,
sortAttention
} from '#lib/data/attention';
import type { AttentionItem, EndpointDetail, ServiceItem } from '#lib/types';

const originalFetch = globalThis.fetch;

afterEach(() => {
globalThis.fetch = originalFetch;
});

describe('parseAttentionFeed', () => {
it('accepts an items object or a bare array and fills defaults', () => {
const wrapped = parseAttentionFeed({
items: [{ title: ' Review requested ', url: 'https://example.test/pr/1', source: 'GitHub', severity: 'warning' }]
});
assert.deepEqual(wrapped, [
{
id: 'feed:https://example.test/pr/1',
title: 'Review requested',
severity: 'warning',
url: 'https://example.test/pr/1',
detail: undefined,
source: 'GitHub',
updatedAt: undefined
}
]);
assert.equal(parseAttentionFeed([{ title: 'Bare' }])[0].severity, 'info');
});

it('drops entries without a title, unsafe URLs, invalid times and duplicate ids', () => {
const items = parseAttentionFeed([
null,
'text',
{ url: 'https://example.test' },
{ title: 'Script', url: 'javascript:alert(1)', updatedAt: 'yesterday', severity: 'fatal' },
{ id: 'a', title: 'First', updatedAt: '2026-11-16T10:00:00Z' },
{ id: 'a', title: 'Second' }
]);
assert.deepEqual(
items.map((i) => [i.id, i.title, i.url, i.updatedAt, i.severity]),
[
['feed:Script', 'Script', undefined, undefined, 'info'],
['feed:a', 'First', undefined, '2026-11-16T10:00:00Z', 'info']
]
);
});

it('returns nothing for a non-feed payload and caps the list at 50 items', () => {
for (const bad of [null, 42, 'x', {}, { items: 'none' }]) assert.deepEqual(parseAttentionFeed(bad), []);
const many = Array.from({ length: 80 }, (_, i) => ({ title: `Item ${i}` }));
assert.equal(parseAttentionFeed(many).length, 50);
});

it('shortens overlong text', () => {
const [item] = parseAttentionFeed([{ title: 't'.repeat(500), detail: 'd'.repeat(500) }]);
assert.equal(item.title.length, 200);
assert.equal(item.detail?.length, 300);
});
});

describe('fetchAttentionFeed', () => {
it('returns parsed items, and null when the feed is unreachable or not JSON', async () => {
globalThis.fetch = (async () => new Response(JSON.stringify({ items: [{ title: 'One' }] }))) as typeof fetch;
assert.equal((await fetchAttentionFeed('/attention.json'))?.[0].title, 'One');

globalThis.fetch = (async () => new Response('', { status: 503 })) as typeof fetch;
assert.equal(await fetchAttentionFeed('/attention.json'), null);

globalThis.fetch = (async () => new Response('<html>login</html>')) as typeof fetch;
assert.equal(await fetchAttentionFeed('/attention.json'), null);

globalThis.fetch = (async () => {
throw new TypeError('network');
}) as typeof fetch;
assert.equal(await fetchAttentionFeed('/attention.json'), null);
});
});

describe('buildServiceAttention', () => {
const service = (id: string, name: string): ServiceItem => ({
id, name, category: 'Apps', icon: '📦', description: '', url: `https://${id}.example.test`, host: 'core-pi', network: 'mesh'
});

it('lists only services whose latest probe failed', () => {
const details: Record<string, EndpointDetail> = {
paperless: {
name: 'Paperless', status: 'down', history: [true, false], reason: 'connection refused',
checkedAt: '2026-11-16T10:06:00Z', downSince: '2026-11-16T10:03:00Z'
},
grafana: { name: 'Grafana', status: 'healthy', history: [true] },
old: { name: 'Old', status: 'down', history: [false], checkedAt: '2026-11-16T10:06:00Z' }
};
const items = buildServiceAttention(
[service('paperless', 'Paperless'), service('grafana', 'Grafana'), service('old', 'Old'), service('unprobed', 'Unprobed')],
details
);
assert.deepEqual(items, [
{
id: 'svc:paperless', title: 'Paperless is down', severity: 'critical',
url: 'https://paperless.example.test', detail: 'connection refused', source: 'core-pi',
updatedAt: '2026-11-16T10:03:00Z'
},
{
id: 'svc:old', title: 'Old is down', severity: 'critical',
url: 'https://old.example.test', detail: undefined, source: 'core-pi',
updatedAt: '2026-11-16T10:06:00Z'
}
]);
});
});

describe('sortAttention', () => {
it('orders by severity, then newest first, with undated items last', () => {
const item = (id: string, severity: AttentionItem['severity'], updatedAt?: string): AttentionItem => ({
id, title: id, severity, updatedAt
});
const input = [
item('info-old', 'info', '2026-11-01T00:00:00Z'),
item('warn', 'warning'),
item('crit-undated', 'critical'),
item('info-new', 'info', '2026-11-16T00:00:00Z'),
item('crit-new', 'critical', '2026-11-16T00:00:00Z')
];
assert.deepEqual(sortAttention(input).map((i) => i.id), ['crit-new', 'crit-undated', 'warn', 'info-new', 'info-old']);
assert.equal(input[0].id, 'info-old');
});
});
Loading