From 017c2834435b8ccefc756b4a91c89fa60bb6448b Mon Sep 17 00:00:00 2001 From: Aaron Guo <89121695+PolarWolf314@users.noreply.github.com> Date: Thu, 15 Oct 2026 19:47:25 +1300 Subject: [PATCH 01/58] fix: pass element constructor to getElement to satisfy no-unnecessary-type-parameters --- client/src/controllers/cinema.ts | 6 +++--- client/src/controllers/entryCard.ts | 8 ++++---- client/src/controllers/movie.ts | 2 +- client/src/controllers/sidebar.ts | 2 +- client/src/controllers/waitingRoom.ts | 6 +++--- client/src/util/getElement.ts | 10 +++++++--- client/src/util/getUsername.ts | 2 +- 7 files changed, 20 insertions(+), 16 deletions(-) diff --git a/client/src/controllers/cinema.ts b/client/src/controllers/cinema.ts index 62b8cd3..b254bd0 100644 --- a/client/src/controllers/cinema.ts +++ b/client/src/controllers/cinema.ts @@ -3,11 +3,11 @@ import { socket } from '../main'; import { BaseUser, ServerEvents } from '../shared'; import { getElement } from '../util'; -const element = getElement('#cinema'); +const element = getElement('#cinema', HTMLDivElement); -const title = getElement('#cinema > h3'); +const title = getElement('#cinema > h3', HTMLHeadingElement); -const userContainer = getElement('#cinema > div'); +const userContainer = getElement('#cinema > div', HTMLDivElement); const users = new Map(); diff --git a/client/src/controllers/entryCard.ts b/client/src/controllers/entryCard.ts index f80afc9..c27a6fa 100644 --- a/client/src/controllers/entryCard.ts +++ b/client/src/controllers/entryCard.ts @@ -2,13 +2,13 @@ import { socket } from '../main'; import { ServerEvents } from '../shared'; import { getElement } from '../util'; -const cardElement = getElement('#entry-card'); +const cardElement = getElement('#entry-card', HTMLDivElement); -const titleElement = getElement('#entry-card h1'); +const titleElement = getElement('#entry-card h1', HTMLHeadingElement); -const descriptionElement = getElement('#entry-card p'); +const descriptionElement = getElement('#entry-card p', HTMLParagraphElement); -const inputElement = getElement('#entry-card input'); +const inputElement = getElement('#entry-card input', HTMLInputElement); interface ShowProps { title: string; diff --git a/client/src/controllers/movie.ts b/client/src/controllers/movie.ts index 8ba3b25..b2e7731 100644 --- a/client/src/controllers/movie.ts +++ b/client/src/controllers/movie.ts @@ -2,7 +2,7 @@ import { MOVIE_SOURCE, MOVIE_TYPE, socket, SUBTITLES } from '../main'; import { ClientEvents, ServerEvents } from '../shared'; import { getElement } from '../util'; -const element = getElement('#movie'); +const element = getElement('#movie', HTMLVideoElement); const LOCAL_STORAGE_KEY = 'volume'; const DEFAULT_VOLUME = 0.15; // 100% is always crazy loud diff --git a/client/src/controllers/sidebar.ts b/client/src/controllers/sidebar.ts index 22184c0..7d26142 100644 --- a/client/src/controllers/sidebar.ts +++ b/client/src/controllers/sidebar.ts @@ -1,7 +1,7 @@ import { Cinema, WaitingRoom } from '.'; import { getElement } from '../util'; -const element = getElement('#sidebar'); +const element = getElement('#sidebar', HTMLDivElement); export function update(): void { element.hidden = Cinema.isHidden() && WaitingRoom.isHidden(); diff --git a/client/src/controllers/waitingRoom.ts b/client/src/controllers/waitingRoom.ts index 1045e16..b98ef13 100644 --- a/client/src/controllers/waitingRoom.ts +++ b/client/src/controllers/waitingRoom.ts @@ -3,11 +3,11 @@ import { socket } from '../main'; import { BaseUser, ServerEvents } from '../shared'; import { getElement } from '../util'; -const element = getElement('#waiting-room'); +const element = getElement('#waiting-room', HTMLDivElement); -const title = getElement('#waiting-room > h3'); +const title = getElement('#waiting-room > h3', HTMLHeadingElement); -const userContainer = getElement('#waiting-room > div'); +const userContainer = getElement('#waiting-room > div', HTMLDivElement); const users = new Map(); diff --git a/client/src/util/getElement.ts b/client/src/util/getElement.ts index 8592fd4..029132f 100644 --- a/client/src/util/getElement.ts +++ b/client/src/util/getElement.ts @@ -1,10 +1,14 @@ -/** Queries the DOM for an element, throwing an error if it is not found. */ -export function getElement(selector: string): T { - const element = document.querySelector(selector); +/** Queries the DOM for an element, throwing an error if it is not found or isn't the expected type. */ +export function getElement(selector: string, elementType: new () => T): T { + const element = document.querySelector(selector); if (element === null) { throw new Error(`Element with selector ${selector} not found.`); } + if (!(element instanceof elementType)) { + throw new Error(`Element with selector ${selector} is not ${elementType.name}.`); + } + return element; } diff --git a/client/src/util/getUsername.ts b/client/src/util/getUsername.ts index ff91d8a..6e20cae 100644 --- a/client/src/util/getUsername.ts +++ b/client/src/util/getUsername.ts @@ -1,7 +1,7 @@ import { EntryCard } from '../controllers'; import { getElement } from './getElement'; -const usernameInput = getElement('#username-input'); +const usernameInput = getElement('#username-input', HTMLInputElement); const LOCAL_STORAGE_KEY = 'username'; From 72587e2ac48dc01839251d162c9dc36352ae1d1d Mon Sep 17 00:00:00 2001 From: Aaron Guo <89121695+PolarWolf314@users.noreply.github.com> Date: Thu, 15 Oct 2026 19:55:12 +1300 Subject: [PATCH 02/58] fix: install typescript as converter devDependency so typecheck works --- converter/bun.lock | 4 +--- converter/package.json | 6 ++---- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/converter/bun.lock b/converter/bun.lock index cb40517..98986b8 100644 --- a/converter/bun.lock +++ b/converter/bun.lock @@ -5,9 +5,7 @@ "": { "devDependencies": { "@types/bun": "latest", - }, - "peerDependencies": { - "typescript": "^6.0.3", + "typescript": "6.0.3", }, }, }, diff --git a/converter/package.json b/converter/package.json index 93b6607..0e095ca 100644 --- a/converter/package.json +++ b/converter/package.json @@ -9,9 +9,7 @@ "check-all": "bun run typecheck" }, "devDependencies": { - "@types/bun": "latest" - }, - "peerDependencies": { - "typescript": "^6.0.3" + "@types/bun": "latest", + "typescript": "6.0.3" } } \ No newline at end of file From 99cffb244566d04c7a24403cd0f0c0d9af42a405 Mon Sep 17 00:00:00 2001 From: Aaron Guo <89121695+PolarWolf314@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:11:01 +1300 Subject: [PATCH 03/58] test: add Vitest/Playwright test tooling and media fixtures - Vitest (node env, no DOM simulator) for client and server; bun test for converter, with unit + integration suites and npm scripts wired up - Playwright config (chromium/firefox/webkit projects, serial workers) plus a chromium browser smoke spec; chromium browser downloaded - vite.test.config.ts serves fixture media via a fixture publicDir and redirects the settings.json import to tests/fixtures/player-settings.json so user data is never read during browser tests - generate-media.mjs synthesizes three tiny H.264/AAC clips (FFmpeg lavfi sources only, so licensed by construction) into the gitignored tests/fixtures/public/data/; idempotent with --force - typecheck/lint now cover tests: client tsconfig includes tests + root configs, server gains tests/tsconfig.json, converter includes tests/; eslint lints src tests in client and server - characterization smoke tests pin the client/server wire event strings --- client/.gitignore | 6 +- client/eslint.config.js | 6 +- client/package.json | 8 +- client/playwright.config.ts | 31 +++ client/tests/browser/smoke.spec.ts | 9 + client/tests/fixtures/player-settings.json | 5 + client/tests/helpers/playerHarness.ts | 10 + client/tests/scripts/generate-media.mjs | 121 +++++++++ client/tests/unit/shared.test.ts | 21 ++ client/tsconfig.json | 4 +- client/vite.test.config.ts | 25 ++ client/vitest.config.ts | 10 + converter/package.json | 4 +- converter/tests/integration/smoke.test.ts | 9 + converter/tests/unit/smoke.test.ts | 10 + converter/tsconfig.json | 1 + pnpm-lock.yaml | 290 +++++++++++++++++++++ server/package.json | 8 +- server/tests/helpers/testApp.ts | 8 + server/tests/tsconfig.json | 10 + server/tests/unit/shared.test.ts | 17 ++ server/vitest.config.ts | 10 + 22 files changed, 613 insertions(+), 10 deletions(-) create mode 100644 client/playwright.config.ts create mode 100644 client/tests/browser/smoke.spec.ts create mode 100644 client/tests/fixtures/player-settings.json create mode 100644 client/tests/helpers/playerHarness.ts create mode 100644 client/tests/scripts/generate-media.mjs create mode 100644 client/tests/unit/shared.test.ts create mode 100644 client/vite.test.config.ts create mode 100644 client/vitest.config.ts create mode 100644 converter/tests/integration/smoke.test.ts create mode 100644 converter/tests/unit/smoke.test.ts create mode 100644 server/tests/helpers/testApp.ts create mode 100644 server/tests/tsconfig.json create mode 100644 server/tests/unit/shared.test.ts create mode 100644 server/vitest.config.ts diff --git a/client/.gitignore b/client/.gitignore index 93bd73e..f944c8a 100644 --- a/client/.gitignore +++ b/client/.gitignore @@ -3,4 +3,8 @@ dist/ public/data/* !public/data/put movie here.txt -settings.json \ No newline at end of file +settings.json + +# Generated test fixtures and browser-test artifacts +tests/fixtures/public/ +test-results/ diff --git a/client/eslint.config.js b/client/eslint.config.js index 4ca8bae..b72d8ff 100644 --- a/client/eslint.config.js +++ b/client/eslint.config.js @@ -4,6 +4,11 @@ import eslint from '@eslint/js'; import tseslint from 'typescript-eslint'; export default tseslint.config( + { + // Standalone `ignores` objects are global; tests/scripts holds plain-JS + // Node scripts that run outside type-aware linting. + ignores: ['eslint.config.js', 'build/**', 'node_modules/**', 'tests/scripts/**'], + }, eslint.configs.recommended, ...tseslint.configs.strictTypeChecked, ...tseslint.configs.stylisticTypeChecked, @@ -14,7 +19,6 @@ export default tseslint.config( tsconfigRootDir: import.meta.dirname, }, }, - ignores: ['eslint.config.js', 'build/**', 'node_modules/**'], rules: { // Possible Problems (https://eslint.org/docs/latest/rules/#possible-problems) diff --git a/client/package.json b/client/package.json index a06a3f3..057dffa 100644 --- a/client/package.json +++ b/client/package.json @@ -15,17 +15,21 @@ "scripts": { "build": "tsc && vite build", "typecheck": "tsc", - "lint": "eslint src --max-warnings=0", + "lint": "eslint src tests --max-warnings=0", "check-all": "pnpm run typecheck && pnpm run lint", + "test": "vitest run", + "test:browser": "playwright test --project=chromium", "start": "vite preview --host --port=1730", "dev": "vite --host --port=1730" }, "devDependencies": { "@eslint/js": "^10.0.1", + "@playwright/test": "1.63.0", "eslint": "^10.4.1", "socket.io-client": "^4.7.5", "typescript": "^6.0.3", "typescript-eslint": "^8.61.0", - "vite": "^8.0.16" + "vite": "^8.0.16", + "vitest": "4.1.6" } } diff --git a/client/playwright.config.ts b/client/playwright.config.ts new file mode 100644 index 0000000..4a59e30 --- /dev/null +++ b/client/playwright.config.ts @@ -0,0 +1,31 @@ +import { defineConfig, devices } from '@playwright/test'; + +// Browser tests run serially (workers: 1) because they share cinema state on +// the server under test. The webServer wiring is added alongside the browser +// test suite itself. +export default defineConfig({ + testDir: 'tests/browser', + timeout: 30_000, + fullyParallel: false, + workers: 1, + retries: 0, + reporter: [['list']], + use: { + baseURL: 'http://localhost:1730', + trace: 'retain-on-failure', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + { + name: 'firefox', + use: { ...devices['Desktop Firefox'] }, + }, + { + name: 'webkit', + use: { ...devices['Desktop Safari'] }, + }, + ], +}); diff --git a/client/tests/browser/smoke.spec.ts b/client/tests/browser/smoke.spec.ts new file mode 100644 index 0000000..ef0984c --- /dev/null +++ b/client/tests/browser/smoke.spec.ts @@ -0,0 +1,9 @@ +import { expect, test } from '@playwright/test'; + +// Harness smoke test: proves chromium launches, the driver connects, and +// locators/assertions work. Real page tests arrive with Task 6. +test('the browser harness launches and renders a page', async ({ page }): Promise => { + await page.setContent('

Panopticon browser harness

'); + + await expect(page.locator('h1')).toHaveText('Panopticon browser harness'); +}); diff --git a/client/tests/fixtures/player-settings.json b/client/tests/fixtures/player-settings.json new file mode 100644 index 0000000..c2e9a09 --- /dev/null +++ b/client/tests/fixtures/player-settings.json @@ -0,0 +1,5 @@ +{ + "file": "red.mp4", + "type": "video/mp4", + "subtitles": [] +} diff --git a/client/tests/helpers/playerHarness.ts b/client/tests/helpers/playerHarness.ts new file mode 100644 index 0000000..53d73ab --- /dev/null +++ b/client/tests/helpers/playerHarness.ts @@ -0,0 +1,10 @@ +/** + * Placeholder for the browser-test player harness (fleshed out in Task 6). + * + * Intended purpose: drive the real `#movie` element from Playwright specs — + * admission flow, play/pause/seek state, and volume persistence — against the + * fixture media served via `vite.test.config.ts` (fixture `settings.json` and + * fixture `publicDir`, never the user's `client/settings.json` or + * `client/public/data/`). + */ +export const PLAYER_HARNESS_PENDING = true; diff --git a/client/tests/scripts/generate-media.mjs b/client/tests/scripts/generate-media.mjs new file mode 100644 index 0000000..3929d41 --- /dev/null +++ b/client/tests/scripts/generate-media.mjs @@ -0,0 +1,121 @@ +#!/usr/bin/env node + +// Generates the three tiny, distinguishable H.264/AAC MP4 fixtures used by the +// browser tests into client/tests/fixtures/public/data/, which is served by +// vite.test.config.ts's publicDir. The clips are produced entirely from +// FFmpeg's own lavfi synthesizers (solid color video + sine tone audio), so +// they are licensed by construction — no third-party content is bundled. +// +// Usage: +// node client/tests/scripts/generate-media.mjs # skip existing +// node client/tests/scripts/generate-media.mjs --force # regenerate all +// +// The output directory is gitignored; run this script after cloning. + +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, unlinkSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const scriptDir = dirname(fileURLToPath(import.meta.url)); + +const outputDir = resolve(scriptDir, '../fixtures/public/data'); + +// One clip per color; each also carries a distinct sine tone so they are +// distinguishable by ear as well as by sight. +const clips = [ + { name: 'red.mp4', color: 'red', tone: 440 }, + { name: 'green.mp4', color: 'green', tone: 554 }, + { name: 'blue.mp4', color: 'blue', tone: 659 }, +]; + +const DURATION_SECONDS = 3; + +const force = process.argv.includes('--force'); + +function run(command, args) { + const result = spawnSync(command, args, { encoding: 'utf-8' }); + + if (result.error !== undefined) { + throw new Error( + `Failed to run ${command} (${result.error.message}). Is it installed and on PATH?`, + ); + } + + if (result.status !== 0) { + throw new Error( + `${command} ${args.join(' ')}\nfailed with status ${result.status}:\n${result.stderr}`, + ); + } + + return result.stdout; +} + +function generate(clip) { + // Mirrors the playback-relevant parts of the real converter: H.264 + // (yuv420p, level 4.1) + AAC stereo + +faststart. + run('ffmpeg', [ + '-y', + '-f', 'lavfi', + '-i', `color=c=${clip.color}:s=320x240:r=24:d=${DURATION_SECONDS}`, + '-f', 'lavfi', + '-i', `sine=frequency=${clip.tone}:b=0.5:d=${DURATION_SECONDS}`, + '-shortest', + '-c:v', 'libx264', + '-level', '4.1', + '-pix_fmt', 'yuv420p', + '-preset', 'veryfast', + '-crf', '30', + '-c:a', 'aac', + '-b:a', '64k', + '-ac', '2', + '-movflags', '+faststart', + resolve(outputDir, clip.name), + ]); +} + +function verify(clip) { + const videoCodec = run('ffprobe', [ + '-v', 'error', + '-select_streams', 'v:0', + '-show_entries', 'stream=codec_name', + '-of', 'csv=p=0', + resolve(outputDir, clip.name), + ]).trim(); + + const audioCodec = run('ffprobe', [ + '-v', 'error', + '-select_streams', 'a:0', + '-show_entries', 'stream=codec_name', + '-of', 'csv=p=0', + resolve(outputDir, clip.name), + ]).trim(); + + if (videoCodec !== 'h264' || audioCodec !== 'aac') { + throw new Error( + `${clip.name}: expected h264/aac streams, got ${videoCodec}/${audioCodec}`, + ); + } +} + +mkdirSync(outputDir, { recursive: true }); + +for (const clip of clips) { + const output = resolve(outputDir, clip.name); + + if (existsSync(output)) { + if (!force) { + console.log(`${clip.name}: already exists, skipping (--force to regenerate)`); + continue; + } + + unlinkSync(output); + } + + console.log(`${clip.name}: generating ${DURATION_SECONDS}s ${clip.color} clip...`); + + generate(clip); + verify(clip); + + console.log(`${clip.name}: ok (h264/aac)`); +} diff --git a/client/tests/unit/shared.test.ts b/client/tests/unit/shared.test.ts new file mode 100644 index 0000000..27465a1 --- /dev/null +++ b/client/tests/unit/shared.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest'; +import { ClientEvents, ServerEvents } from '../../src/shared'; + +// These strings are the wire protocol between client and server; pinning them +// catches accidental renames that would silently break synchronization. +describe('shared event contracts', (): void => { + it('pins the connection events', (): void => { + expect(ServerEvents.Connection.Accepted).toBe('connection:accepted'); + expect(ServerEvents.Connection.Rejected).toBe('connection:rejected'); + }); + + it('pins the cinema playback events', (): void => { + expect(ClientEvents.Cinema.Play).toBe('cinema:play'); + expect(ClientEvents.Cinema.Pause).toBe('cinema:pause'); + expect(ClientEvents.Cinema.Seek).toBe('cinema:seek'); + + expect(ServerEvents.Cinema.Playing).toBe('cinema:playing'); + expect(ServerEvents.Cinema.Paused).toBe('cinema:paused'); + expect(ServerEvents.Cinema.Seeked).toBe('cinema:seeked'); + }); +}); diff --git a/client/tsconfig.json b/client/tsconfig.json index 378dfd2..ff42a54 100644 --- a/client/tsconfig.json +++ b/client/tsconfig.json @@ -18,7 +18,7 @@ // Emit "outDir": "build", - "rootDir": "./src", + "rootDir": "./", "noEmit": true, "removeComments": true, "sourceMap": true, @@ -36,5 +36,5 @@ // Completeness "skipLibCheck": true }, - "include": ["src/**/*"] + "include": ["src/**/*", "tests/**/*", "*.config.ts"] } diff --git a/client/vite.test.config.ts b/client/vite.test.config.ts new file mode 100644 index 0000000..a276c12 --- /dev/null +++ b/client/vite.test.config.ts @@ -0,0 +1,25 @@ +import { defineConfig } from 'vite'; + +// Test-only Vite config for browser-test builds (consumed by the Playwright +// webServer). It serves fixture media from a fixture publicDir and redirects +// the settings.json import to a fixture so the user's client/settings.json +// and client/public/data/ are never read or written during tests. +const FIXTURE_SETTINGS_PATH = decodeURIComponent( + new URL('./tests/fixtures/player-settings.json', import.meta.url).pathname, +); + +export default defineConfig({ + publicDir: 'tests/fixtures/public', + resolve: { + alias: [ + { + find: '../settings.json', + replacement: FIXTURE_SETTINGS_PATH, + }, + ], + }, + server: { + port: 1730, + strictPort: true, + }, +}); diff --git a/client/vitest.config.ts b/client/vitest.config.ts new file mode 100644 index 0000000..6525842 --- /dev/null +++ b/client/vitest.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vitest/config'; + +// Node-environment unit tests only; DOM/media/UI behavior is covered by the +// Playwright browser tests. No DOM simulator (jsdom/happy-dom) is used. +export default defineConfig({ + test: { + environment: 'node', + include: ['tests/{unit,http}/**/*.test.ts'], + }, +}); diff --git a/converter/package.json b/converter/package.json index 0e095ca..68037b9 100644 --- a/converter/package.json +++ b/converter/package.json @@ -6,7 +6,9 @@ "dev": "bun --watch run src/main.ts", "start": "bun .", "typecheck": "bun run tsc", - "check-all": "bun run typecheck" + "check-all": "bun run typecheck", + "test": "bun test tests/unit", + "test:integration": "bun test tests/integration" }, "devDependencies": { "@types/bun": "latest", diff --git a/converter/tests/integration/smoke.test.ts b/converter/tests/integration/smoke.test.ts new file mode 100644 index 0000000..06883bb --- /dev/null +++ b/converter/tests/integration/smoke.test.ts @@ -0,0 +1,9 @@ +import { describe, expect, it } from 'bun:test'; + +// The converter shells out to ffmpeg, so integration tests cannot run without +// it on PATH. +describe('converter integration prerequisites', (): void => { + it('has ffmpeg on PATH', (): void => { + expect(Bun.which('ffmpeg')).not.toBeNull(); + }); +}); diff --git a/converter/tests/unit/smoke.test.ts b/converter/tests/unit/smoke.test.ts new file mode 100644 index 0000000..a3941e1 --- /dev/null +++ b/converter/tests/unit/smoke.test.ts @@ -0,0 +1,10 @@ +import { describe, expect, it } from 'bun:test'; +import { doTranscode } from '../../src/doTranscode'; + +// Harness smoke test: proves the test setup can import and evaluate the +// converter's TypeScript sources. +describe('converter unit harness', (): void => { + it('loads the transcode module', (): void => { + expect(typeof doTranscode).toBe('function'); + }); +}); diff --git a/converter/tsconfig.json b/converter/tsconfig.json index 1876808..ea23bb4 100644 --- a/converter/tsconfig.json +++ b/converter/tsconfig.json @@ -37,5 +37,6 @@ }, "include": [ "src", + "tests", ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b73a92d..f39ab46 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -11,6 +11,9 @@ importers: '@eslint/js': specifier: ^10.0.1 version: 10.0.1(eslint@10.4.1) + '@playwright/test': + specifier: 1.63.0 + version: 1.63.0 eslint: specifier: ^10.4.1 version: 10.4.1 @@ -26,6 +29,9 @@ importers: vite: specifier: ^8.0.16 version: 8.0.16(@types/node@25.9.3)(esbuild@0.28.0)(tsx@4.22.4) + vitest: + specifier: 4.1.6 + version: 4.1.6(@types/node@25.9.3)(vite@8.0.16(@types/node@25.9.3)(esbuild@0.28.0)(tsx@4.22.4)) server: dependencies: @@ -51,6 +57,9 @@ importers: typescript-eslint: specifier: ^8.61.0 version: 8.61.0(eslint@10.4.1)(typescript@6.0.3) + vitest: + specifier: 4.1.6 + version: 4.1.6(@types/node@25.9.3)(vite@8.0.16(@types/node@25.9.3)(esbuild@0.28.0)(tsx@4.22.4)) packages: @@ -278,6 +287,9 @@ packages: resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} engines: {node: '>=18.18'} + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + '@napi-rs/wasm-runtime@1.1.5': resolution: {integrity: sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==} peerDependencies: @@ -287,6 +299,11 @@ packages: '@oxc-project/types@0.133.0': resolution: {integrity: sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==} + '@playwright/test@1.63.0': + resolution: {integrity: sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==} + engines: {node: '>=20'} + hasBin: true + '@rolldown/binding-android-arm64@1.0.3': resolution: {integrity: sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -388,12 +405,21 @@ packages: '@socket.io/component-emitter@3.1.2': resolution: {integrity: sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==} + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@tybys/wasm-util@0.10.2': resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==} + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + '@types/cors@2.8.19': resolution: {integrity: sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==} + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + '@types/esrecurse@4.3.1': resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==} @@ -468,6 +494,35 @@ packages: resolution: {integrity: sha512-QVLZu3ZPQEE+HICQyAMZ2yLQhxf0meY/wx6Hx14YcTNj13JB3qHlX3lJ02L3fLGHgERRH71kvYDwiXIguT3AjQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@vitest/expect@4.1.6': + resolution: {integrity: sha512-7EHDquPthALSV0jhhjgEW8FXaviMx7rSqu8W6oqCoAuOhKov814P99QDV1pxMA3QPv21YudvJngIhjrNI4opLg==} + + '@vitest/mocker@4.1.6': + resolution: {integrity: sha512-MCFc63czMjEInOlcY2cpQCvCN+KgbAn+60xu9cMgP4sKaLC5JNAKw7JH8QdAnoAC88hW1IiSNZ+GgVXlN1UcMQ==} + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@4.1.6': + resolution: {integrity: sha512-h5SxD/IzNhZYnrSZRsUZQIC+vD0GY8cUvq0iwsmkFKixRCKLLWqCXa/FIQ4S1R+sI+PGoojkHsdNrbZiM9Qpgw==} + + '@vitest/runner@4.1.6': + resolution: {integrity: sha512-nOPCmn2+yD0ZNmKdsXGv/UxMMWbMuKeD6GyYncNwdkYDxpQvrPSKYj2rWuDjC2Y4b6w6hjip5dBKFzEUuZe3vA==} + + '@vitest/snapshot@4.1.6': + resolution: {integrity: sha512-YhsdE6xAVfTDmzjxL2ZDUvjj+ZsgyOKe+TdQzqkD72wIOmHka8NuGQ6NpTNZv9D2Z63fbwWKJPeVpEw4EQgYxw==} + + '@vitest/spy@4.1.6': + resolution: {integrity: sha512-JFKxMx6udhwKh/Ldo270e17QX710vgunMkuPAvXjHSvC6oqLWAHhVhjg/I71q0u0CBSErIODV1Kjv0FQNSWjdg==} + + '@vitest/utils@4.1.6': + resolution: {integrity: sha512-FxIY+U81R3LGKCxaHHFRQ5+g6/iRgGLmeHWdp2Amj4ljQRrEIWHmZyDfDYBRZlpyqA7qKxtS9DD1dhk8RnRIVQ==} + accepts@1.3.8: resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==} engines: {node: '>= 0.6'} @@ -485,6 +540,10 @@ packages: ajv@6.15.0: resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + balanced-match@4.0.4: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} @@ -497,6 +556,13 @@ packages: resolution: {integrity: sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==} engines: {node: 18 || 20 || >=22} + chai@6.3.0: + resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} + engines: {node: '>=18'} + + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + cookie@0.7.2: resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==} engines: {node: '>= 0.6'} @@ -536,6 +602,9 @@ packages: resolution: {integrity: sha512-2agL3ueZhqxoVrfmntO8yuVj+uNSlIOnhykYHk3Cq0ShYPdUjjUiSJrQvXjq01I9jAuI0Zl2YO8Evv5Mqytm5g==} engines: {node: '>=10.2.0'} + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + esbuild@0.28.0: resolution: {integrity: sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==} engines: {node: '>=18'} @@ -583,10 +652,17 @@ packages: resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} engines: {node: '>=4.0'} + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + esutils@2.0.3: resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} engines: {node: '>=0.10.0'} + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} @@ -746,6 +822,9 @@ packages: resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} engines: {node: '>=10'} + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + mime-db@1.52.0: resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} engines: {node: '>= 0.6'} @@ -777,6 +856,10 @@ packages: resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} engines: {node: '>=0.10.0'} + obug@2.2.1: + resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} + engines: {node: '>=12.20.0'} + optionator@0.9.4: resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} engines: {node: '>= 0.8.0'} @@ -797,6 +880,9 @@ packages: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -804,6 +890,16 @@ packages: resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} engines: {node: '>=12'} + playwright-core@1.63.0: + resolution: {integrity: sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.63.0: + resolution: {integrity: sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==} + engines: {node: '>=20'} + hasBin: true + postcss@8.5.15: resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==} engines: {node: ^10 || ^12 || >=14} @@ -834,6 +930,9 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + socket.io-adapter@2.5.7: resolution: {integrity: sha512-e0LyK91f3cUxTmv95/KzoLg47+zF+s/sbxRGDNsyG4dmIP8ZSX8ax6byOxfJXeNNtS/8AZlfD+uP7gBeR7DLlg==} @@ -853,10 +952,27 @@ packages: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} + tinyrainbow@3.2.0: + resolution: {integrity: sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==} + engines: {node: '>=14.0.0'} + ts-api-utils@2.5.0: resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==} engines: {node: '>=18.12'} @@ -940,11 +1056,57 @@ packages: yaml: optional: true + vitest@4.1.6: + resolution: {integrity: sha512-6lvjbS3p9b4CrdCmguzbh2/4uoXhGE2q71R4OX5sqF9R1bo9Xd6fGrMAfvp5wnCzlBnFVdCOp6onuTQVbo8iUQ==} + engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 4.1.6 + '@vitest/browser-preview': 4.1.6 + '@vitest/browser-webdriverio': 4.1.6 + '@vitest/coverage-istanbul': 4.1.6 + '@vitest/coverage-v8': 4.1.6 + '@vitest/ui': 4.1.6 + happy-dom: '*' + jsdom: '*' + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + which@2.0.2: resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} engines: {node: '>= 8'} hasBin: true + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + word-wrap@1.2.5: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} @@ -1115,6 +1277,8 @@ snapshots: '@humanwhocodes/retry@0.4.3': {} + '@jridgewell/sourcemap-codec@1.6.0': {} + '@napi-rs/wasm-runtime@1.1.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': dependencies: '@emnapi/core': 1.10.0 @@ -1124,6 +1288,10 @@ snapshots: '@oxc-project/types@0.133.0': {} + '@playwright/test@1.63.0': + dependencies: + playwright: 1.63.0 + '@rolldown/binding-android-arm64@1.0.3': optional: true @@ -1177,15 +1345,24 @@ snapshots: '@socket.io/component-emitter@3.1.2': {} + '@standard-schema/spec@1.1.0': {} + '@tybys/wasm-util@0.10.2': dependencies: tslib: 2.8.1 optional: true + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + '@types/cors@2.8.19': dependencies: '@types/node': 25.9.3 + '@types/deep-eql@4.0.2': {} + '@types/esrecurse@4.3.1': {} '@types/estree@1.0.9': {} @@ -1291,6 +1468,47 @@ snapshots: '@typescript-eslint/types': 8.61.0 eslint-visitor-keys: 5.0.1 + '@vitest/expect@4.1.6': + dependencies: + '@standard-schema/spec': 1.1.0 + '@types/chai': 5.2.3 + '@vitest/spy': 4.1.6 + '@vitest/utils': 4.1.6 + chai: 6.3.0 + tinyrainbow: 3.2.0 + + '@vitest/mocker@4.1.6(vite@8.0.16(@types/node@25.9.3)(esbuild@0.28.0)(tsx@4.22.4))': + dependencies: + '@vitest/spy': 4.1.6 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 8.0.16(@types/node@25.9.3)(esbuild@0.28.0)(tsx@4.22.4) + + '@vitest/pretty-format@4.1.6': + dependencies: + tinyrainbow: 3.2.0 + + '@vitest/runner@4.1.6': + dependencies: + '@vitest/utils': 4.1.6 + pathe: 2.0.3 + + '@vitest/snapshot@4.1.6': + dependencies: + '@vitest/pretty-format': 4.1.6 + '@vitest/utils': 4.1.6 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@4.1.6': {} + + '@vitest/utils@4.1.6': + dependencies: + '@vitest/pretty-format': 4.1.6 + convert-source-map: 2.0.0 + tinyrainbow: 3.2.0 + accepts@1.3.8: dependencies: mime-types: 2.1.35 @@ -1309,6 +1527,8 @@ snapshots: json-schema-traverse: 0.4.1 uri-js: 4.4.1 + assertion-error@2.0.1: {} + balanced-match@4.0.4: {} base64id@2.0.0: {} @@ -1317,6 +1537,10 @@ snapshots: dependencies: balanced-match: 4.0.4 + chai@6.3.0: {} + + convert-source-map@2.0.0: {} + cookie@0.7.2: {} cors@2.8.6: @@ -1369,6 +1593,8 @@ snapshots: - supports-color - utf-8-validate + es-module-lexer@2.3.2: {} + esbuild@0.28.0: optionalDependencies: '@esbuild/aix-ppc64': 0.28.0 @@ -1462,8 +1688,14 @@ snapshots: estraverse@5.3.0: {} + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + esutils@2.0.3: {} + expect-type@1.4.0: {} + fast-deep-equal@3.1.3: {} fast-json-stable-stringify@2.1.0: {} @@ -1579,6 +1811,10 @@ snapshots: dependencies: p-locate: 5.0.0 + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + mime-db@1.52.0: {} mime-types@2.1.35: @@ -1599,6 +1835,8 @@ snapshots: object-assign@4.1.1: {} + obug@2.2.1: {} + optionator@0.9.4: dependencies: deep-is: 0.1.4 @@ -1620,10 +1858,18 @@ snapshots: path-key@3.1.1: {} + pathe@2.0.3: {} + picocolors@1.1.1: {} picomatch@4.0.4: {} + playwright-core@1.63.0: {} + + playwright@1.63.0: + dependencies: + playwright-core: 1.63.0 + postcss@8.5.15: dependencies: nanoid: 3.3.12 @@ -1663,6 +1909,8 @@ snapshots: shebang-regex@3.0.0: {} + siginfo@2.0.0: {} + socket.io-adapter@2.5.7: dependencies: debug: 4.4.3 @@ -1706,11 +1954,21 @@ snapshots: source-map-js@1.2.1: {} + stackback@0.0.2: {} + + std-env@4.3.0: {} + + tinybench@2.9.0: {} + + tinyexec@1.3.1: {} + tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.4) picomatch: 4.0.4 + tinyrainbow@3.2.0: {} + ts-api-utils@2.5.0(typescript@6.0.3): dependencies: typescript: 6.0.3 @@ -1762,10 +2020,42 @@ snapshots: fsevents: 2.3.3 tsx: 4.22.4 + vitest@4.1.6(@types/node@25.9.3)(vite@8.0.16(@types/node@25.9.3)(esbuild@0.28.0)(tsx@4.22.4)): + dependencies: + '@vitest/expect': 4.1.6 + '@vitest/mocker': 4.1.6(vite@8.0.16(@types/node@25.9.3)(esbuild@0.28.0)(tsx@4.22.4)) + '@vitest/pretty-format': 4.1.6 + '@vitest/runner': 4.1.6 + '@vitest/snapshot': 4.1.6 + '@vitest/spy': 4.1.6 + '@vitest/utils': 4.1.6 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 0.30.21 + obug: 2.2.1 + pathe: 2.0.3 + picomatch: 4.0.4 + std-env: 4.3.0 + tinybench: 2.9.0 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + tinyrainbow: 3.2.0 + vite: 8.0.16(@types/node@25.9.3)(esbuild@0.28.0)(tsx@4.22.4) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 25.9.3 + transitivePeerDependencies: + - msw + which@2.0.2: dependencies: isexe: 2.0.0 + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + word-wrap@1.2.5: {} ws@8.20.1: {} diff --git a/server/package.json b/server/package.json index f471791..a94a62a 100644 --- a/server/package.json +++ b/server/package.json @@ -14,9 +14,10 @@ }, "scripts": { "build": "tsc", - "typecheck": "tsc --noEmit", - "lint": "eslint src --max-warnings=0", + "typecheck": "tsc --noEmit && tsc --noEmit -p tests/tsconfig.json", + "lint": "eslint src tests --max-warnings=0", "check-all": "pnpm run typecheck && pnpm run lint", + "test": "vitest run", "start": "node build/index.js", "dev": "node --import tsx --env-file=.env --watch-path=src --disable-warning=ExperimentalWarning src/index.ts" }, @@ -29,6 +30,7 @@ "eslint": "^10.4.1", "tsx": "^4.16.0", "typescript": "^6.0.3", - "typescript-eslint": "^8.61.0" + "typescript-eslint": "^8.61.0", + "vitest": "4.1.6" } } diff --git a/server/tests/helpers/testApp.ts b/server/tests/helpers/testApp.ts new file mode 100644 index 0000000..de4cc22 --- /dev/null +++ b/server/tests/helpers/testApp.ts @@ -0,0 +1,8 @@ +/** + * Placeholder for the server test-application factory (fleshed out in Task 5). + * + * Intended purpose: build an in-process Socket.IO server bound to an ephemeral + * port with deterministic room state, so integration tests can connect real + * socket.io clients without touching a production server. + */ +export const TEST_APP_PENDING = true; diff --git a/server/tests/tsconfig.json b/server/tests/tsconfig.json new file mode 100644 index 0000000..5dba058 --- /dev/null +++ b/server/tests/tsconfig.json @@ -0,0 +1,10 @@ +{ + // https://www.typescriptlang.org/tsconfig/ + "extends": "../tsconfig.json", + "compilerOptions": { + // Tests live outside src/, so widen rootDir; nothing is emitted. + "noEmit": true, + "rootDir": "../" + }, + "include": ["./**/*", "../vitest.config.ts"] +} diff --git a/server/tests/unit/shared.test.ts b/server/tests/unit/shared.test.ts new file mode 100644 index 0000000..1a1369a --- /dev/null +++ b/server/tests/unit/shared.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest'; +import { ServerEvents } from '../../src/shared/index.js'; + +// These strings are the wire protocol between client and server; pinning them +// catches accidental renames that would silently break synchronization. +describe('shared event contracts', (): void => { + it('pins the connection events', (): void => { + expect(ServerEvents.Connection.Accepted).toBe('connection:accepted'); + expect(ServerEvents.Connection.Rejected).toBe('connection:rejected'); + }); + + it('pins the cinema room events', (): void => { + expect(ServerEvents.Cinema.Users).toBe('cinema:users'); + expect(ServerEvents.Cinema.Joined).toBe('cinema:joined'); + expect(ServerEvents.Cinema.Left).toBe('cinema:left'); + }); +}); diff --git a/server/vitest.config.ts b/server/vitest.config.ts new file mode 100644 index 0000000..4e97aa8 --- /dev/null +++ b/server/vitest.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vitest/config'; + +// Node-environment tests only; integration tests spin up in-process servers +// (see tests/helpers/testApp.ts). +export default defineConfig({ + test: { + environment: 'node', + include: ['tests/{unit,integration}/**/*.test.ts'], + }, +}); From 29daa2043b94f33a897ffa6d926d57c07405c972 Mon Sep 17 00:00:00 2001 From: Aaron Guo <89121695+PolarWolf314@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:34:04 +1300 Subject: [PATCH 04/58] fix: verify existing fixtures and report child signals in media generator The skip path now runs the same ffprobe verification used after generation and regenerates automatically when a fixture is truncated or corrupt, instead of letting it slip through and surface later as cryptic browser-test decode errors. Children killed by a signal are reported with the signal name rather than 'status null', and main() is wrapped so failures print a clean one-line error and set exit code 1. --- client/tests/scripts/generate-media.mjs | 56 ++++++++++++++++++------- 1 file changed, 41 insertions(+), 15 deletions(-) diff --git a/client/tests/scripts/generate-media.mjs b/client/tests/scripts/generate-media.mjs index 3929d41..05946d1 100644 --- a/client/tests/scripts/generate-media.mjs +++ b/client/tests/scripts/generate-media.mjs @@ -43,8 +43,15 @@ function run(command, args) { } if (result.status !== 0) { + // A child killed by a signal has status null; report the signal + // instead of a confusing "failed with status null". + const reason = + result.signal !== null + ? `killed by signal ${result.signal}` + : `failed with status ${result.status}`; + throw new Error( - `${command} ${args.join(' ')}\nfailed with status ${result.status}:\n${result.stderr}`, + `${command} ${args.join(' ')}\n${reason}:\n${result.stderr}`, ); } @@ -98,24 +105,43 @@ function verify(clip) { } } -mkdirSync(outputDir, { recursive: true }); - -for (const clip of clips) { - const output = resolve(outputDir, clip.name); +function main() { + mkdirSync(outputDir, { recursive: true }); + + for (const clip of clips) { + const output = resolve(outputDir, clip.name); + + // An existing file is only trusted if it still verifies; a truncated + // or corrupt fixture would otherwise slip through here and blow up + // later with cryptic decode errors inside the browser tests. + if (existsSync(output) && !force) { + try { + verify(clip); + console.log( + `${clip.name}: already exists and verifies, skipping (--force to regenerate)`, + ); + continue; + } catch { + console.warn(`${clip.name}: failed verification, regenerating`); + } + } - if (existsSync(output)) { - if (!force) { - console.log(`${clip.name}: already exists, skipping (--force to regenerate)`); - continue; + if (existsSync(output)) { + unlinkSync(output); } - unlinkSync(output); - } + console.log(`${clip.name}: generating ${DURATION_SECONDS}s ${clip.color} clip...`); - console.log(`${clip.name}: generating ${DURATION_SECONDS}s ${clip.color} clip...`); + generate(clip); + verify(clip); - generate(clip); - verify(clip); + console.log(`${clip.name}: ok (h264/aac)`); + } +} - console.log(`${clip.name}: ok (h264/aac)`); +try { + main(); +} catch (error) { + console.error(`error: ${error.message}`); + process.exitCode = 1; } From 1b16db3483708ea6297d002719a9e3550d8dda2b Mon Sep 17 00:00:00 2001 From: Aaron Guo <89121695+PolarWolf314@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:34:04 +1300 Subject: [PATCH 05/58] test: pin full wire contracts; hoist server eslint ignores; document testing Both shared.test.ts suites now pin every enum value of Connection, WaitingRoom, Cinema and Admin (ClientEvents + ServerEvents) from their own workspace's src/shared copies, closing the coverage gaps where a rename on one side would go unnoticed. Also hoists the server eslint ignores into a standalone global-ignores object mirroring the client config, notes the playwright-install prerequisite where projects are defined, and adds a Testing subsection to the README. --- README.md | 22 ++++++++++++++++++++++ client/playwright.config.ts | 3 +++ client/tests/unit/shared.test.ts | 23 ++++++++++++++++++++++- server/eslint.config.js | 6 +++++- server/tests/unit/shared.test.ts | 31 ++++++++++++++++++++++++++++--- 5 files changed, 80 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index f8f3756..d09c5fa 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,28 @@ pnpm typecheck # TypeScript type checking pnpm lint # ESLint (client and server only) ``` +### Testing + +Unit tests run with vitest (client/server) and bun test (converter): + +```sh +pnpm --dir client run test +pnpm --dir server run test +cd converter && bun run test && bun run test:integration +``` + +Browser tests run Playwright against a real browser. `test:browser` pins chromium for now — to cover the rest, install the other engines (`pnpm --dir client exec playwright install firefox webkit`) and then run `pnpm --dir client exec playwright test` without the project pin: + +```sh +pnpm --dir client run test:browser +``` + +Browser tests need three tiny generated video fixtures (the output is gitignored), so bootstrap them once after cloning: + +```sh +node client/tests/scripts/generate-media.mjs +``` + ### Formatting This project uses [Prettier](https://prettier.io/) and [EditorConfig](https://editorconfig.org/) for consistent formatting: diff --git a/client/playwright.config.ts b/client/playwright.config.ts index 4a59e30..1bfa211 100644 --- a/client/playwright.config.ts +++ b/client/playwright.config.ts @@ -14,6 +14,9 @@ export default defineConfig({ baseURL: 'http://localhost:1730', trace: 'retain-on-failure', }, + // firefox/webkit need their browsers installed first: + // pnpm --dir client exec playwright install firefox webkit + // test:browser pins --project=chromium until both are installed. projects: [ { name: 'chromium', diff --git a/client/tests/unit/shared.test.ts b/client/tests/unit/shared.test.ts index 27465a1..298ddc0 100644 --- a/client/tests/unit/shared.test.ts +++ b/client/tests/unit/shared.test.ts @@ -9,13 +9,34 @@ describe('shared event contracts', (): void => { expect(ServerEvents.Connection.Rejected).toBe('connection:rejected'); }); - it('pins the cinema playback events', (): void => { + it('pins the waiting-room events', (): void => { + expect(ServerEvents.WaitingRoom.Joined).toBe('waiting-room:joined'); + expect(ServerEvents.WaitingRoom.Left).toBe('waiting-room:left'); + }); + + it('pins the cinema events', (): void => { expect(ClientEvents.Cinema.Play).toBe('cinema:play'); expect(ClientEvents.Cinema.Pause).toBe('cinema:pause'); expect(ClientEvents.Cinema.Seek).toBe('cinema:seek'); + expect(ServerEvents.Cinema.Joined).toBe('cinema:joined'); + expect(ServerEvents.Cinema.Left).toBe('cinema:left'); + expect(ServerEvents.Cinema.Users).toBe('cinema:users'); expect(ServerEvents.Cinema.Playing).toBe('cinema:playing'); expect(ServerEvents.Cinema.Paused).toBe('cinema:paused'); expect(ServerEvents.Cinema.Seeked).toBe('cinema:seeked'); }); + + it('pins the admin events', (): void => { + expect(ClientEvents.Admin.Kick).toBe('admin:kick'); + expect(ClientEvents.Admin.Ban).toBe('admin:ban'); + expect(ClientEvents.Admin.Approve).toBe('admin:approve'); + + expect(ServerEvents.Admin.Added).toBe('admin:added'); + expect(ServerEvents.Admin.Left).toBe('admin:left'); + expect(ServerEvents.Admin.Users).toBe('admin:users'); + expect(ServerEvents.Admin.Kicked).toBe('admin:kicked'); + expect(ServerEvents.Admin.Banned).toBe('admin:banned'); + expect(ServerEvents.Admin.Approved).toBe('admin:approved'); + }); }); diff --git a/server/eslint.config.js b/server/eslint.config.js index 4ca8bae..49c8abf 100644 --- a/server/eslint.config.js +++ b/server/eslint.config.js @@ -4,6 +4,11 @@ import eslint from '@eslint/js'; import tseslint from 'typescript-eslint'; export default tseslint.config( + { + // Standalone `ignores` objects are global; `ignores` inside a config + // with rules would only be scoped to that object. + ignores: ['eslint.config.js', 'build/**', 'node_modules/**'], + }, eslint.configs.recommended, ...tseslint.configs.strictTypeChecked, ...tseslint.configs.stylisticTypeChecked, @@ -14,7 +19,6 @@ export default tseslint.config( tsconfigRootDir: import.meta.dirname, }, }, - ignores: ['eslint.config.js', 'build/**', 'node_modules/**'], rules: { // Possible Problems (https://eslint.org/docs/latest/rules/#possible-problems) diff --git a/server/tests/unit/shared.test.ts b/server/tests/unit/shared.test.ts index 1a1369a..f8afaef 100644 --- a/server/tests/unit/shared.test.ts +++ b/server/tests/unit/shared.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { ServerEvents } from '../../src/shared/index.js'; +import { ClientEvents, ServerEvents } from '../../src/shared/index.js'; // These strings are the wire protocol between client and server; pinning them // catches accidental renames that would silently break synchronization. @@ -9,9 +9,34 @@ describe('shared event contracts', (): void => { expect(ServerEvents.Connection.Rejected).toBe('connection:rejected'); }); - it('pins the cinema room events', (): void => { - expect(ServerEvents.Cinema.Users).toBe('cinema:users'); + it('pins the waiting-room events', (): void => { + expect(ServerEvents.WaitingRoom.Joined).toBe('waiting-room:joined'); + expect(ServerEvents.WaitingRoom.Left).toBe('waiting-room:left'); + }); + + it('pins the cinema events', (): void => { + expect(ClientEvents.Cinema.Play).toBe('cinema:play'); + expect(ClientEvents.Cinema.Pause).toBe('cinema:pause'); + expect(ClientEvents.Cinema.Seek).toBe('cinema:seek'); + expect(ServerEvents.Cinema.Joined).toBe('cinema:joined'); expect(ServerEvents.Cinema.Left).toBe('cinema:left'); + expect(ServerEvents.Cinema.Users).toBe('cinema:users'); + expect(ServerEvents.Cinema.Playing).toBe('cinema:playing'); + expect(ServerEvents.Cinema.Paused).toBe('cinema:paused'); + expect(ServerEvents.Cinema.Seeked).toBe('cinema:seeked'); + }); + + it('pins the admin events', (): void => { + expect(ClientEvents.Admin.Kick).toBe('admin:kick'); + expect(ClientEvents.Admin.Ban).toBe('admin:ban'); + expect(ClientEvents.Admin.Approve).toBe('admin:approve'); + + expect(ServerEvents.Admin.Added).toBe('admin:added'); + expect(ServerEvents.Admin.Left).toBe('admin:left'); + expect(ServerEvents.Admin.Users).toBe('admin:users'); + expect(ServerEvents.Admin.Kicked).toBe('admin:kicked'); + expect(ServerEvents.Admin.Banned).toBe('admin:banned'); + expect(ServerEvents.Admin.Approved).toBe('admin:approved'); }); }); From d3ab065aef450803fdf5d3eb695b88d5fe8df704 Mon Sep 17 00:00:00 2001 From: Aaron Guo <89121695+PolarWolf314@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:54:36 +1300 Subject: [PATCH 06/58] feat(diagnostics): add issue store with incident merging and normalization UI-independent issue/diagnostics data layer (PR 1 of the playback reliability work). Known issue codes map to fixed neutral messages, severity, blocking status, and permitted recovery actions. Repeated reports of one incident key fold into a single issue with an occurrence count; media network and decode failures share a per-media incident. Subscribers get current-state replay, bounded active issues (16) evict the least recently reported, and every entry point tolerates garbage, circular, and primitive values without throwing. --- client/src/diagnostics/issues.ts | 372 +++++++++++++++++++++++++++++ client/src/diagnostics/snapshot.ts | 128 ++++++++++ client/tests/unit/issues.test.ts | 210 ++++++++++++++++ 3 files changed, 710 insertions(+) create mode 100644 client/src/diagnostics/issues.ts create mode 100644 client/src/diagnostics/snapshot.ts create mode 100644 client/tests/unit/issues.test.ts diff --git a/client/src/diagnostics/issues.ts b/client/src/diagnostics/issues.ts new file mode 100644 index 0000000..765acf4 --- /dev/null +++ b/client/src/diagnostics/issues.ts @@ -0,0 +1,372 @@ +import { + ACTIVE_ISSUE_LIMIT, + DiagnosticEvent, + Issue, + IssueCode, + IssueDefinition, + IssueInput, + IssueListener, + IssueSnapshot, + RecoveryAction, + Severity, +} from './snapshot'; + +/** + * Fixed definitions for every known issue code. Messages are neutral and + * actionable: they never speculate about causes (a failed request does not + * prove an extension blocked it; an unusable source does not prove a bad + * codec) and never embed raw error text. + */ +export const ISSUE_CATALOG: Readonly> = { + [IssueCode.PlaybackInteractionRequired]: { + code: IssueCode.PlaybackInteractionRequired, + message: 'Playback is ready, but the browser needs you to press play to start it.', + severity: Severity.Warning, + blocking: true, + recoveryActions: [RecoveryAction.Retry], + }, + [IssueCode.MediaNetwork]: { + code: IssueCode.MediaNetwork, + message: 'The video could not load just now. Check your connection, then try again.', + severity: Severity.Critical, + blocking: true, + recoveryActions: [RecoveryAction.Retry], + }, + [IssueCode.MediaDecode]: { + code: IssueCode.MediaDecode, + message: 'The video stopped because this browser could not decode it. Trying again, or switching browsers, may help.', + severity: Severity.Critical, + blocking: true, + recoveryActions: [RecoveryAction.Retry], + }, + [IssueCode.MediaUnusable]: { + code: IssueCode.MediaUnusable, + message: 'The current video source cannot be used. Ask the host to check the shared video, then try again.', + severity: Severity.Critical, + blocking: true, + recoveryActions: [RecoveryAction.Retry], + }, + [IssueCode.MediaMismatch]: { + code: IssueCode.MediaMismatch, + message: 'Your video does not match the one the room is watching. Reloading will resynchronize playback.', + severity: Severity.Warning, + blocking: true, + recoveryActions: [RecoveryAction.Reload], + }, + [IssueCode.SlowLoading]: { + code: IssueCode.SlowLoading, + message: 'The video is taking longer than usual to load, so playback may stall.', + severity: Severity.Info, + blocking: false, + recoveryActions: [], + }, + [IssueCode.ConnectionLost]: { + code: IssueCode.ConnectionLost, + message: 'The connection to the room was lost. Reconnect or reload to rejoin.', + severity: Severity.Critical, + blocking: true, + recoveryActions: [RecoveryAction.Reconnect, RecoveryAction.Reload], + }, + [IssueCode.StorageUnavailable]: { + code: IssueCode.StorageUnavailable, + message: 'Browser storage is unavailable, so preferences like your name cannot be saved.', + severity: Severity.Info, + blocking: false, + recoveryActions: [], + }, + [IssueCode.InvalidServerState]: { + code: IssueCode.InvalidServerState, + message: 'The server sent room state that cannot be used. Reloading will resynchronize the room.', + severity: Severity.Warning, + blocking: true, + recoveryActions: [RecoveryAction.Reload], + }, + [IssueCode.AppInit]: { + code: IssueCode.AppInit, + message: 'The app failed to start. Reload the page to try again.', + severity: Severity.Critical, + blocking: true, + recoveryActions: [RecoveryAction.Reload], + }, + [IssueCode.Unexpected]: { + code: IssueCode.Unexpected, + message: 'Something unexpected went wrong. Reload the page if anything looks off.', + severity: Severity.Warning, + blocking: false, + recoveryActions: [RecoveryAction.Reload], + }, +}; + +const GLOBAL_SCOPE = 'global'; + +/** Incident family shared by related media source errors (network + decode). */ +const MEDIA_PLAYBACK_INCIDENT = 'media-playback'; + +const MAX_MEDIA_ID_LENGTH = 64; +const MAX_NAME_LENGTH = 64; + +/** Module-local incident counter; ids must not depend on a secure context. */ +let incidentCounter = 0; + +function nextIncidentId(): string { + incidentCounter += 1; + return `issue-${String(incidentCounter)}`; +} + +/** Internal mutable incident record; snapshots expose defensive copies. */ +interface MutableIssue { + readonly id: string; + readonly key: string; + code: IssueCode; + mediaId?: string; + occurrences: number; + mediaErrorCode?: number; + readonly firstSeen: number; + lastSeen: number; +} + +interface NormalizedIssueInput { + readonly code: IssueCode; + readonly mediaId: string | undefined; + readonly error: unknown; + readonly mediaErrorCode: number | undefined; +} + +/** + * Incident keying scheme: `${canonicalCode}:${scope}`. + * + * - The scope is the media id for media-scoped reports and `global` otherwise. + * - `MediaNetwork` and `MediaDecode` both key to `media-playback:${mediaId}` + * so related source failures refine one per-media incident instead of + * creating two; the incident's code tracks the most recent report. + * - All other codes key directly, e.g. `connection-lost:global`. + */ +function issueKeyFor(code: IssueCode, mediaId: string | undefined): string { + const scope = mediaId ?? GLOBAL_SCOPE; + if (code === IssueCode.MediaNetwork || code === IssueCode.MediaDecode) { + return `${MEDIA_PLAYBACK_INCIDENT}:${scope}`; + } + return `${code}:${scope}`; +} + +function toRecord(value: unknown): Record { + return typeof value === 'object' && value !== null ? (value as Record) : {}; +} + +function isIssueCode(value: unknown): value is IssueCode { + return typeof value === 'string' && Object.prototype.hasOwnProperty.call(ISSUE_CATALOG, value); +} + +/** Reads a finite numeric `code`/`mediaErrorCode` property from any value. */ +function extractMediaErrorCode(value: unknown): number | undefined { + const record = toRecord(value); + const candidate = record['code'] ?? record['mediaErrorCode']; + return typeof candidate === 'number' && Number.isFinite(candidate) ? candidate : undefined; +} + +/** Tolerates garbage, primitives, circular references, and hostile proxies. */ +function normalizeIssueInput(input: unknown): NormalizedIssueInput { + const record = toRecord(input); + const rawCode = record['code']; + const rawMediaId = record['mediaId']; + const error = record['error']; + const mediaErrorCode = extractMediaErrorCode(error) ?? extractMediaErrorCode(record['detail']); + return { + code: isIssueCode(rawCode) ? rawCode : IssueCode.Unexpected, + mediaId: + typeof rawMediaId === 'string' && rawMediaId.length > 0 && rawMediaId.length <= MAX_MEDIA_ID_LENGTH + ? rawMediaId + : undefined, + error, + mediaErrorCode, + }; +} + +/** Extracts a safe error identifier (the constructor name) from any value. */ +export function normalizeErrorName(error: unknown): string | undefined { + if (typeof error !== 'object' || error === null) { + return undefined; + } + try { + const name = (error as { readonly name?: unknown }).name; + if (typeof name === 'string' && name.length > 0 && name.length <= MAX_NAME_LENGTH) { + return name; + } + const constructor = (error as { readonly constructor?: unknown }).constructor; + if (typeof constructor === 'function') { + const constructorName = (constructor as { readonly name?: unknown }).name; + if (typeof constructorName === 'string' && constructorName.length > 0 && constructorName.length <= MAX_NAME_LENGTH) { + return constructorName; + } + } + return 'Object'; + } catch { + // Reading properties from a hostile proxy can throw; never propagate. + return 'Object'; + } +} + +function toPublicIssue(incident: MutableIssue): Issue { + const definition: IssueDefinition = ISSUE_CATALOG[incident.code]; + const issue: Issue = { + id: incident.id, + key: incident.key, + code: incident.code, + message: definition.message, + severity: definition.severity, + blocking: definition.blocking, + recoveryActions: definition.recoveryActions, + occurrences: incident.occurrences, + firstSeen: incident.firstSeen, + lastSeen: incident.lastSeen, + ...(incident.mediaId !== undefined ? { mediaId: incident.mediaId } : {}), + ...(incident.mediaErrorCode !== undefined ? { mediaErrorCode: incident.mediaErrorCode } : {}), + }; + return Object.freeze(issue); +} + +export interface IssueStore { + reportIssue(input: IssueInput): void; + resolveIssue(id: string): void; + subscribeIssues(listener: IssueListener): () => void; + getIssueSnapshot(): IssueSnapshot; + recordDiagnostic(event: DiagnosticEvent): void; + exportDiagnostics(): string; +} + +/** + * Creates an issue store. `now` is injectable for deterministic timestamps. + * All mutating entry points tolerate arbitrary garbage and never throw. + */ +export function createIssueStore(now: () => number = Date.now): IssueStore { + /** Active incidents by incident key. */ + const active = new Map(); + /** Allowlisted diagnostic events (bounded ring). */ + const history: DiagnosticEvent[] = []; + const listeners = new Set(); + + function snapshot(): IssueSnapshot { + return { issues: Object.freeze([...active.values()].map(toPublicIssue)) }; + } + + function notify(): void { + const current = snapshot(); + for (const listener of [...listeners]) { + try { + listener(current); + } catch (error) { + console.warn('[panopticon] issue listener threw', error); + } + } + } + + function evictIfNeeded(): void { + while (active.size > ACTIVE_ISSUE_LIMIT) { + let oldestKey: string | undefined; + let oldestSeen = Number.POSITIVE_INFINITY; + for (const [key, incident] of active) { + if (incident.lastSeen < oldestSeen) { + oldestSeen = incident.lastSeen; + oldestKey = key; + } + } + if (oldestKey === undefined) { + break; + } + active.delete(oldestKey); + } + } + + function reportIssue(input: IssueInput): void { + try { + const at = now(); + const normalized = normalizeIssueInput(input); + const key = issueKeyFor(normalized.code, normalized.mediaId); + const incident = active.get(key); + + if (incident === undefined) { + const fresh: MutableIssue = { + id: nextIncidentId(), + key, + code: normalized.code, + occurrences: 1, + firstSeen: at, + lastSeen: at, + }; + if (normalized.mediaId !== undefined) { + fresh.mediaId = normalized.mediaId; + } + if (normalized.mediaErrorCode !== undefined) { + fresh.mediaErrorCode = normalized.mediaErrorCode; + } + active.set(key, fresh); + evictIfNeeded(); + } else { + incident.code = normalized.code; + incident.occurrences += 1; + incident.lastSeen = at; + if (normalized.mediaErrorCode !== undefined) { + incident.mediaErrorCode = normalized.mediaErrorCode; + } + } + + notify(); + } catch (failure) { + console.warn('[panopticon] failed to record issue', failure); + } + } + + function resolveIssue(id: string): void { + try { + for (const [key, incident] of active) { + if (incident.id === id) { + active.delete(key); + notify(); + return; + } + } + } catch (failure) { + console.warn('[panopticon] failed to resolve issue', failure); + } + } + + function subscribeIssues(listener: IssueListener): () => void { + listeners.add(listener); + try { + listener(snapshot()); + } catch (error) { + console.warn('[panopticon] issue listener threw during replay', error); + } + return (): void => { + listeners.delete(listener); + }; + } + + function getIssueSnapshot(): IssueSnapshot { + return snapshot(); + } + + function recordDiagnostic(event: DiagnosticEvent): void { + try { + history.push(event); + } catch (failure) { + console.warn('[panopticon] failed to record diagnostic', failure); + } + } + + function exportDiagnostics(): string { + return ''; + } + + return { + reportIssue, + resolveIssue, + subscribeIssues, + getIssueSnapshot, + recordDiagnostic, + exportDiagnostics, + }; +} + +/** Shared application-wide store; tests create isolated stores instead. */ +export const issueStore: IssueStore = createIssueStore(); diff --git a/client/src/diagnostics/snapshot.ts b/client/src/diagnostics/snapshot.ts new file mode 100644 index 0000000..ab787f7 --- /dev/null +++ b/client/src/diagnostics/snapshot.ts @@ -0,0 +1,128 @@ +/** + * Data contract for the diagnostics layer. + * + * This module owns the shapes shared between the issue store, the runtime + * handlers, and (in PR 2) the UI. It must stay presentation-free and must + * never import from controllers, styles, or other application modules. + */ + +/** Maximum retained diagnostic events; oldest entries are evicted first. */ +export const DIAGNOSTIC_HISTORY_LIMIT = 50; + +/** Maximum simultaneously active issues; the least recently reported is evicted. */ +export const ACTIVE_ISSUE_LIMIT = 16; + +/** How disruptive an issue is to the core experience. */ +export const enum Severity { + Info = 'info', + Warning = 'warning', + Critical = 'critical', +} + +/** User-initiated recovery actions an issue permits. */ +export const enum RecoveryAction { + /** Try the failed operation again (e.g. attempt playback once more). */ + Retry = 'retry', + /** Reload the page. */ + Reload = 'reload', + /** Ask the socket to reconnect. */ + Reconnect = 'reconnect', +} + +/** + * Canonical issue codes. These are the keys PR 2's message catalog will use; + * they are also the only error identifiers that ever reach user-facing text. + */ +export const enum IssueCode { + /** Playback is waiting for a user gesture before it can start. */ + PlaybackInteractionRequired = 'playback-interaction-required', + /** The media request failed at the network layer (MEDIA_ERR_NETWORK). */ + MediaNetwork = 'media-network', + /** The media data could not be decoded (MEDIA_ERR_DECODE). */ + MediaDecode = 'media-decode', + /** The media source cannot be used (MEDIA_ERR_SRC_NOT_SUPPORTED). */ + MediaUnusable = 'media-unusable', + /** The local media does not match what the room is watching. */ + MediaMismatch = 'media-mismatch', + /** Loading is progressing slower than the configured threshold. */ + SlowLoading = 'slow-loading', + /** The connection to the room was lost. */ + ConnectionLost = 'connection-lost', + /** Browser storage is unavailable. */ + StorageUnavailable = 'storage-unavailable', + /** The server sent state the client cannot interpret. */ + InvalidServerState = 'invalid-server-state', + /** Application bootstrap failed (module load or initialization). */ + AppInit = 'app-init', + /** Any failure that does not map to a known code. */ + Unexpected = 'unexpected', +} + +/** Fixed definition for a known issue code. Messages are neutral and actionable. */ +export interface IssueDefinition { + readonly code: IssueCode; + readonly message: string; + readonly severity: Severity; + /** True when the issue prevents the core experience until resolved. */ + readonly blocking: boolean; + readonly recoveryActions: readonly RecoveryAction[]; +} + +/** An active (or recently reported) issue incident, as exposed to subscribers. */ +export interface Issue { + /** Stable identifier for this incident (module-local counter). */ + readonly id: string; + /** Incident identity key; see the store's documented keying scheme. */ + readonly key: string; + readonly code: IssueCode; + /** Local media element identifier, when the issue is media-scoped. */ + readonly mediaId?: string; + readonly message: string; + readonly severity: Severity; + readonly blocking: boolean; + readonly recoveryActions: readonly RecoveryAction[]; + /** How many reports were folded into this incident. */ + readonly occurrences: number; + /** Last seen numeric media error code (MEDIA_ERR_*), if any. */ + readonly mediaErrorCode?: number; + readonly firstSeen: number; + readonly lastSeen: number; +} + +/** Immutable view of the active issue set, replayed to every new subscriber. */ +export interface IssueSnapshot { + readonly issues: readonly Issue[]; +} + +/** Listener notified with a fresh snapshot whenever active issues change. */ +export type IssueListener = (snapshot: IssueSnapshot) => void; + +/** + * Input accepted by `IssueStore.reportIssue`. Every field is normalized at + * runtime: garbage codes collapse to `Unexpected`, and `error`/`detail` are + * never stringified into user-visible or persisted text. + */ +export interface IssueInput { + readonly code?: IssueCode | string; + readonly mediaId?: string; + readonly error?: unknown; + readonly detail?: unknown; +} + +/** + * Allowlisted diagnostic event. Fields are deliberately narrow: error *names* + * (never messages), numeric media codes, boolean markers, and numeric + * readings (booleans should be recorded as 0/1). Anything else is dropped. + */ +export interface DiagnosticEvent { + /** Machine-readable event kind, e.g. 'window-error' or 'extension-error'. */ + readonly type: string; + /** Epoch timestamp in milliseconds. */ + readonly at: number; + readonly errorName?: string; + readonly mediaErrorCode?: number; + /** True when the event's script origin looked like a browser extension. */ + readonly extensionOrigin?: boolean; + /** Numeric measurements (clock skew, readiness, buffer, frames, flags). */ + readonly readings?: Readonly>; +} diff --git a/client/tests/unit/issues.test.ts b/client/tests/unit/issues.test.ts new file mode 100644 index 0000000..99d6bdc --- /dev/null +++ b/client/tests/unit/issues.test.ts @@ -0,0 +1,210 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createIssueStore, ISSUE_CATALOG, normalizeErrorName } from '../../src/diagnostics/issues'; +import { ACTIVE_ISSUE_LIMIT, IssueCode, IssueInput, IssueSnapshot } from '../../src/diagnostics/snapshot'; + +afterEach((): void => { + vi.restoreAllMocks(); +}); + +describe('issue store', (): void => { + it('replays current state to subscribers that attach after reports', (): void => { + const store = createIssueStore(); + store.reportIssue({ code: IssueCode.ConnectionLost }); + + let received: IssueSnapshot | undefined; + store.subscribeIssues((snapshot: IssueSnapshot): void => { + received = snapshot; + }); + + expect(received?.issues).toHaveLength(1); + expect(received?.issues[0]?.code).toBe(IssueCode.ConnectionLost); + }); + + it('merges repeated reports into one incident with an occurrence count', (): void => { + const store = createIssueStore(); + + store.reportIssue({ code: IssueCode.MediaNetwork, mediaId: 'movie' }); + store.reportIssue({ code: IssueCode.MediaNetwork, mediaId: 'movie' }); + store.reportIssue({ code: IssueCode.MediaNetwork, mediaId: 'movie' }); + + const issues = store.getIssueSnapshot().issues; + expect(issues).toHaveLength(1); + expect(issues[0]?.occurrences).toBe(3); + expect(issues[0]?.message).toBe(ISSUE_CATALOG[IssueCode.MediaNetwork].message); + }); + + it('derives user-facing text from the catalog, never from the error', (): void => { + const store = createIssueStore(); + + store.reportIssue({ code: IssueCode.Unexpected, error: new Error('sekrit token at http://10.0.0.1:5000') }); + + const [issue] = store.getIssueSnapshot().issues; + expect(issue?.message).toBe(ISSUE_CATALOG[IssueCode.Unexpected].message); + expect(issue?.message).not.toContain('sekrit'); + }); + + it('removes resolved issues from active state and starts a fresh incident on recurrence', (): void => { + const store = createIssueStore(); + store.reportIssue({ code: IssueCode.ConnectionLost }); + + const [first] = store.getIssueSnapshot().issues; + if (first === undefined) { + throw new Error('expected a ConnectionLost issue'); + } + + store.resolveIssue(first.id); + expect(store.getIssueSnapshot().issues).toHaveLength(0); + + store.reportIssue({ code: IssueCode.ConnectionLost }); + const [recurred] = store.getIssueSnapshot().issues; + expect(recurred?.occurrences).toBe(1); + expect(recurred?.id).not.toBe(first.id); + + // Unknown ids are a no-op, not a throw. + store.resolveIssue('does-not-exist'); + expect(store.getIssueSnapshot().issues).toHaveLength(1); + }); + + it('folds related media network and decode failures into one per-media incident', (): void => { + const store = createIssueStore(); + + store.reportIssue({ code: IssueCode.MediaNetwork, mediaId: 'movie' }); + store.reportIssue({ code: IssueCode.MediaDecode, mediaId: 'movie' }); + store.reportIssue({ code: IssueCode.MediaDecode, mediaId: 'trailer' }); + + const issues = store.getIssueSnapshot().issues; + expect(issues).toHaveLength(2); + + const [movie] = issues.filter((issue) => issue.mediaId === 'movie'); + expect(movie?.occurrences).toBe(2); + }); + + it('caps active issues and evicts the least recently reported', (): void => { + let clock = 0; + const store = createIssueStore((): number => clock); + + for (let index = 0; index < 20; index += 1) { + clock += 1; + store.reportIssue({ code: IssueCode.InvalidServerState, mediaId: `media-${String(index)}` }); + } + + const mediaIds = store.getIssueSnapshot().issues.map((issue) => issue.mediaId); + expect(mediaIds).toHaveLength(ACTIVE_ISSUE_LIMIT); + expect(mediaIds).not.toContain('media-3'); + expect(mediaIds).toContain('media-4'); + expect(mediaIds).toContain('media-19'); + + // Re-reporting an old incident bumps its recency and protects it. + clock += 1; + store.reportIssue({ code: IssueCode.InvalidServerState, mediaId: 'media-4' }); + clock += 1; + store.reportIssue({ code: IssueCode.InvalidServerState, mediaId: 'media-20' }); + + const remaining = store.getIssueSnapshot().issues.map((issue) => issue.mediaId); + expect(remaining).toHaveLength(ACTIVE_ISSUE_LIMIT); + expect(remaining).toContain('media-4'); + expect(remaining).not.toContain('media-5'); + expect(remaining).toContain('media-20'); + }); + + it('isolates subscriber failures from other subscribers and the reporter', (): void => { + const warn = vi.spyOn(console, 'warn').mockImplementation((): void => undefined); + const store = createIssueStore(); + + const breaking = vi.fn((): void => { + throw new Error('listener bug'); + }); + expect(() => { + store.subscribeIssues(breaking); + }).not.toThrow(); + + const snapshots: IssueSnapshot[] = []; + store.subscribeIssues((snapshot: IssueSnapshot): void => { + snapshots.push(snapshot); + }); + + expect(() => { + store.reportIssue({ code: IssueCode.ConnectionLost }); + }).not.toThrow(); + expect(breaking).toHaveBeenCalled(); + expect(warn).toHaveBeenCalled(); + + // Replay plus the report notification both reached the healthy listener. + expect(snapshots).toHaveLength(2); + expect(snapshots[1]?.issues).toHaveLength(1); + }); + + it('normalizes garbage, missing, and hostile inputs without throwing', (): void => { + const circular: Record = { username: 'alice' }; + circular['self'] = circular; + + const symbolKeyed: Record = {}; + symbolKeyed[Symbol('k')] = 'value'; + symbolKeyed['name'] = 12345; + + const nullInput: unknown = null; + const numberInput: unknown = 42; + + const store = createIssueStore(); + + expect(() => { + store.reportIssue({}); + }).not.toThrow(); + expect(() => { + store.reportIssue(nullInput as IssueInput); + }).not.toThrow(); + expect(() => { + store.reportIssue(numberInput as IssueInput); + }).not.toThrow(); + expect(() => { + store.reportIssue({ code: 'definitely-not-a-code', error: circular }); + }).not.toThrow(); + expect(() => { + store.reportIssue({ code: IssueCode.Unexpected, error: 'primitive rejection' }); + }).not.toThrow(); + expect(() => { + store.reportIssue({ code: IssueCode.Unexpected, error: 7 }); + }).not.toThrow(); + expect(() => { + store.reportIssue({ code: IssueCode.Unexpected, error: null }); + }).not.toThrow(); + expect(() => { + store.reportIssue({ code: IssueCode.Unexpected, error: symbolKeyed }); + }).not.toThrow(); + + const issues = store.getIssueSnapshot().issues; + expect(issues).toHaveLength(1); + expect(issues[0]?.code).toBe(IssueCode.Unexpected); + expect(issues[0]?.occurrences).toBe(8); + expect(issues[0]?.key).toBe('unexpected:global'); + }); + + it('assigns unique stable ids per incident', (): void => { + const store = createIssueStore(); + + store.reportIssue({ code: IssueCode.StorageUnavailable }); + store.reportIssue({ code: IssueCode.InvalidServerState }); + + const ids = store.getIssueSnapshot().issues.map((issue) => issue.id); + expect(new Set(ids).size).toBe(2); + }); + + it('captures numeric media error codes from detail payloads', (): void => { + const store = createIssueStore(); + + store.reportIssue({ code: IssueCode.MediaDecode, mediaId: 'movie', detail: { code: 3 } }); + + const [issue] = store.getIssueSnapshot().issues; + expect(issue?.mediaErrorCode).toBe(3); + }); +}); + +describe('normalizeErrorName', (): void => { + it('reads constructor names and survives primitives and garbage', (): void => { + expect(normalizeErrorName(new TypeError('boom'))).toBe('TypeError'); + expect(normalizeErrorName('just a string')).toBeUndefined(); + expect(normalizeErrorName(null)).toBeUndefined(); + expect(normalizeErrorName(undefined)).toBeUndefined(); + expect(normalizeErrorName({ name: 12345 })).toBe('Object'); + }); +}); From 1717e76baec237ddb5fdbca71f1a1134b6f546bb Mon Sep 17 00:00:00 2001 From: Aaron Guo <89121695+PolarWolf314@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:57:31 +1300 Subject: [PATCH 07/58] feat(diagnostics): bound diagnostic ring and allowlist diagnostics export recordDiagnostic sanitizes every event to the allowlisted shape (error names, numeric media codes, EXTENSION_ORIGIN marker, numeric readings) and bounds history to 50 entries, evicting oldest first. exportDiagnostics renders a human-readable, local-only report built exclusively from allowlisted fields: usernames, URLs/IPs, query tokens, raw messages, and stack traces never appear. Adds conservative user-agent engine detection and an allowlisted socket-argument summarizer (kinds, never values). --- client/src/diagnostics/issues.ts | 78 +++++++++++++- client/src/diagnostics/snapshot.ts | 143 +++++++++++++++++++++++++ client/tests/unit/diagnostics.test.ts | 144 ++++++++++++++++++++++++++ 3 files changed, 363 insertions(+), 2 deletions(-) create mode 100644 client/tests/unit/diagnostics.test.ts diff --git a/client/src/diagnostics/issues.ts b/client/src/diagnostics/issues.ts index 765acf4..69b2d7c 100644 --- a/client/src/diagnostics/issues.ts +++ b/client/src/diagnostics/issues.ts @@ -1,6 +1,11 @@ import { ACTIVE_ISSUE_LIMIT, + currentEngineFamily, DiagnosticEvent, + formatDiagnosticsReport, + DIAGNOSTICS_HEADER, + DIAGNOSTIC_HISTORY_LIMIT, + isSafeToken, Issue, IssueCode, IssueDefinition, @@ -104,6 +109,8 @@ const MEDIA_PLAYBACK_INCIDENT = 'media-playback'; const MAX_MEDIA_ID_LENGTH = 64; const MAX_NAME_LENGTH = 64; +const MAX_EVENT_TYPE_LENGTH = 64; +const MAX_READINGS_PER_EVENT = 8; /** Module-local incident counter; ids must not depend on a secure context. */ let incidentCounter = 0; @@ -206,6 +213,54 @@ export function normalizeErrorName(error: unknown): string | undefined { } } +/** + * Reduces any diagnostic event input to the allowlisted `DiagnosticEvent` + * shape. Unknown fields, non-numeric readings, and raw payloads are dropped; + * the result never references DOM events, error objects, or media elements. + */ +function sanitizeDiagnosticEvent(event: unknown, fallbackAt: number): DiagnosticEvent { + const record = toRecord(event); + const rawType = record['type']; + const rawAt = record['at']; + + const sanitized: DiagnosticEvent = { + type: + typeof rawType === 'string' && rawType.length > 0 && rawType.length <= MAX_EVENT_TYPE_LENGTH + ? rawType + : 'unknown', + at: typeof rawAt === 'number' && Number.isFinite(rawAt) ? rawAt : fallbackAt, + ...pickErrorName(record['errorName']), + ...pickMediaErrorCode(record['mediaErrorCode']), + ...(record['extensionOrigin'] === true ? { extensionOrigin: true } : {}), + ...pickReadings(record['readings']), + }; + return sanitized; +} + +function pickErrorName(value: unknown): { errorName?: string } { + return typeof value === 'string' && value.length > 0 && value.length <= MAX_NAME_LENGTH ? { errorName: value } : {}; +} + +function pickMediaErrorCode(value: unknown): { mediaErrorCode?: number } { + return typeof value === 'number' && Number.isFinite(value) ? { mediaErrorCode: value } : {}; +} + +function pickReadings(value: unknown): { readings?: Readonly> } { + if (typeof value !== 'object' || value === null) { + return {}; + } + const readings: Record = {}; + for (const [key, reading] of Object.entries(value as Record)) { + if (Object.keys(readings).length >= MAX_READINGS_PER_EVENT) { + break; + } + if (isSafeToken(key) && typeof reading === 'number' && Number.isFinite(reading)) { + readings[key] = reading; + } + } + return Object.keys(readings).length > 0 ? { readings } : {}; +} + function toPublicIssue(incident: MutableIssue): Issue { const definition: IssueDefinition = ISSUE_CATALOG[incident.code]; const issue: Issue = { @@ -244,6 +299,8 @@ export function createIssueStore(now: () => number = Date.now): IssueStore { /** Allowlisted diagnostic events (bounded ring). */ const history: DiagnosticEvent[] = []; const listeners = new Set(); + let totalIncidents = 0; + let retiredIncidents = 0; function snapshot(): IssueSnapshot { return { issues: Object.freeze([...active.values()].map(toPublicIssue)) }; @@ -274,6 +331,7 @@ export function createIssueStore(now: () => number = Date.now): IssueStore { break; } active.delete(oldestKey); + retiredIncidents += 1; } } @@ -300,6 +358,7 @@ export function createIssueStore(now: () => number = Date.now): IssueStore { fresh.mediaErrorCode = normalized.mediaErrorCode; } active.set(key, fresh); + totalIncidents += 1; evictIfNeeded(); } else { incident.code = normalized.code; @@ -321,6 +380,7 @@ export function createIssueStore(now: () => number = Date.now): IssueStore { for (const [key, incident] of active) { if (incident.id === id) { active.delete(key); + retiredIncidents += 1; notify(); return; } @@ -348,14 +408,28 @@ export function createIssueStore(now: () => number = Date.now): IssueStore { function recordDiagnostic(event: DiagnosticEvent): void { try { - history.push(event); + history.push(sanitizeDiagnosticEvent(event, now())); + while (history.length > DIAGNOSTIC_HISTORY_LIMIT) { + history.shift(); + } } catch (failure) { console.warn('[panopticon] failed to record diagnostic', failure); } } function exportDiagnostics(): string { - return ''; + try { + return formatDiagnosticsReport({ + generatedAt: now(), + engineFamily: currentEngineFamily(), + activeIssues: [...active.values()].map(toPublicIssue), + diagnostics: [...history], + totalIncidentCount: totalIncidents, + retiredIncidentCount: retiredIncidents, + }); + } catch { + return `${DIAGNOSTICS_HEADER}\nDiagnostics export failed.`; + } } return { diff --git a/client/src/diagnostics/snapshot.ts b/client/src/diagnostics/snapshot.ts index ab787f7..e96e70c 100644 --- a/client/src/diagnostics/snapshot.ts +++ b/client/src/diagnostics/snapshot.ts @@ -126,3 +126,146 @@ export interface DiagnosticEvent { /** Numeric measurements (clock skew, readiness, buffer, frames, flags). */ readonly readings?: Readonly>; } + +/** + * Derives a coarse engine family from a user agent. Deliberately + * conservative: anything unparsable reports 'unknown'. + */ +export function detectEngineFamily(userAgent: string | undefined): string { + if (typeof userAgent !== 'string') { + return 'unknown'; + } + if (userAgent.includes('Firefox/')) { + return 'gecko'; + } + if (userAgent.includes('Edg/') || userAgent.includes('Chrome/')) { + return 'blink'; + } + if (userAgent.includes('Safari/')) { + return 'webkit'; + } + return 'unknown'; +} + +/** Reads the current engine family without assuming a DOM global exists. */ +export function currentEngineFamily(): string { + const host = globalThis as { readonly navigator?: { readonly userAgent?: unknown } }; + const userAgent = host.navigator?.userAgent; + return detectEngineFamily(typeof userAgent === 'string' ? userAgent : undefined); +} + +/** Describes a value by kind only; the value itself never appears in output. */ +export function describeValueKind(value: unknown): string { + if (value === null) { + return 'null'; + } + if (typeof value === 'object') { + return Array.isArray(value) ? 'array' : 'object'; + } + return typeof value; +} + +/** + * Summarizes socket event arguments as an allowlisted description: + * argument count plus per-argument kind strings. Values never appear. + */ +export function summarizeEventArgs(args: readonly unknown[]): string { + if (args.length === 0) { + return 'args=0'; + } + const kinds = args.map((arg: unknown): string => describeValueKind(arg)); + return `args=${String(args.length)} [${kinds.join(', ')}]`; +} + +/** Header line for exported diagnostics. */ +export const DIAGNOSTICS_HEADER = 'Project Panopticon diagnostics'; + +const LOCAL_ONLY_NOTE = 'Local-only debug information. Nothing here is collected or uploaded.'; +const MAX_READINGS_PER_EVENT = 8; +const SAFE_TOKEN_PATTERN = /^[A-Za-z0-9_-]{1,32}$/; + +function toIso(timestamp: number): string { + return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : 'unknown-time'; +} + +function isSafeToken(value: string): boolean { + return SAFE_TOKEN_PATTERN.test(value); +} + +export { isSafeToken }; + +/** Everything `formatDiagnosticsReport` needs; already allowlisted. */ +export interface DiagnosticsReportInput { + readonly generatedAt: number; + readonly engineFamily: string; + readonly activeIssues: readonly Issue[]; + readonly diagnostics: readonly DiagnosticEvent[]; + readonly totalIncidentCount: number; + readonly retiredIncidentCount: number; +} + +/** + * Renders a human-readable diagnostics report from allowlisted fields only. + * Issue codes, error names, numeric codes/readings, markers, timestamps, and + * coarse engine info may appear; usernames, URLs/IPs, tokens, messages, and + * stacks may not. + */ +export function formatDiagnosticsReport(input: DiagnosticsReportInput): string { + const lines: string[] = [ + DIAGNOSTICS_HEADER, + LOCAL_ONLY_NOTE, + `Generated: ${toIso(input.generatedAt)}`, + `Engine: ${input.engineFamily}`, + '', + `Active issues (${String(input.activeIssues.length)}, ${String(input.retiredIncidentCount)} retired, ${String(input.totalIncidentCount)} total incidents):`, + ]; + + if (input.activeIssues.length === 0) { + lines.push(' (none)'); + } + for (const issue of input.activeIssues) { + const parts = [ + `${issue.id} code=${issue.code}`, + `severity=${issue.severity}`, + `blocking=${issue.blocking ? 'yes' : 'no'}`, + `occurrences=${String(issue.occurrences)}`, + `first=${toIso(issue.firstSeen)}`, + `last=${toIso(issue.lastSeen)}`, + ]; + if (issue.mediaId !== undefined && isSafeToken(issue.mediaId)) { + parts.push(`media=${issue.mediaId}`); + } + if (issue.mediaErrorCode !== undefined) { + parts.push(`mediaErrorCode=${String(issue.mediaErrorCode)}`); + } + lines.push(` - ${parts.join(' ')}`); + } + + lines.push(''); + lines.push(`Diagnostic history (${String(input.diagnostics.length)}/${String(DIAGNOSTIC_HISTORY_LIMIT)} entries):`); + if (input.diagnostics.length === 0) { + lines.push(' (none)'); + } + for (const event of input.diagnostics) { + const parts = [toIso(event.at), event.type]; + if (event.extensionOrigin === true) { + parts.push('origin=EXTENSION_ORIGIN'); + } + if (event.errorName !== undefined) { + parts.push(`name=${event.errorName}`); + } + if (event.mediaErrorCode !== undefined) { + parts.push(`mediaErrorCode=${String(event.mediaErrorCode)}`); + } + if (event.readings !== undefined) { + for (const [key, value] of Object.entries(event.readings).slice(0, MAX_READINGS_PER_EVENT)) { + if (isSafeToken(key)) { + parts.push(`${key}=${String(value)}`); + } + } + } + lines.push(` - ${parts.join(' ')}`); + } + + return lines.join('\n'); +} diff --git a/client/tests/unit/diagnostics.test.ts b/client/tests/unit/diagnostics.test.ts new file mode 100644 index 0000000..5a22622 --- /dev/null +++ b/client/tests/unit/diagnostics.test.ts @@ -0,0 +1,144 @@ +import { describe, expect, it } from 'vitest'; +import { createIssueStore } from '../../src/diagnostics/issues'; +import { + detectEngineFamily, + DIAGNOSTIC_HISTORY_LIMIT, + DiagnosticEvent, + IssueCode, + summarizeEventArgs, +} from '../../src/diagnostics/snapshot'; + +describe('diagnostic ring', (): void => { + it('bounds the diagnostic ring to the documented limit, evicting oldest first', (): void => { + let clock = 0; + const store = createIssueStore((): number => clock); + + for (let index = 0; index < 60; index += 1) { + clock += 1; + store.recordDiagnostic({ type: 'probe', at: clock }); + } + + const report = store.exportDiagnostics(); + + expect(report).not.toContain(new Date(1).toISOString()); + expect(report).not.toContain(new Date(10).toISOString()); + expect(report).toContain(new Date(11).toISOString()); + expect(report).toContain(new Date(60).toISOString()); + expect(report.match(/probe/g)).toHaveLength(DIAGNOSTIC_HISTORY_LIMIT); + expect(report).toContain(`Diagnostic history (${String(DIAGNOSTIC_HISTORY_LIMIT)}/${String(DIAGNOSTIC_HISTORY_LIMIT)} entries)`); + }); + + it('sanitizes diagnostic events to allowlisted fields only', (): void => { + const store = createIssueStore(); + + const hostile: unknown = { + type: 'window-error', + at: 12345, + errorName: 'TypeError', + mediaErrorCode: 2, + message: 'secret message with token=abc', + stack: 'at http://10.0.0.1/x.js', + url: 'http://10.0.0.1/x.js?token=abc', + username: 'alice', + rawEvent: { target: 'video element' }, + }; + const garbage: unknown = 'garbage'; + + expect(() => { + store.recordDiagnostic(hostile as DiagnosticEvent); + }).not.toThrow(); + expect(() => { + store.recordDiagnostic(garbage as DiagnosticEvent); + }).not.toThrow(); + + const report = store.exportDiagnostics(); + expect(report).toContain('window-error'); + expect(report).toContain('name=TypeError'); + expect(report).toContain('mediaErrorCode=2'); + for (const banned of ['secret message', 'token=abc', '10.0.0.1', 'alice', 'video element']) { + expect(report).not.toContain(banned); + } + }); +}); + +describe('exportDiagnostics', (): void => { + it('exports an allowlisted, human-readable report', (): void => { + const store = createIssueStore(); + + const secretUrl = 'http://192.168.1.50:5000/?token=sekrit&user=alice'; + const failure = new TypeError(`failed to load ${secretUrl}`); + failure.stack = `TypeError: failed to load ${secretUrl}\n at load (${secretUrl}:1:1)`; + + store.reportIssue({ + code: IssueCode.MediaNetwork, + mediaId: 'movie', + error: failure, + detail: { code: 2, message: 'nope', url: secretUrl, username: 'alice' }, + }); + store.recordDiagnostic({ type: 'window-error', at: 4242424, errorName: 'TypeError' }); + + const report = store.exportDiagnostics(); + + // Header, allowlisted identifiers, and coarse environment info. + expect(report).toContain('Project Panopticon diagnostics'); + expect(report).toContain('Local-only'); + expect(report).toContain('media-network'); + expect(report).toContain('name=TypeError'); + expect(report).toContain('mediaErrorCode=2'); + expect(report).toMatch(/^Engine: (gecko|blink|webkit|unknown)$/m); + + // Usernames, URLs/IPs, query tokens, messages, and stacks never appear. + for (const banned of ['alice', 'sekrit', '192.168.1.50', 'token=', 'failed to load']) { + expect(report).not.toContain(banned); + } + }); + + it('omits unsafe media ids from the exported report', (): void => { + const store = createIssueStore(); + + store.reportIssue({ code: IssueCode.MediaMismatch, mediaId: 'http://10.0.0.7/logged-token' }); + + const report = store.exportDiagnostics(); + expect(report).toContain('media-mismatch'); + expect(report).not.toContain('10.0.0.7'); + expect(report).not.toContain('logged-token'); + }); +}); + +describe('detectEngineFamily', (): void => { + it('maps user agents to coarse engine families', (): void => { + expect(detectEngineFamily('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:133.0) Gecko/20100101 Firefox/133.0')).toBe('gecko'); + expect( + detectEngineFamily( + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', + ), + ).toBe('blink'); + expect( + detectEngineFamily( + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0', + ), + ).toBe('blink'); + expect( + detectEngineFamily( + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15', + ), + ).toBe('webkit'); + expect(detectEngineFamily('curl/8.4.0')).toBe('unknown'); + expect(detectEngineFamily('')).toBe('unknown'); + expect(detectEngineFamily(undefined)).toBe('unknown'); + }); +}); + +describe('summarizeEventArgs', (): void => { + it('describes argument kinds without leaking values', (): void => { + const summary = summarizeEventArgs([{ username: 'alice' }, 42, 'sekrit token', null, [1, 2], undefined]); + + expect(summary).toBe('args=6 [object, number, string, null, array, undefined]'); + expect(summary).not.toContain('alice'); + expect(summary).not.toContain('sekrit'); + }); + + it('summarizes empty argument lists', (): void => { + expect(summarizeEventArgs([])).toBe('args=0'); + }); +}); From c57b2bf50b5ed6c59a0a381127bb9f986b6d1dad Mon Sep 17 00:00:00 2001 From: Aaron Guo <89121695+PolarWolf314@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:03:49 +1300 Subject: [PATCH 08/58] feat(diagnostics): add runtime error handlers and bootstrap failure boundary index.html now loads /src/bootstrap.ts, which installs last-resort window error/unhandledrejection handlers before dynamically importing main and calling its explicit initApp. The load-event wait moved into bootstrap so a slow dynamic import can no longer miss it. Import or initialization failures normalize into an app-init issue, render the plain-text #startup-fallback container, and keep console.error reporting instead of swallowing. Runtime handlers preserve native console behavior, filter obvious extension-origin scripts (chrome-/safari-web-/moz-extension and foreign http origins) into EXTENSION_ORIGIN diagnostics rather than first-party failures, and replace socket.onAny raw-argument logging with an allowlisted console.debug summary (event name + argument kinds only). --- client/index.html | 4 +- client/src/bootstrap.ts | 111 ++++++++++ client/src/diagnostics/runtime.ts | 117 ++++++++++ client/src/main.ts | 14 +- client/tests/unit/runtimeErrors.test.ts | 280 ++++++++++++++++++++++++ 5 files changed, 521 insertions(+), 5 deletions(-) create mode 100644 client/src/bootstrap.ts create mode 100644 client/src/diagnostics/runtime.ts create mode 100644 client/tests/unit/runtimeErrors.test.ts diff --git a/client/index.html b/client/index.html index e9ab953..a1cb8c3 100644 --- a/client/index.html +++ b/client/index.html @@ -15,7 +15,9 @@ - + + +