~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test: comprehensive Vitest JS unit tests (348 tests) + CI integration (#3385)
LearningCircuit585079740972
diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.ymlindex 02f544a58d..d065f5310d 100644--- a/.github/workflows/docker-tests.yml+++ b/.github/workflows/docker-tests.yml@@ -63,6 +63,7 @@ jobs:- 'src/local_deep_research/web/routes/**'- 'src/local_deep_research/web/static/js/**'- 'tests/infrastructure_tests/**'+ - 'tests/js/**'- '.github/workflows/docker-tests.yml'docker:- 'Dockerfile'@@ -201,6 +202,11 @@ jobs:run: |cd tests/infrastructure_tests && npm test+ - name: Run Vitest JS unit tests+ if: always()+ run: |+ npm ci && npm test+- name: Generate coverage summaryif: always()run: |@@ -1091,3 +1097,7 @@ jobs:- name: Run JavaScript infrastructure testsrun: |cd tests/infrastructure_tests && npm test++ - name: Run Vitest JS unit tests+ run: |+ npm ci && npm testdiff --git a/.gitignore b/.gitignoreindex 4feb2fb0f3..4d8c54c692 100644--- a/.gitignore+++ b/.gitignore@@ -194,6 +194,7 @@ js-db/*.sarifcodeql_analysis_results.txt.coverage+coverage/# benchmark results for examplesexamples/benchmark_results/diff --git a/.pre-commit-hooks/_commit_analysis.py b/.pre-commit-hooks/_commit_analysis.pyindex 79983b0473..804fd4a1d8 100644--- a/.pre-commit-hooks/_commit_analysis.py+++ b/.pre-commit-hooks/_commit_analysis.py@@ -96,6 +96,19 @@ def classify_file(path):if p.suffix == ".md":return "doc"+ # JavaScript files+ if p.suffix == ".js":+ # Vitest test files: tests/js/**/*.test.js+ if "tests" in parts_set and basename.endswith(".test.js"):+ return "test"+ # Source: under src/.../static/js/+ if "static" in parts_set and "js" in parts_set and parts_set & {"src"}:+ # Skip vendored / third-party+ if "vendor" in parts_set or "lib" in parts_set:+ return "other"+ return "source"+ return "other"+# Non-Python files are "other"if p.suffix != ".py":return "other"@@ -144,9 +157,27 @@ def _dir_to_category(dirname):def suggest_test_path(source_path):"""Suggest a test file path for a given source file.- Example: src/local_deep_research/web/api.py -> tests/web/test_api.py+ Python: src/local_deep_research/web/api.py -> tests/web/test_api.py+ JS: src/local_deep_research/web/static/js/components/foo.js+ -> tests/js/components/foo.test.js"""p = PurePosixPath(source_path)++ # JavaScript: mirror tests/js/<subpath under static/js/>+ if p.suffix == ".js":+ parts = list(p.parts)+ if "static" in parts and "js" in parts:+ js_idx = parts.index("js", parts.index("static"))+ sub_parts = parts[js_idx + 1 :]+ if sub_parts:+ stem = PurePosixPath(sub_parts[-1]).stem+ # Convert snake_case → kebab-case to match existing test naming+ stem = stem.replace("_", "-")+ test_name = f"{stem}.test.js"+ test_parts = ["tests", "js"] + sub_parts[:-1] + [test_name]+ return str(PurePosixPath(*test_parts))+ return f"tests/js/{p.stem.replace('_', '-')}.test.js"+parts = list(p.parts)# Strip leading src/ and package name (e.g., src/local_deep_research/)diff --git a/package-lock.json b/package-lock.jsonindex 4d29e56d36..a5dedddfc6 100644--- a/package-lock.json+++ b/package-lock.json@@ -23,14 +23,53 @@"socket.io-client": "^4.8.3"},"devDependencies": {+ "@vitest/coverage-v8": "^4.1.2","eslint": "^9.39.1","eslint-plugin-no-unsanitized": "^4.1.5",- "vite": "^7.3.2"+ "happy-dom": "^20.8.9",+ "vite": "^7.3.2",+ "vitest": "^4.1.2"},"engines": {"node": ">=24.0.0"}},+ "node_modules/@babel/helper-string-parser": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",+ "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-validator-identifier": {+ "version": "7.28.5",+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",+ "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/parser": {+ "version": "7.29.2",+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz",+ "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/types": "^7.29.0"+ },+ "bin": {+ "parser": "bin/babel-parser.js"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },"node_modules/@babel/runtime": {"version": "7.29.2","resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",@@ -40,6 +79,30 @@"node": ">=6.9.0"}},+ "node_modules/@babel/types": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",+ "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/helper-string-parser": "^7.27.1",+ "@babel/helper-validator-identifier": "^7.28.5"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@bcoe/v8-coverage": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz",+ "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },"node_modules/@esbuild/aix-ppc64": {"version": "0.27.4","resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz",@@ -687,6 +750,34 @@"url": "https://github.com/sponsors/nzakas"}},+ "node_modules/@jridgewell/resolve-uri": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@jridgewell/trace-mapping": {+ "version": "0.3.31",+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/resolve-uri": "^3.1.0",+ "@jridgewell/sourcemap-codec": "^1.4.14"+ }+ },"node_modules/@kurkle/color": {"version": "0.3.4","resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz",@@ -1060,6 +1151,31 @@"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==","license": "MIT"},+ "node_modules/@standard-schema/spec": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/chai": {+ "version": "5.2.3",+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/deep-eql": "*",+ "assertion-error": "^2.0.1"+ }+ },+ "node_modules/@types/deep-eql": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/estree": {"version": "1.0.8","resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",@@ -1074,6 +1190,16 @@"dev": true,"license": "MIT"},+ "node_modules/@types/node": {+ "version": "25.6.0",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-25.6.0.tgz",+ "integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~7.19.0"+ }+ },"node_modules/@types/pako": {"version": "2.0.4","resolved": "https://registry.npmjs.org/@types/pako/-/pako-2.0.4.tgz",@@ -1094,6 +1220,167 @@"license": "MIT","optional": true},+ "node_modules/@types/whatwg-mimetype": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz",+ "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/ws": {+ "version": "8.18.1",+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@vitest/coverage-v8": {+ "version": "4.1.4",+ "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.4.tgz",+ "integrity": "sha512-x7FptB5oDruxNPDNY2+S8tCh0pcq7ymCe1gTHcsp733jYjrJl8V1gMUlVysuCD9Kz46Xz9t1akkv08dPcYDs1w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@bcoe/v8-coverage": "^1.0.2",+ "@vitest/utils": "4.1.4",+ "ast-v8-to-istanbul": "^1.0.0",+ "istanbul-lib-coverage": "^3.2.2",+ "istanbul-lib-report": "^3.0.1",+ "istanbul-reports": "^3.2.0",+ "magicast": "^0.5.2",+ "obug": "^2.1.1",+ "std-env": "^4.0.0-rc.1",+ "tinyrainbow": "^3.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "@vitest/browser": "4.1.4",+ "vitest": "4.1.4"+ },+ "peerDependenciesMeta": {+ "@vitest/browser": {+ "optional": true+ }+ }+ },+ "node_modules/@vitest/expect": {+ "version": "4.1.4",+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.4.tgz",+ "integrity": "sha512-iPBpra+VDuXmBFI3FMKHSFXp3Gx5HfmSCE8X67Dn+bwephCnQCaB7qWK2ldHa+8ncN8hJU8VTMcxjPpyMkUjww==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@standard-schema/spec": "^1.1.0",+ "@types/chai": "^5.2.2",+ "@vitest/spy": "4.1.4",+ "@vitest/utils": "4.1.4",+ "chai": "^6.2.2",+ "tinyrainbow": "^3.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/mocker": {+ "version": "4.1.4",+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.4.tgz",+ "integrity": "sha512-R9HTZBhW6yCSGbGQnDnH3QHfJxokKN4KB+Yvk9Q1le7eQNYwiCyKxmLmurSpFy6BzJanSLuEUDrD+j97Q+ZLPg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/spy": "4.1.4",+ "estree-walker": "^3.0.3",+ "magic-string": "^0.30.21"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "msw": "^2.4.9",+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"+ },+ "peerDependenciesMeta": {+ "msw": {+ "optional": true+ },+ "vite": {+ "optional": true+ }+ }+ },+ "node_modules/@vitest/pretty-format": {+ "version": "4.1.4",+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.4.tgz",+ "integrity": "sha512-ddmDHU0gjEUyEVLxtZa7xamrpIefdEETu3nZjWtHeZX4QxqJ7tRxSteHVXJOcr8jhiLoGAhkK4WJ3WqBpjx42A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyrainbow": "^3.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/runner": {+ "version": "4.1.4",+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.4.tgz",+ "integrity": "sha512-xTp7VZ5aXP5ZJrn15UtJUWlx6qXLnGtF6jNxHepdPHpMfz/aVPx+htHtgcAL2mDXJgKhpoo2e9/hVJsIeFbytQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/utils": "4.1.4",+ "pathe": "^2.0.3"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/snapshot": {+ "version": "4.1.4",+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.4.tgz",+ "integrity": "sha512-MCjCFgaS8aZz+m5nTcEcgk/xhWv0rEH4Yl53PPlMXOZ1/Ka2VcZU6CJ+MgYCZbcJvzGhQRjVrGQNZqkGPttIKw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "4.1.4",+ "@vitest/utils": "4.1.4",+ "magic-string": "^0.30.21",+ "pathe": "^2.0.3"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/spy": {+ "version": "4.1.4",+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.4.tgz",+ "integrity": "sha512-XxNdAsKW7C+FLydqFJLb5KhJtl3PGCMmYwFRfhvIgxJvLSXhhVI1zM8f1qD3Zg7RCjTSzDVyct6sghs9UEgBEQ==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/utils": {+ "version": "4.1.4",+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.4.tgz",+ "integrity": "sha512-13QMT+eysM5uVGa1rG4kegGYNp6cnQcsTc67ELFbhNLQO+vgsygtYJx2khvdt4gVQqSSpC/KT5FZZxUpP3Oatw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "4.1.4",+ "convert-source-map": "^2.0.0",+ "tinyrainbow": "^3.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },"node_modules/acorn": {"version": "8.16.0","resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",@@ -1157,6 +1444,28 @@"dev": true,"license": "Python-2.0"},+ "node_modules/assertion-error": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/ast-v8-to-istanbul": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.0.tgz",+ "integrity": "sha512-1fSfIwuDICFA4LKkCzRPO7F0hzFf0B7+Xqrl27ynQaa+Rh0e1Es0v6kWHPott3lU10AyAr7oKHa65OppjLn3Rg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/trace-mapping": "^0.3.31",+ "estree-walker": "^3.0.3",+ "js-tokens": "^10.0.0"+ }+ },"node_modules/balanced-match": {"version": "1.0.2","resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",@@ -1249,6 +1558,16 @@"node": ">=10.0.0"}},+ "node_modules/chai": {+ "version": "6.2.2",+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },"node_modules/chalk": {"version": "4.1.2","resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",@@ -1324,6 +1643,13 @@"dev": true,"license": "MIT"},+ "node_modules/convert-source-map": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/core-js": {"version": "3.49.0","resolved": "https://registry.npmjs.org/core-js/-/core-js-3.49.0.tgz",@@ -1425,6 +1751,26 @@"node": ">=10.0.0"}},+ "node_modules/entities": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",+ "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.12"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },+ "node_modules/es-module-lexer": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.0.0.tgz",+ "integrity": "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/esbuild": {"version": "0.27.4","resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.4.tgz",@@ -1634,6 +1980,16 @@"node": ">=4.0"}},+ "node_modules/estree-walker": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0"+ }+ },"node_modules/esutils": {"version": "2.0.3","resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",@@ -1644,6 +2000,16 @@"node": ">=0.10.0"}},+ "node_modules/expect-type": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",+ "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=12.0.0"+ }+ },"node_modules/fast-deep-equal": {"version": "3.1.3","resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",@@ -1792,6 +2158,24 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/happy-dom": {+ "version": "20.8.9",+ "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.8.9.tgz",+ "integrity": "sha512-Tz23LR9T9jOGVZm2x1EPdXqwA37G/owYMxRwU0E4miurAtFsPMQ1d2Jc2okUaSjZqAFz2oEn3FLXC5a0a+siyA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": ">=20.0.0",+ "@types/whatwg-mimetype": "^3.0.2",+ "@types/ws": "^8.18.1",+ "entities": "^7.0.1",+ "whatwg-mimetype": "^3.0.0",+ "ws": "^8.18.3"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },"node_modules/has-flag": {"version": "4.0.0","resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",@@ -1811,6 +2195,13 @@"node": ">=12.0.0"}},+ "node_modules/html-escaper": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",+ "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/html2canvas": {"version": "1.4.1","resolved": "https://registry.npmjs.org/html2canvas/-/html2canvas-1.4.1.tgz",@@ -1897,6 +2288,52 @@"dev": true,"license": "ISC"},+ "node_modules/istanbul-lib-coverage": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",+ "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/istanbul-lib-report": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",+ "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "istanbul-lib-coverage": "^3.0.0",+ "make-dir": "^4.0.0",+ "supports-color": "^7.1.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/istanbul-reports": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz",+ "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "html-escaper": "^2.0.0",+ "istanbul-lib-report": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/js-tokens": {+ "version": "10.0.0",+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz",+ "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==",+ "dev": true,+ "license": "MIT"+ },"node_modules/js-yaml": {"version": "4.1.1","resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",@@ -1995,6 +2432,44 @@"dev": true,"license": "MIT"},+ "node_modules/magic-string": {+ "version": "0.30.21",+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.5"+ }+ },+ "node_modules/magicast": {+ "version": "0.5.2",+ "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.2.tgz",+ "integrity": "sha512-E3ZJh4J3S9KfwdjZhe2afj6R9lGIN5Pher1pF39UGrXRqq/VDaGVIGN13BjHd2u8B61hArAGOnso7nBOouW3TQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/parser": "^7.29.0",+ "@babel/types": "^7.29.0",+ "source-map-js": "^1.2.1"+ }+ },+ "node_modules/make-dir": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",+ "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "semver": "^7.5.3"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/marked": {"version": "17.0.5","resolved": "https://registry.npmjs.org/marked/-/marked-17.0.5.tgz",@@ -2052,6 +2527,17 @@"dev": true,"license": "MIT"},+ "node_modules/obug": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz",+ "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==",+ "dev": true,+ "funding": [+ "https://github.com/sponsors/sxzz",+ "https://opencollective.com/debug"+ ],+ "license": "MIT"+ },"node_modules/optionator": {"version": "0.9.4","resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",@@ -2141,6 +2627,13 @@"node": ">=8"}},+ "node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "dev": true,+ "license": "MIT"+ },"node_modules/performance-now": {"version": "2.1.0","resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",@@ -2299,6 +2792,19 @@"fsevents": "~2.3.2"}},+ "node_modules/semver": {+ "version": "7.7.4",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },"node_modules/shebang-command": {"version": "2.0.0","resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",@@ -2322,6 +2828,13 @@"node": ">=8"}},+ "node_modules/siginfo": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",+ "dev": true,+ "license": "ISC"+ },"node_modules/socket.io-client": {"version": "4.8.3","resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.3.tgz",@@ -2360,6 +2873,13 @@"node": ">=0.10.0"}},+ "node_modules/stackback": {+ "version": "0.0.2",+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/stackblur-canvas": {"version": "2.7.0","resolved": "https://registry.npmjs.org/stackblur-canvas/-/stackblur-canvas-2.7.0.tgz",@@ -2370,6 +2890,13 @@"node": ">=0.1.14"}},+ "node_modules/std-env": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.0.0.tgz",+ "integrity": "sha512-zUMPtQ/HBY3/50VbpkupYHbRroTRZJPRLvreamgErJVys0ceuzMkD44J/QjqhHjOzK42GQ3QZIeFG1OYfOtKqQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/strip-json-comments": {"version": "3.1.1","resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",@@ -2415,6 +2942,23 @@"utrie": "^1.0.2"}},+ "node_modules/tinybench": {+ "version": "2.9.0",+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tinyexec": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.1.1.tgz",+ "integrity": "sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },"node_modules/tinyglobby": {"version": "0.2.15","resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",@@ -2432,6 +2976,16 @@"url": "https://github.com/sponsors/SuperchupuDev"}},+ "node_modules/tinyrainbow": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz",+ "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },"node_modules/type-check": {"version": "0.4.0","resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",@@ -2445,6 +2999,13 @@"node": ">= 0.8.0"}},+ "node_modules/undici-types": {+ "version": "7.19.2",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz",+ "integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/uri-js": {"version": "4.4.1","resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",@@ -2539,6 +3100,106 @@}}},+ "node_modules/vitest": {+ "version": "4.1.4",+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.4.tgz",+ "integrity": "sha512-tFuJqTxKb8AvfyqMfnavXdzfy3h3sWZRWwfluGbkeR7n0HUev+FmNgZ8SDrRBTVrVCjgH5cA21qGbCffMNtWvg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/expect": "4.1.4",+ "@vitest/mocker": "4.1.4",+ "@vitest/pretty-format": "4.1.4",+ "@vitest/runner": "4.1.4",+ "@vitest/snapshot": "4.1.4",+ "@vitest/spy": "4.1.4",+ "@vitest/utils": "4.1.4",+ "es-module-lexer": "^2.0.0",+ "expect-type": "^1.3.0",+ "magic-string": "^0.30.21",+ "obug": "^2.1.1",+ "pathe": "^2.0.3",+ "picomatch": "^4.0.3",+ "std-env": "^4.0.0-rc.1",+ "tinybench": "^2.9.0",+ "tinyexec": "^1.0.2",+ "tinyglobby": "^0.2.15",+ "tinyrainbow": "^3.1.0",+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",+ "why-is-node-running": "^2.3.0"+ },+ "bin": {+ "vitest": "vitest.mjs"+ },+ "engines": {+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "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.4",+ "@vitest/browser-preview": "4.1.4",+ "@vitest/browser-webdriverio": "4.1.4",+ "@vitest/coverage-istanbul": "4.1.4",+ "@vitest/coverage-v8": "4.1.4",+ "@vitest/ui": "4.1.4",+ "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+ },+ "vite": {+ "optional": false+ }+ }+ },+ "node_modules/whatwg-mimetype": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",+ "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/which": {"version": "2.0.2","resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",@@ -2555,6 +3216,23 @@"node": ">= 8"}},+ "node_modules/why-is-node-running": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "siginfo": "^2.0.0",+ "stackback": "0.0.2"+ },+ "bin": {+ "why-is-node-running": "cli.js"+ },+ "engines": {+ "node": ">=8"+ }+ },"node_modules/word-wrap": {"version": "1.2.5","resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",diff --git a/package.json b/package.jsonindex 86c99c47a8..26b40d7e76 100644--- a/package.json+++ b/package.json@@ -15,7 +15,9 @@"audit": "npm audit","audit-fix": "npm audit fix","security-check": "npm audit && npm outdated",- "test": "echo \"Error: no test specified\" && exit 1"+ "test": "vitest run",+ "test:watch": "vitest",+ "test:coverage": "vitest run --coverage"},"dependencies": {"@fortawesome/fontawesome-free": "^7.2.0",@@ -33,8 +35,11 @@"socket.io-client": "^4.8.3"},"devDependencies": {+ "@vitest/coverage-v8": "^4.1.2","eslint": "^9.39.1","eslint-plugin-no-unsanitized": "^4.1.5",- "vite": "^7.3.2"+ "happy-dom": "^20.8.9",+ "vite": "^7.3.2",+ "vitest": "^4.1.2"}}diff --git a/tests/js/components/checkbox-handler.test.js b/tests/js/components/checkbox-handler.test.jsnew file mode 100644index 0000000000..5039e210e5--- /dev/null+++ b/tests/js/components/checkbox-handler.test.js@@ -0,0 +1,130 @@+/**+ * Tests for components/checkbox_handler.js+ *+ * Tests the checkbox-hidden input fallback pattern that ensures+ * both checked and unchecked states are submitted in HTML forms.+ */++let handler;++beforeAll(async () => {+ await import('@js/components/checkbox_handler.js');+ handler = window.checkboxHandler;+});++describe('CheckboxHandler', () => {+ let form;++ beforeEach(() => {+ form = document.createElement('form');+ document.body.appendChild(form);+ });++ afterEach(() => {+ form.remove();+ });++ describe('setupCheckbox', () => {+ it('disables hidden input when checkbox is checked', () => {+ const checkbox = document.createElement('input');+ checkbox.type = 'checkbox';+ checkbox.checked = true;+ checkbox.setAttribute('data-hidden-fallback', 'hidden-1');++ const hidden = document.createElement('input');+ hidden.type = 'hidden';+ hidden.id = 'hidden-1';+ hidden.value = 'false';++ form.appendChild(checkbox);+ form.appendChild(hidden);++ handler.setupCheckbox(checkbox);+ expect(hidden.disabled).toBe(true);+ });++ it('enables hidden input when checkbox is unchecked', () => {+ const checkbox = document.createElement('input');+ checkbox.type = 'checkbox';+ checkbox.checked = false;+ checkbox.setAttribute('data-hidden-fallback', 'hidden-2');++ const hidden = document.createElement('input');+ hidden.type = 'hidden';+ hidden.id = 'hidden-2';+ hidden.value = 'false';++ form.appendChild(checkbox);+ form.appendChild(hidden);++ handler.setupCheckbox(checkbox);+ expect(hidden.disabled).toBe(false);+ });++ it('toggles hidden input on change event', () => {+ const checkbox = document.createElement('input');+ checkbox.type = 'checkbox';+ checkbox.checked = false;+ checkbox.setAttribute('data-hidden-fallback', 'hidden-3');++ const hidden = document.createElement('input');+ hidden.type = 'hidden';+ hidden.id = 'hidden-3';++ form.appendChild(checkbox);+ form.appendChild(hidden);++ handler.setupCheckbox(checkbox);+ expect(hidden.disabled).toBe(false);++ checkbox.checked = true;+ checkbox.dispatchEvent(new Event('change'));+ expect(hidden.disabled).toBe(true);++ checkbox.checked = false;+ checkbox.dispatchEvent(new Event('change'));+ expect(hidden.disabled).toBe(false);+ });+ });++ describe('cleanup', () => {+ it('removes event listener from checkbox', () => {+ const checkbox = document.createElement('input');+ checkbox.type = 'checkbox';+ checkbox.setAttribute('data-hidden-fallback', 'hidden-4');++ const hidden = document.createElement('input');+ hidden.type = 'hidden';+ hidden.id = 'hidden-4';++ form.appendChild(checkbox);+ form.appendChild(hidden);++ handler.setupCheckbox(checkbox);+ expect(checkbox._checkboxHandlerCleanup).toBeTypeOf('function');++ handler.cleanup(checkbox);+ expect(checkbox._checkboxHandlerCleanup).toBeUndefined();+ });+ });++ describe('prepareFormSubmission', () => {+ it('syncs all checkbox-hidden pairs before submit', () => {+ const checkbox = document.createElement('input');+ checkbox.type = 'checkbox';+ checkbox.checked = true;+ checkbox.setAttribute('data-hidden-fallback', 'hidden-5');++ const hidden = document.createElement('input');+ hidden.type = 'hidden';+ hidden.id = 'hidden-5';+ hidden.disabled = false;++ form.appendChild(checkbox);+ form.appendChild(hidden);++ handler.prepareFormSubmission(form);+ expect(hidden.disabled).toBe(true);+ });+ });+});diff --git a/tests/js/components/custom-dropdown.test.js b/tests/js/components/custom-dropdown.test.jsnew file mode 100644index 0000000000..e19cca0ee0--- /dev/null+++ b/tests/js/components/custom-dropdown.test.js@@ -0,0 +1,233 @@+/**+ * Tests for components/custom_dropdown.js+ *+ * Tests the custom dropdown component's core behavior:+ * setup, filtering, selection, keyboard navigation, and cleanup.+ */++import '@js/security/xss-protection.js';+import '@js/components/custom_dropdown.js';++const setupCustomDropdown = window.setupCustomDropdown;+const updateDropdownOptions = window.updateDropdownOptions;++describe('setupCustomDropdown', () => {+ let input, hiddenInput, dropdownList, onSelect, options;++ beforeEach(() => {+ input = document.createElement('input');+ input.type = 'text';+ input.id = 'test-dropdown-input';++ hiddenInput = document.createElement('input');+ hiddenInput.type = 'hidden';+ hiddenInput.id = 'test-dropdown-input_hidden';++ dropdownList = document.createElement('div');+ dropdownList.id = 'test-dropdown-list';++ const wrapper = document.createElement('div');+ wrapper.appendChild(input);+ wrapper.appendChild(hiddenInput);+ wrapper.appendChild(dropdownList);+ document.body.appendChild(wrapper);++ onSelect = vi.fn();++ options = [+ { value: 'gpt4', label: 'GPT-4' },+ { value: 'claude', label: 'Claude' },+ { value: 'llama', label: 'Llama 3' },+ { value: 'mistral', label: 'Mistral' },+ ];+ });++ afterEach(() => {+ const wrapper = input.closest('div');+ if (wrapper && wrapper.parentNode) {+ wrapper.remove();+ }+ // Clean up any detached dropdown lists+ const detached = document.getElementById('test-dropdown-list');+ if (detached) detached.remove();+ });++ it('returns control functions', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ expect(dd.updateDropdown).toBeTypeOf('function');+ expect(dd.showDropdown).toBeTypeOf('function');+ expect(dd.hideDropdown).toBeTypeOf('function');+ expect(dd.destroy).toBeTypeOf('function');+ expect(dd.setValue).toBeTypeOf('function');+ dd.destroy();+ });++ it('initially hides the dropdown', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ expect(dropdownList.style.display).toBe('none');+ dd.destroy();+ });++ it('shows dropdown on input click', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ input.click();+ expect(dropdownList.style.display).toBe('block');+ dd.destroy();+ });++ it('populates dropdown with all options on click', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ input.click();+ const items = dropdownList.querySelectorAll('.ldr-custom-dropdown-item');+ expect(items.length).toBe(4);+ dd.destroy();+ });++ it('filters options when typing', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ input.value = 'Cl';+ input.dispatchEvent(new Event('input'));+ const items = dropdownList.querySelectorAll('.ldr-custom-dropdown-item');+ expect(items.length).toBe(1);+ expect(items[0].getAttribute('data-value')).toBe('claude');+ dd.destroy();+ });++ it('shows "no results" when nothing matches', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ input.value = 'zzzzz';+ input.dispatchEvent(new Event('input'));+ expect(dropdownList.querySelector('.ldr-custom-dropdown-no-results')).not.toBeNull();+ dd.destroy();+ });++ it('calls onSelect when an option is clicked', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ input.click();+ const items = dropdownList.querySelectorAll('.ldr-custom-dropdown-item');+ items[1].click(); // Click "Claude"+ expect(onSelect).toHaveBeenCalledWith('claude', options[1]);+ dd.destroy();+ });++ it('updates input value on selection', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ input.click();+ const items = dropdownList.querySelectorAll('.ldr-custom-dropdown-item');+ items[0].click(); // Click "GPT-4"+ expect(input.value).toBe('GPT-4');+ dd.destroy();+ });++ it('updates hidden input on selection', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ input.click();+ const items = dropdownList.querySelectorAll('.ldr-custom-dropdown-item');+ items[0].click();+ expect(hiddenInput.value).toBe('gpt4');+ dd.destroy();+ });++ it('hides dropdown after selection', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ input.click();+ const items = dropdownList.querySelectorAll('.ldr-custom-dropdown-item');+ items[0].click();+ expect(dropdownList.style.display).toBe('none');+ dd.destroy();+ });++ it('hides dropdown on Escape key', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ input.click();+ expect(dropdownList.style.display).toBe('block');+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));+ expect(dropdownList.style.display).toBe('none');+ dd.destroy();+ });++ it('sets ARIA attributes for accessibility', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ // Initially closed+ expect(input.getAttribute('aria-expanded')).toBe('false');+ // Open+ input.click();+ expect(input.getAttribute('aria-expanded')).toBe('true');++ // Items have role="option"+ const items = dropdownList.querySelectorAll('.ldr-custom-dropdown-item');+ items.forEach(item => {+ expect(item.getAttribute('role')).toBe('option');+ });+ dd.destroy();+ });++ describe('setValue', () => {+ it('sets value by matching option value', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ dd.setValue('mistral');+ expect(input.value).toBe('Mistral');+ expect(hiddenInput.value).toBe('mistral');+ dd.destroy();+ });++ it('calls onSelect callback', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ dd.setValue('claude');+ expect(onSelect).toHaveBeenCalledWith('claude', options[1]);+ dd.destroy();+ });++ it('clears input for unknown value when custom values disallowed', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect, false);+ dd.setValue('unknown-model');+ expect(input.value).toBe('');+ dd.destroy();+ });++ it('sets raw value when custom values are allowed', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect, true);+ dd.setValue('custom-model');+ expect(input.value).toBe('custom-model');+ dd.destroy();+ });+ });++ describe('destroy', () => {+ it('cleans up event listeners and registry', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ dd.destroy();+ // After destroy, input events should not trigger dropdown+ input.click();+ // Dropdown should stay hidden (no listener to open it)+ expect(dropdownList.style.display).toBe('none');+ });+ });++ describe('keyboard navigation', () => {+ it('ArrowDown opens dropdown and selects first item', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }));+ expect(dropdownList.style.display).toBe('block');+ const active = dropdownList.querySelector('.active');+ expect(active).not.toBeNull();+ dd.destroy();+ });++ it('Enter selects highlighted item', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ // Open and select first+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }));+ // Select it+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));+ expect(onSelect).toHaveBeenCalled();+ dd.destroy();+ });+ });+});++describe('updateDropdownOptions', () => {+ it('does nothing for null input', () => {+ expect(() => updateDropdownOptions(null, [])).not.toThrow();+ });+});diff --git a/tests/js/components/fallback-formatting.test.js b/tests/js/components/fallback-formatting.test.jsnew file mode 100644index 0000000000..143c256d50--- /dev/null+++ b/tests/js/components/fallback-formatting.test.js@@ -0,0 +1,133 @@+/**+ * Tests for components/fallback/formatting.js+ *+ * Tests the fallback formatting utilities that provide basic+ * implementations when the main formatting module is unavailable.+ */++// Ensure main formatting is NOT loaded (so fallback activates)+// We need ResearchStates for formatStatus+window.RESEARCH_STATUS = {+ IN_PROGRESS: 'in_progress',+ COMPLETED: 'completed',+ FAILED: 'failed',+ SUSPENDED: 'suspended',+ CANCELLED: 'cancelled',+ QUEUED: 'queued',+ PENDING: 'pending',+ ERROR: 'error',+};+window.RESEARCH_TERMINAL_STATES = new Set([+ 'completed', 'suspended', 'failed', 'error', 'cancelled',+]);++let fallbackFormatting;++beforeAll(async () => {+ // Load ResearchStates+ await import('@js/config/constants.js');++ // Delete any existing formatting to force fallback to activate+ delete window.formatting;++ // Load fallback+ await import('@js/components/fallback/formatting.js');+ fallbackFormatting = window.formatting;+});++describe('fallback formatting', () => {+ describe('formatDate', () => {+ it('returns N/A for falsy input', () => {+ expect(fallbackFormatting.formatDate(null)).toBe('N/A');+ expect(fallbackFormatting.formatDate('')).toBe('N/A');+ expect(fallbackFormatting.formatDate(undefined)).toBe('N/A');+ });++ it('formats a valid ISO date', () => {+ const result = fallbackFormatting.formatDate('2025-06-15T10:30:00Z');+ expect(result).toContain('2025');+ expect(result).toContain('15');+ });++ it('returns original string for invalid date', () => {+ const result = fallbackFormatting.formatDate('not-a-date');+ // The function returns the original string on error+ expect(result).toBeDefined();+ });+ });++ describe('formatMode', () => {+ it('maps known modes', () => {+ expect(fallbackFormatting.formatMode('quick')).toBe('Quick Summary');+ expect(fallbackFormatting.formatMode('detailed')).toBe('Detailed Report');+ expect(fallbackFormatting.formatMode('standard')).toBe('Standard Research');+ expect(fallbackFormatting.formatMode('advanced')).toBe('Advanced Research');+ });++ it('returns Unknown for falsy input', () => {+ expect(fallbackFormatting.formatMode(null)).toBe('Unknown');+ expect(fallbackFormatting.formatMode('')).toBe('Unknown');+ });++ it('returns raw value for unknown modes', () => {+ expect(fallbackFormatting.formatMode('custom')).toBe('custom');+ });+ });++ describe('formatDuration', () => {+ it('returns N/A for falsy input (except 0)', () => {+ expect(fallbackFormatting.formatDuration(null)).toBe('N/A');+ expect(fallbackFormatting.formatDuration(undefined)).toBe('N/A');+ });++ it('formats seconds only when < 60', () => {+ expect(fallbackFormatting.formatDuration(45)).toBe('45s');+ });++ it('formats minutes and seconds', () => {+ expect(fallbackFormatting.formatDuration(125)).toBe('2m 5s');+ });++ it('handles zero seconds', () => {+ expect(fallbackFormatting.formatDuration(0)).toBe('0s');+ });+ });++ describe('formatFileSize', () => {+ it('returns N/A for falsy input (except 0)', () => {+ expect(fallbackFormatting.formatFileSize(null)).toBe('N/A');+ expect(fallbackFormatting.formatFileSize(undefined)).toBe('N/A');+ });++ it('formats bytes', () => {+ expect(fallbackFormatting.formatFileSize(500)).toBe('500.0 B');+ });++ it('formats kilobytes', () => {+ expect(fallbackFormatting.formatFileSize(1024)).toBe('1.0 KB');+ });++ it('formats megabytes', () => {+ expect(fallbackFormatting.formatFileSize(1048576)).toBe('1.0 MB');+ });++ it('formats gigabytes', () => {+ expect(fallbackFormatting.formatFileSize(1073741824)).toBe('1.0 GB');+ });++ it('handles zero bytes', () => {+ expect(fallbackFormatting.formatFileSize(0)).toBe('0.0 B');+ });++ it('formats with decimal precision', () => {+ expect(fallbackFormatting.formatFileSize(1536)).toBe('1.5 KB');+ });+ });++ describe('formatStatus', () => {+ it('delegates to ResearchStates.formatStatus', () => {+ expect(fallbackFormatting.formatStatus('completed')).toBe('Completed');+ expect(fallbackFormatting.formatStatus('in_progress')).toBe('In Progress');+ });+ });+});diff --git a/tests/js/components/history-search.test.js b/tests/js/components/history-search.test.jsnew file mode 100644index 0000000000..eb9f13e2a0--- /dev/null+++ b/tests/js/components/history-search.test.js@@ -0,0 +1,226 @@+/**+ * Tests for components/history_search.js+ *+ * Covers the public API exposed via window.HistorySearch:+ * - triggerIndexing: convert-all then index-start sequence + error handling+ * - semanticSearchHistory: POST shape + error mapping+ * - renderSemanticResults: empty-state and SemanticSearch delegation+ *+ * Polling (startPolling) holds private module state (isIndexing,+ * pollErrorCount, indexingPollInterval) and uses real setInterval — testing+ * it directly here would leak state between tests, so we exercise the+ * setup-and-error paths and trust integration coverage for the loop body.+ */++// Stubs MUST be in place before the module is imported, because the IIFE+// auto-runs initSemanticSearch() at the bottom (DOM is "loaded" in tests).+window.URLS = {+ LIBRARY_API: {+ RESEARCH_HISTORY_COLLECTION: '/library/api/research-history/collection',+ RESEARCH_HISTORY_CONVERT_ALL: '/library/api/research-history/convert-all',+ COLLECTION_INDEX_START: '/library/api/collections/{id}/index/start',+ COLLECTION_INDEX_STATUS: '/library/api/collections/{id}/index/status',+ COLLECTION_SEARCH: '/library/api/collections/{id}/search',+ },+};+window.URLBuilder = {+ build: (template, id) => template.replace('{id}', id),+};+window.ResearchStates = {+ isTerminal: (s) => ['completed', 'failed', 'cancelled'].includes(s),+ isCompleted: (s) => s === 'completed',+ isFailed: (s) => s === 'failed',+ isCancelled: (s) => s === 'cancelled',+};+window.api = { getCsrfToken: () => 'test-token' };++// Initial init fetch — return a collection ID so triggerIndexing won't bail+const initialFetchMock = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({+ success: true,+ collection_id: 'coll-1',+ indexed_documents: 0,+ total_documents: 10,+ }),+});+globalThis.fetch = initialFetchMock;++let HS;+beforeAll(async () => {+ await import('@js/components/history_search.js');+ HS = window.HistorySearch;+ // Wait for the auto-init's fetches to settle+ await new Promise(r => setTimeout(r, 0));+});++beforeEach(() => {+ // Reset to a no-op fetch; each test installs what it needs+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({}),+ });+});++describe('HistorySearch namespace', () => {+ it('exposes the expected functions', () => {+ expect(typeof HS.toggleSemanticPanel).toBe('function');+ expect(typeof HS.triggerIndexing).toBe('function');+ expect(typeof HS.semanticSearchHistory).toBe('function');+ expect(typeof HS.renderSemanticResults).toBe('function');+ expect(typeof HS.getSemanticCollectionId).toBe('function');+ });++ it('caches collection ID from initial loadIndexingStatus', () => {+ // initialFetchMock returned collection_id 'coll-1'+ expect(HS.getSemanticCollectionId()).toBe('coll-1');+ });+});++describe('HistorySearch.semanticSearchHistory', () => {+ it('returns [] for empty query', async () => {+ const r = await HS.semanticSearchHistory('');+ expect(r).toEqual([]);+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it('POSTs to the collection search endpoint with query and CSRF token', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({+ success: true,+ results: [{ research_id: 'r1', similarity: 0.8 }],+ }),+ });++ const results = await HS.semanticSearchHistory('hello world');++ expect(globalThis.fetch).toHaveBeenCalledTimes(1);+ const [url, opts] = globalThis.fetch.mock.calls[0];+ expect(url).toContain('coll-1');+ expect(url).toContain('search');+ expect(opts.method).toBe('POST');+ expect(opts.headers['X-CSRFToken']).toBe('test-token');+ expect(JSON.parse(opts.body)).toEqual({ query: 'hello world', limit: 20 });+ expect(results).toHaveLength(1);+ });++ it('throws when the API returns success: false', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ success: false, error: 'Index missing' }),+ });++ await expect(HS.semanticSearchHistory('q')).rejects.toThrow('Index missing');+ });++ it('throws on non-OK responses', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: false,+ status: 500,+ json: () => Promise.resolve({}),+ });++ await expect(HS.semanticSearchHistory('q')).rejects.toThrow(/500/);+ });++ it('returns empty array when results field is missing', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ success: true }),+ });++ const r = await HS.semanticSearchHistory('q');+ expect(r).toEqual([]);+ });+});++describe('HistorySearch.renderSemanticResults', () => {+ afterEach(() => {+ document.body.innerHTML = '';+ });++ it('does nothing when the history-items container is missing', () => {+ // No container in DOM+ expect(() => HS.renderSemanticResults([{ research_id: 'a' }], 'q')).not.toThrow();+ });++ it('renders an empty-state message for null results', () => {+ const c = document.createElement('div');+ c.id = 'history-items';+ document.body.appendChild(c);++ HS.renderSemanticResults(null, 'q');+ expect(c.querySelector('.ldr-empty-state')).not.toBeNull();+ });++ it('renders an empty-state message for an empty array', () => {+ const c = document.createElement('div');+ c.id = 'history-items';+ document.body.appendChild(c);++ HS.renderSemanticResults([], 'q');+ expect(c.querySelector('.ldr-empty-state')).not.toBeNull();+ expect(c.textContent).toContain('No matching results');+ });++ it('delegates each result to SemanticSearch.createSemanticResultCard', () => {+ const c = document.createElement('div');+ c.id = 'history-items';+ document.body.appendChild(c);++ const fakeCard = () => {+ const el = document.createElement('div');+ el.className = 'fake-card';+ return el;+ };+ const savedSS = window.SemanticSearch;+ window.SemanticSearch = {+ createSemanticResultCard: vi.fn().mockImplementation(fakeCard),+ };++ try {+ HS.renderSemanticResults(+ [{ research_id: 'a' }, { research_id: 'b' }],+ 'q'+ );+ expect(window.SemanticSearch.createSemanticResultCard).toHaveBeenCalledTimes(2);+ expect(c.querySelectorAll('.fake-card')).toHaveLength(2);+ } finally {+ window.SemanticSearch = savedSS;+ }+ });+});++describe('HistorySearch.toggleSemanticPanel', () => {+ afterEach(() => {+ document.body.innerHTML = '';+ });++ it('toggles display style and chevron icon class', () => {+ const content = document.createElement('div');+ content.id = 'semantic-panel-content';+ content.style.display = 'block';+ const toggle = document.createElement('i');+ toggle.id = 'semantic-panel-toggle';+ toggle.className = 'fas fa-chevron-down';+ const header = document.createElement('div');+ header.id = 'semantic-panel-header';+ header.setAttribute('aria-expanded', 'true');+ document.body.append(content, toggle, header);++ HS.toggleSemanticPanel();+ expect(content.style.display).toBe('none');+ expect(toggle.className).toBe('fas fa-chevron-right');+ expect(header.getAttribute('aria-expanded')).toBe('false');++ HS.toggleSemanticPanel();+ expect(content.style.display).toBe('block');+ expect(toggle.className).toBe('fas fa-chevron-down');+ expect(header.getAttribute('aria-expanded')).toBe('true');+ });++ it('does nothing when expected elements are missing', () => {+ expect(() => HS.toggleSemanticPanel()).not.toThrow();+ });+});diff --git a/tests/js/components/library-search.test.js b/tests/js/components/library-search.test.jsnew file mode 100644index 0000000000..241f54367d--- /dev/null+++ b/tests/js/components/library-search.test.js@@ -0,0 +1,273 @@+/**+ * Tests for components/library_search.js+ *+ * Tests the LibrarySearch utilities:+ * fileTypeIcon, initLibrarySearch, getIndexedCollectionIds,+ * getDefaultCollectionId, searchAllCollections (deduplication logic),+ * renderSemanticResults.+ */++// Stub URLBuilder before loading the module+window.URLBuilder = {+ build: (template, id) => template.replace('{id}', id),+ documentPage: (id) => `/library/document/${id}`,+};+window.URLS = {+ LIBRARY_API: {+ COLLECTION_SEARCH: '/library/api/collections/{id}/search',+ },+};++import '@js/components/library_search.js';++const LS = window.LibrarySearch;++describe('LibrarySearch', () => {+ describe('initLibrarySearch', () => {+ it('stores default collection ID', () => {+ LS.initLibrarySearch('default-coll', []);+ expect(LS.getDefaultCollectionId()).toBe('default-coll');+ });++ it('stores collections data', () => {+ LS.initLibrarySearch(null, [+ { id: 'a', indexed_document_count: 5 },+ { id: 'b', indexed_document_count: 0 },+ { id: 'c', indexed_document_count: 10 },+ ]);+ expect(LS.getIndexedCollectionIds()).toEqual(['a', 'c']);+ });++ it('handles null/undefined args', () => {+ LS.initLibrarySearch(null, null);+ expect(LS.getDefaultCollectionId()).toBeNull();+ expect(LS.getIndexedCollectionIds()).toEqual([]);+ });+ });++ describe('getIndexedCollectionIds', () => {+ it('filters out collections with 0 indexed documents', () => {+ LS.initLibrarySearch(null, [+ { id: 'a', indexed_document_count: 5 },+ { id: 'b', indexed_document_count: 0 },+ { id: 'c' }, // missing field — treated as 0+ ]);+ expect(LS.getIndexedCollectionIds()).toEqual(['a']);+ });++ it('returns empty array for no collections', () => {+ LS.initLibrarySearch(null, []);+ expect(LS.getIndexedCollectionIds()).toEqual([]);+ });+ });++ describe('LIBRARY_CARD_CONFIG', () => {+ const config = LS.getLibraryCardConfig();++ it('getId returns document_id', () => {+ expect(config.getId({ document_id: 'doc-1' })).toBe('doc-1');+ expect(config.getId({})).toBe('');+ });++ it('getTitle returns title or "Untitled"', () => {+ expect(config.getTitle({ title: 'My Doc' })).toBe('My Doc');+ expect(config.getTitle({})).toBe('Untitled');+ });++ it('getUrl builds document page URL', () => {+ expect(config.getUrl({ document_id: 'abc' })).toBe('/library/document/abc');+ });++ it('getUrl returns # for missing document_id', () => {+ expect(config.getUrl({})).toBe('#');+ });++ it('getBadges returns file type badge', () => {+ const badges = config.getBadges({ file_type: 'pdf' });+ expect(badges).toHaveLength(1);+ expect(badges[0].label).toBe('PDF');+ expect(badges[0].icon).toBe('file-pdf');+ });++ it('getBadges returns default DOC badge when no file type', () => {+ const badges = config.getBadges({});+ expect(badges[0].label).toBe('DOC');+ expect(badges[0].icon).toBe('file');+ });++ it('getBadges maps known file types to icons', () => {+ expect(config.getBadges({ file_type: 'txt' })[0].icon).toBe('file-alt');+ expect(config.getBadges({ file_type: 'md' })[0].icon).toBe('file-code');+ expect(config.getBadges({ file_type: 'markdown' })[0].icon).toBe('file-code');+ expect(config.getBadges({ file_type: 'html' })[0].icon).toBe('file-code');+ });++ it('getDate returns created_at', () => {+ expect(config.getDate({ created_at: '2025-01-15' })).toBe('2025-01-15');+ expect(config.getDate({})).toBeNull();+ });++ it('getSubtitle returns domain', () => {+ expect(config.getSubtitle({ domain: 'example.com' })).toBe('example.com');+ expect(config.getSubtitle({})).toBeNull();+ });+ });++ describe('searchAllCollections deduplication', () => {+ let originalFetch;++ beforeEach(() => {+ originalFetch = globalThis.fetch;+ });++ afterEach(() => {+ globalThis.fetch = originalFetch;+ });++ it('returns empty array for empty collection list', async () => {+ const result = await LS.searchAllCollections([], 'query');+ expect(result).toEqual([]);+ });++ it('deduplicates results by document_id, keeping highest similarity', async () => {+ // Mock fetch to return overlapping results from two collections+ globalThis.fetch = vi.fn()+ .mockResolvedValueOnce({+ ok: true,+ json: () => Promise.resolve({+ success: true,+ results: [+ { document_id: 'doc1', similarity: 0.5 },+ { document_id: 'doc2', similarity: 0.9 },+ ],+ }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: () => Promise.resolve({+ success: true,+ results: [+ { document_id: 'doc1', similarity: 0.8 }, // higher than first+ { document_id: 'doc3', similarity: 0.6 },+ ],+ }),+ });++ const result = await LS.searchAllCollections(['c1', 'c2'], 'test');+ // Should have 3 unique docs+ expect(result).toHaveLength(3);+ // doc1 should have similarity 0.8 (the higher one)+ const doc1 = result.find(r => r.document_id === 'doc1');+ expect(doc1.similarity).toBe(0.8);+ });++ it('sorts results by similarity descending', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({+ success: true,+ results: [+ { document_id: 'a', similarity: 0.3 },+ { document_id: 'b', similarity: 0.9 },+ { document_id: 'c', similarity: 0.6 },+ ],+ }),+ });++ const result = await LS.searchAllCollections(['c1'], 'test');+ expect(result.map(r => r.document_id)).toEqual(['b', 'c', 'a']);+ });++ it('handles failed search responses gracefully', async () => {+ globalThis.fetch = vi.fn()+ .mockResolvedValueOnce({+ ok: true,+ json: () => Promise.resolve({ success: false }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: () => Promise.resolve({+ success: true,+ results: [{ document_id: 'd1', similarity: 0.7 }],+ }),+ });++ const result = await LS.searchAllCollections(['c1', 'c2'], 'test');+ expect(result).toHaveLength(1);+ expect(result[0].document_id).toBe('d1');+ });++ it('catches per-collection fetch errors', async () => {+ globalThis.fetch = vi.fn()+ .mockRejectedValueOnce(new Error('network'))+ .mockResolvedValueOnce({+ ok: true,+ json: () => Promise.resolve({+ success: true,+ results: [{ document_id: 'd1', similarity: 0.5 }],+ }),+ });++ const result = await LS.searchAllCollections(['c1', 'c2'], 'test');+ expect(result).toHaveLength(1);+ });++ it('respects limit parameter', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({+ success: true,+ results: Array.from({ length: 30 }, (_, i) => ({+ document_id: `doc${i}`,+ similarity: 1 - i * 0.01,+ })),+ }),+ });++ const result = await LS.searchAllCollections(['c1'], 'test', 5);+ expect(result).toHaveLength(5);+ });++ it('skips results without document_id', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({+ success: true,+ results: [+ { document_id: 'a', similarity: 0.5 },+ { similarity: 0.9 }, // missing document_id+ ],+ }),+ });++ const result = await LS.searchAllCollections(['c1'], 'test');+ expect(result).toHaveLength(1);+ expect(result[0].document_id).toBe('a');+ });+ });++ describe('renderSemanticResults', () => {+ it('renders empty state when no results', () => {+ const container = document.createElement('div');+ LS.renderSemanticResults([], container, 'query');+ expect(container.querySelector('.ldr-empty-state')).not.toBeNull();+ });++ it('renders empty state for null results', () => {+ const container = document.createElement('div');+ LS.renderSemanticResults(null, container, 'query');+ expect(container.querySelector('.ldr-empty-state')).not.toBeNull();+ });++ it('does nothing when container is null', () => {+ expect(() => LS.renderSemanticResults([], null, 'q')).not.toThrow();+ });++ it('renders fallback message when SemanticSearch module not loaded', () => {+ const container = document.createElement('div');+ // SemanticSearch not loaded in tests+ LS.renderSemanticResults([{ document_id: '1' }], container, 'q');+ expect(container.textContent).toContain('Search module not loaded');+ });+ });+});diff --git a/tests/js/components/news.test.js b/tests/js/components/news.test.jsnew file mode 100644index 0000000000..c3bda251da--- /dev/null+++ b/tests/js/components/news.test.js@@ -0,0 +1,219 @@+/**+ * Tests for components/news.js+ *+ * Tests the news utility functions: formatTimeAgo, debounce, createTag,+ * showEmptyState, showLoadingState, showErrorState, showModal/hideModal.+ */++import '@js/components/news.js';++describe('NewsUtils', () => {+ describe('formatTimeAgo', () => {+ const now = new Date('2025-06-15T12:00:00Z');++ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(now);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('returns "just now" for < 60 seconds', () => {+ const time = new Date(now.getTime() - 30 * 1000);+ expect(window.formatTimeAgo(time)).toBe('just now');+ });++ it('returns minutes ago for < 1 hour', () => {+ const time = new Date(now.getTime() - 5 * 60 * 1000);+ expect(window.formatTimeAgo(time)).toBe('5 minutes ago');+ });++ it('returns hours ago for < 1 day', () => {+ const time = new Date(now.getTime() - 3 * 60 * 60 * 1000);+ expect(window.formatTimeAgo(time)).toBe('3 hours ago');+ });++ it('returns days ago for < 1 week', () => {+ const time = new Date(now.getTime() - 4 * 24 * 60 * 60 * 1000);+ expect(window.formatTimeAgo(time)).toBe('4 days ago');+ });++ it('returns date string for older timestamps', () => {+ const time = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);+ const result = window.formatTimeAgo(time);+ // Should be a date string, not "X ago"+ expect(result).not.toContain('ago');+ });+ });++ describe('createTag', () => {+ it('creates a span element with the text', () => {+ const tag = window.createTag('javascript');+ expect(tag.tagName).toBe('SPAN');+ expect(tag.textContent).toBe('javascript');+ });++ it('uses default ldr-tag class', () => {+ const tag = window.createTag('test');+ expect(tag.className).toBe('ldr-tag');+ });++ it('accepts custom class name', () => {+ const tag = window.createTag('test', 'custom-class');+ expect(tag.className).toBe('custom-class');+ });++ it('uses textContent (XSS-safe)', () => {+ const tag = window.createTag('<script>alert(1)</script>');+ expect(tag.innerHTML).not.toContain('<script>');+ expect(tag.textContent).toBe('<script>alert(1)</script>');+ });+ });++ describe('debounce', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('delays function execution', () => {+ const fn = vi.fn();+ const debounced = window.debounce(fn, 100);+ debounced();+ expect(fn).not.toHaveBeenCalled();+ vi.advanceTimersByTime(100);+ expect(fn).toHaveBeenCalledTimes(1);+ });++ it('cancels previous calls when called again', () => {+ const fn = vi.fn();+ const debounced = window.debounce(fn, 100);+ debounced();+ vi.advanceTimersByTime(50);+ debounced();+ vi.advanceTimersByTime(50);+ expect(fn).not.toHaveBeenCalled();+ vi.advanceTimersByTime(50);+ expect(fn).toHaveBeenCalledTimes(1);+ });++ it('passes arguments to debounced function', () => {+ const fn = vi.fn();+ const debounced = window.debounce(fn, 50);+ debounced('a', 'b', 'c');+ vi.advanceTimersByTime(50);+ expect(fn).toHaveBeenCalledWith('a', 'b', 'c');+ });+ });++ describe('showEmptyState', () => {+ it('renders empty state HTML in container', () => {+ const container = document.createElement('div');+ window.showEmptyState(container, 'No data');+ expect(container.querySelector('.ldr-empty-state')).not.toBeNull();+ expect(container.textContent).toContain('No data');+ });++ it('uses default newspaper icon', () => {+ const container = document.createElement('div');+ window.showEmptyState(container, 'Empty');+ expect(container.innerHTML).toContain('fa-newspaper');+ });++ it('accepts custom icon', () => {+ const container = document.createElement('div');+ window.showEmptyState(container, 'Empty', 'fas fa-search');+ expect(container.innerHTML).toContain('fa-search');+ });++ it('escapes HTML in message', () => {+ const container = document.createElement('div');+ window.showEmptyState(container, '<script>xss</script>');+ expect(container.innerHTML).not.toContain('<script>');+ });+ });++ describe('showLoadingState', () => {+ it('renders loading state HTML', () => {+ const container = document.createElement('div');+ window.showLoadingState(container);+ expect(container.querySelector('.ldr-loading-placeholder')).not.toBeNull();+ expect(container.textContent).toContain('Loading...');+ });++ it('accepts custom message', () => {+ const container = document.createElement('div');+ window.showLoadingState(container, 'Fetching data...');+ expect(container.textContent).toContain('Fetching data...');+ });++ it('escapes HTML in message', () => {+ const container = document.createElement('div');+ window.showLoadingState(container, '<img src=x onerror=alert(1)>');+ expect(container.innerHTML).not.toContain('<img');+ });+ });++ describe('showErrorState', () => {+ it('renders error state HTML', () => {+ const container = document.createElement('div');+ window.showErrorState(container, 'Connection failed');+ expect(container.querySelector('.ldr-error-state')).not.toBeNull();+ expect(container.textContent).toContain('Connection failed');+ });++ it('escapes HTML in message', () => {+ const container = document.createElement('div');+ window.showErrorState(container, '<script>xss</script>');+ expect(container.innerHTML).not.toContain('<script>');+ });+ });++ describe('showModal / hideModal', () => {+ let modal;++ beforeEach(() => {+ modal = document.createElement('div');+ modal.id = 'test-modal';+ modal.style.display = 'none';+ document.body.appendChild(modal);+ });++ afterEach(() => {+ modal.remove();+ document.body.style.overflow = '';+ });++ it('shows the modal by ID', () => {+ window.showModal('test-modal');+ expect(modal.style.display).toBe('flex');+ });++ it('locks body scroll when shown', () => {+ window.showModal('test-modal');+ expect(document.body.style.overflow).toBe('hidden');+ });++ it('hides the modal by ID', () => {+ window.showModal('test-modal');+ window.hideModal('test-modal');+ expect(modal.style.display).toBe('none');+ });++ it('restores body scroll when hidden', () => {+ window.showModal('test-modal');+ window.hideModal('test-modal');+ expect(document.body.style.overflow).toBe('auto');+ });++ it('does nothing for non-existent modal', () => {+ expect(() => window.showModal('nonexistent')).not.toThrow();+ expect(() => window.hideModal('nonexistent')).not.toThrow();+ });+ });+});diff --git a/tests/js/components/semantic-search.test.js b/tests/js/components/semantic-search.test.jsnew file mode 100644index 0000000000..bb64e7b641--- /dev/null+++ b/tests/js/components/semantic-search.test.js@@ -0,0 +1,204 @@+/**+ * Tests for components/semantic_search.js+ *+ * Focus on the pure data-shaping helpers exposed via window.SemanticSearch:+ * - buildTieredResults: 3-tier merge with dedup + sort+ * - isSafeExternalUrl: URL scheme validation (security-critical)+ *+ * createSemanticResultCard and renderSnippet do DOM/markdown work and depend+ * on optional libraries (marked, DOMPurify) — exercised via integration in+ * library-search tests already.+ */++import '@js/components/semantic_search.js';++const SS = window.SemanticSearch;++describe('SemanticSearch.buildTieredResults', () => {+ it('returns empty tiers for empty inputs', () => {+ const r = SS.buildTieredResults([], []);+ expect(r.tier1).toEqual([]);+ expect(r.tier2).toEqual([]);+ expect(r.tier3).toEqual([]);+ });++ it('puts text-only matches in tier2 (preserving original order)', () => {+ const text = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];+ const r = SS.buildTieredResults(text, []);+ expect(r.tier1).toEqual([]);+ expect(r.tier3).toEqual([]);+ expect(r.tier2.map(x => x.historyItem.id)).toEqual(['a', 'b', 'c']);+ });++ it('puts semantic-only matches in tier3', () => {+ const sem = [+ { research_id: 'x', similarity: 0.5 },+ { research_id: 'y', similarity: 0.8 },+ ];+ const r = SS.buildTieredResults([], sem);+ expect(r.tier1).toEqual([]);+ expect(r.tier2).toEqual([]);+ expect(r.tier3).toHaveLength(2);+ });++ it('places items appearing in both tiers in tier1 with semanticMatch populated', () => {+ const text = [{ id: 'a' }, { id: 'b' }];+ const sem = [+ { research_id: 'a', similarity: 0.7, snippet: 'hi' },+ { research_id: 'c', similarity: 0.9 },+ ];+ const r = SS.buildTieredResults(text, sem);+ expect(r.tier1).toHaveLength(1);+ expect(r.tier1[0].historyItem.id).toBe('a');+ expect(r.tier1[0].semanticMatch.similarity).toBe(0.7);+ expect(r.tier1[0].semanticMatch.snippet).toBe('hi');+ // 'b' was text-only → tier2+ expect(r.tier2.map(x => x.historyItem.id)).toEqual(['b']);+ // 'c' was semantic-only → tier3+ expect(r.tier3.map(x => x.semanticResult.research_id)).toEqual(['c']);+ });++ it('sorts tier1 by similarity DESC', () => {+ const text = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];+ const sem = [+ { research_id: 'a', similarity: 0.3 },+ { research_id: 'b', similarity: 0.9 },+ { research_id: 'c', similarity: 0.6 },+ ];+ const r = SS.buildTieredResults(text, sem);+ expect(r.tier1.map(x => x.historyItem.id)).toEqual(['b', 'c', 'a']);+ });++ it('sorts tier3 by similarity DESC', () => {+ const sem = [+ { research_id: 'a', similarity: 0.2 },+ { research_id: 'b', similarity: 0.95 },+ { research_id: 'c', similarity: 0.5 },+ ];+ const r = SS.buildTieredResults([], sem);+ expect(r.tier3.map(x => x.semanticResult.research_id)).toEqual(['b', 'c', 'a']);+ });++ it('dedups semantic results by ID, keeping the highest similarity', () => {+ const sem = [+ { research_id: 'dup', similarity: 0.3 },+ { research_id: 'dup', similarity: 0.8 },+ { research_id: 'dup', similarity: 0.5 },+ ];+ const r = SS.buildTieredResults([], sem);+ expect(r.tier3).toHaveLength(1);+ expect(r.tier3[0].semanticResult.similarity).toBe(0.8);+ });++ it('skips semantic results missing the configured ID key', () => {+ const sem = [+ { research_id: 'a', similarity: 0.5 },+ { similarity: 0.9 }, // missing research_id+ { research_id: '', similarity: 0.7 }, // empty falsy+ ];+ const r = SS.buildTieredResults([], sem);+ expect(r.tier3).toHaveLength(1);+ expect(r.tier3[0].semanticResult.research_id).toBe('a');+ });++ it('honors custom textIdKey and semanticIdKey', () => {+ const text = [{ doc_id: 'x' }];+ const sem = [{ id: 'x', similarity: 0.5 }];+ const r = SS.buildTieredResults(text, sem, {+ textIdKey: 'doc_id',+ semanticIdKey: 'id',+ });+ expect(r.tier1).toHaveLength(1);+ expect(r.tier1[0].historyItem.doc_id).toBe('x');+ });++ it('uses default keys when options is undefined', () => {+ const text = [{ id: 'k' }];+ const sem = [{ research_id: 'k', similarity: 0.5 }];+ const r = SS.buildTieredResults(text, sem);+ expect(r.tier1).toHaveLength(1);+ });++ it('coerces IDs to strings for matching (number vs string)', () => {+ const text = [{ id: 42 }];+ const sem = [{ research_id: '42', similarity: 0.5 }];+ const r = SS.buildTieredResults(text, sem);+ expect(r.tier1).toHaveLength(1);+ });++ it('defaults snippet to empty string when missing', () => {+ const text = [{ id: 'a' }];+ const sem = [{ research_id: 'a', similarity: 0.5 }];+ const r = SS.buildTieredResults(text, sem);+ expect(r.tier1[0].semanticMatch.snippet).toBe('');+ });+});++describe('SemanticSearch.isSafeExternalUrl', () => {+ let savedValidator;++ beforeEach(() => {+ // Force the fallback path so we test the inline scheme list,+ // not URLValidator's behavior (covered by url-validator tests).+ savedValidator = window.URLValidator;+ delete window.URLValidator;+ });++ afterEach(() => {+ if (savedValidator !== undefined) window.URLValidator = savedValidator;+ });++ it('accepts http and https URLs', () => {+ expect(SS.isSafeExternalUrl('http://example.com')).toBe(true);+ expect(SS.isSafeExternalUrl('https://example.com/path?q=1')).toBe(true);+ });++ it('rejects javascript: URLs', () => {+ expect(SS.isSafeExternalUrl('javascript:alert(1)')).toBe(false);+ });++ it('rejects data: URLs', () => {+ expect(SS.isSafeExternalUrl('data:text/html,<script>alert(1)</script>')).toBe(false);+ });++ it('rejects vbscript: URLs', () => {+ expect(SS.isSafeExternalUrl('vbscript:msgbox(1)')).toBe(false);+ });++ it('rejects about:, blob:, file: schemes', () => {+ expect(SS.isSafeExternalUrl('about:blank')).toBe(false);+ expect(SS.isSafeExternalUrl('blob:https://example.com/abc')).toBe(false);+ expect(SS.isSafeExternalUrl('file:///etc/passwd')).toBe(false);+ });++ it('rejects non-string input', () => {+ expect(SS.isSafeExternalUrl(null)).toBe(false);+ expect(SS.isSafeExternalUrl(undefined)).toBe(false);+ expect(SS.isSafeExternalUrl(42)).toBe(false);+ expect(SS.isSafeExternalUrl({})).toBe(false);+ });++ it('rejects empty string', () => {+ expect(SS.isSafeExternalUrl('')).toBe(false);+ });++ it('is case-insensitive against scheme obfuscation', () => {+ expect(SS.isSafeExternalUrl('JaVaScRiPt:alert(1)')).toBe(false);+ });++ it('rejects relative URLs (no scheme)', () => {+ expect(SS.isSafeExternalUrl('/relative/path')).toBe(false);+ expect(SS.isSafeExternalUrl('example.com')).toBe(false);+ });++ it('delegates to URLValidator when present', () => {+ window.URLValidator = {+ isSafeUrl: vi.fn().mockReturnValue(true),+ };+ expect(SS.isSafeExternalUrl('https://example.com')).toBe(true);+ expect(window.URLValidator.isSafeUrl).toHaveBeenCalledWith(+ 'https://example.com',+ { allowMailto: false }+ );+ });+});diff --git a/tests/js/config/constants.test.js b/tests/js/config/constants.test.jsnew file mode 100644index 0000000000..5c4d5f83f8--- /dev/null+++ b/tests/js/config/constants.test.js@@ -0,0 +1,237 @@+/**+ * Tests for ResearchStates (config/constants.js)+ *+ * Tests the status predicate helpers and formatting utilities+ * that are used throughout the frontend to determine research state.+ */++// Stub the backend-injected constants before loading the module+window.RESEARCH_STATUS = {+ IN_PROGRESS: 'in_progress',+ COMPLETED: 'completed',+ FAILED: 'failed',+ SUSPENDED: 'suspended',+ CANCELLED: 'cancelled',+ QUEUED: 'queued',+ PENDING: 'pending',+ ERROR: 'error',+};++window.RESEARCH_TERMINAL_STATES = new Set([+ 'completed', 'suspended', 'failed', 'error', 'cancelled',+]);++// Load the module — attaches window.LDR_CONSTANTS and window.ResearchStates+import '@js/config/constants.js';++const RS = window.ResearchStates;++describe('LDR_CONSTANTS', () => {+ it('defines SEARCH_MODE values', () => {+ expect(window.LDR_CONSTANTS.SEARCH_MODE.HYBRID).toBe('hybrid');+ expect(window.LDR_CONSTANTS.SEARCH_MODE.TEXT).toBe('text');+ expect(window.LDR_CONSTANTS.SEARCH_MODE.SEMANTIC).toBe('semantic');+ });+});++describe('ResearchStates', () => {+ describe('isTerminal', () => {+ it('returns true for completed', () => {+ expect(RS.isTerminal('completed')).toBe(true);+ });++ it('returns true for failed', () => {+ expect(RS.isTerminal('failed')).toBe(true);+ });++ it('returns true for error', () => {+ expect(RS.isTerminal('error')).toBe(true);+ });++ it('returns true for suspended', () => {+ expect(RS.isTerminal('suspended')).toBe(true);+ });++ it('returns true for cancelled', () => {+ expect(RS.isTerminal('cancelled')).toBe(true);+ });++ it('returns false for in_progress', () => {+ expect(RS.isTerminal('in_progress')).toBe(false);+ });++ it('returns false for queued', () => {+ expect(RS.isTerminal('queued')).toBe(false);+ });++ it('returns false for pending', () => {+ expect(RS.isTerminal('pending')).toBe(false);+ });+ });++ describe('isCompleted', () => {+ it('returns true only for completed status', () => {+ expect(RS.isCompleted('completed')).toBe(true);+ });++ it('returns false for failed', () => {+ expect(RS.isCompleted('failed')).toBe(false);+ });++ it('returns false for in_progress', () => {+ expect(RS.isCompleted('in_progress')).toBe(false);+ });+ });++ describe('isFailed', () => {+ it('returns true for failed', () => {+ expect(RS.isFailed('failed')).toBe(true);+ });++ it('returns true for legacy error status', () => {+ expect(RS.isFailed('error')).toBe(true);+ });++ it('returns false for completed', () => {+ expect(RS.isFailed('completed')).toBe(false);+ });++ it('returns false for cancelled', () => {+ expect(RS.isFailed('cancelled')).toBe(false);+ });+ });++ describe('isCancelled', () => {+ it('returns true for cancelled', () => {+ expect(RS.isCancelled('cancelled')).toBe(true);+ });++ it('returns true for suspended', () => {+ expect(RS.isCancelled('suspended')).toBe(true);+ });++ it('returns false for failed', () => {+ expect(RS.isCancelled('failed')).toBe(false);+ });++ it('returns false for completed', () => {+ expect(RS.isCancelled('completed')).toBe(false);+ });+ });++ describe('isInProgress', () => {+ it('returns true for in_progress', () => {+ expect(RS.isInProgress('in_progress')).toBe(true);+ });++ it('returns false for queued', () => {+ expect(RS.isInProgress('queued')).toBe(false);+ });++ it('returns false for completed', () => {+ expect(RS.isInProgress('completed')).toBe(false);+ });+ });++ describe('isActive', () => {+ it('returns true for in_progress', () => {+ expect(RS.isActive('in_progress')).toBe(true);+ });++ it('returns true for queued', () => {+ expect(RS.isActive('queued')).toBe(true);+ });++ it('returns true for pending', () => {+ expect(RS.isActive('pending')).toBe(true);+ });++ it('returns false for completed', () => {+ expect(RS.isActive('completed')).toBe(false);+ });++ it('returns false for failed', () => {+ expect(RS.isActive('failed')).toBe(false);+ });+ });++ describe('formatStatus', () => {+ it('maps in_progress to In Progress', () => {+ expect(RS.formatStatus('in_progress')).toBe('In Progress');+ });++ it('maps completed to Completed', () => {+ expect(RS.formatStatus('completed')).toBe('Completed');+ });++ it('maps failed to Failed', () => {+ expect(RS.formatStatus('failed')).toBe('Failed');+ });++ it('maps suspended to Cancelled', () => {+ expect(RS.formatStatus('suspended')).toBe('Cancelled');+ });++ it('maps cancelled to Cancelled', () => {+ expect(RS.formatStatus('cancelled')).toBe('Cancelled');+ });++ it('maps queued to Queued', () => {+ expect(RS.formatStatus('queued')).toBe('Queued');+ });++ it('maps pending to Pending', () => {+ expect(RS.formatStatus('pending')).toBe('Pending');+ });++ it('maps error to Error', () => {+ expect(RS.formatStatus('error')).toBe('Error');+ });++ it('maps not_started to Not Started', () => {+ expect(RS.formatStatus('not_started')).toBe('Not Started');+ });++ it('capitalizes unknown statuses and replaces underscores', () => {+ expect(RS.formatStatus('some_custom_status')).toBe('Some custom status');+ });++ it('returns Unknown for falsy input', () => {+ expect(RS.formatStatus(null)).toBe('Unknown');+ expect(RS.formatStatus(undefined)).toBe('Unknown');+ expect(RS.formatStatus('')).toBe('Unknown');+ });+ });++ describe('logLevel', () => {+ it('returns error for error status', () => {+ expect(RS.logLevel('error')).toBe('error');+ });++ it('returns error for statuses containing "error"', () => {+ expect(RS.logLevel('some_error_state')).toBe('error');+ });++ it('returns milestone for terminal states (non-error)', () => {+ expect(RS.logLevel('completed')).toBe('milestone');+ expect(RS.logLevel('failed')).toBe('milestone');+ expect(RS.logLevel('cancelled')).toBe('milestone');+ });++ it('returns info for active states', () => {+ expect(RS.logLevel('in_progress')).toBe('info');+ expect(RS.logLevel('queued')).toBe('info');+ expect(RS.logLevel('pending')).toBe('info');+ });++ it('returns info for falsy input', () => {+ expect(RS.logLevel(null)).toBe('info');+ expect(RS.logLevel(undefined)).toBe('info');+ expect(RS.logLevel('')).toBe('info');+ });+ });++ it('is frozen (immutable)', () => {+ expect(Object.isFrozen(RS)).toBe(true);+ });+});diff --git a/tests/js/config/urls.test.js b/tests/js/config/urls.test.jsnew file mode 100644index 0000000000..8ce8f9f94c--- /dev/null+++ b/tests/js/config/urls.test.js@@ -0,0 +1,162 @@+/**+ * Tests for config/urls.js — URLBuilder behavior+ *+ * Focuses on the URLBuilder logic (placeholder substitution, ID extraction,+ * page-type detection). Does NOT test that URL constants equal specific+ * literals — those tests would just assert the source against itself.+ */++import '@js/config/urls.js';++const { URLS, URLBuilder } = window;++describe('URLBuilder', () => {+ describe('build', () => {+ it('replaces {id} placeholder', () => {+ expect(URLBuilder.build('/api/research/{id}', 42)).toBe('/api/research/42');+ });++ it('handles string IDs', () => {+ expect(URLBuilder.build('/api/research/{id}', 'abc-123')).toBe('/api/research/abc-123');+ });++ it('only replaces first {id} occurrence', () => {+ expect(URLBuilder.build('/api/{id}/{id}', 5)).toBe('/api/5/{id}');+ });++ it('returns template unchanged when no {id} placeholder', () => {+ expect(URLBuilder.build('/api/static', 5)).toBe('/api/static');+ });+ });++ describe('buildWithReplacements', () => {+ it('replaces multiple distinct placeholders', () => {+ const result = URLBuilder.buildWithReplacements(+ '/api/collection/{collectionId}/document/{documentId}',+ { collectionId: '10', documentId: '20' }+ );+ expect(result).toBe('/api/collection/10/document/20');+ });++ it('handles missing placeholder gracefully', () => {+ const result = URLBuilder.buildWithReplacements(+ '/api/{a}/{b}',+ { a: '1' }+ );+ expect(result).toBe('/api/1/{b}');+ });++ it('handles empty replacements object', () => {+ expect(URLBuilder.buildWithReplacements('/api/{id}', {})).toBe('/api/{id}');+ });+ });++ describe('convenience methods build URLs from URLS constants', () => {+ // These test that the convenience methods correctly compose URLBuilder.build+ // with the right URLS constant — not what those constants are.++ it('progressPage substitutes ID into PAGES.PROGRESS', () => {+ expect(URLBuilder.progressPage(42)).toBe(URLS.PAGES.PROGRESS.replace('{id}', '42'));+ });++ it('researchStatus substitutes ID into API.RESEARCH_STATUS', () => {+ expect(URLBuilder.researchStatus(42)).toBe(URLS.API.RESEARCH_STATUS.replace('{id}', '42'));+ });++ it('terminateResearch substitutes ID into API.TERMINATE_RESEARCH', () => {+ expect(URLBuilder.terminateResearch(42)).toBe(URLS.API.TERMINATE_RESEARCH.replace('{id}', '42'));+ });++ it('deleteResearch substitutes ID into API.DELETE_RESEARCH', () => {+ expect(URLBuilder.deleteResearch(42)).toBe(URLS.API.DELETE_RESEARCH.replace('{id}', '42'));+ });++ it('historyStatus substitutes ID into HISTORY_API.STATUS', () => {+ expect(URLBuilder.historyStatus(42)).toBe(URLS.HISTORY_API.STATUS.replace('{id}', '42'));+ });++ it('getSetting substitutes key into SETTINGS_API.GET_SETTING', () => {+ const url = URLBuilder.getSetting('llm.model');+ expect(url).toContain('llm.model');+ expect(url).toBe(URLS.SETTINGS_API.GET_SETTING.replace('{key}', 'llm.model'));+ });++ it('researchMetrics substitutes ID into METRICS_API.RESEARCH', () => {+ expect(URLBuilder.researchMetrics(42)).toBe(URLS.METRICS_API.RESEARCH.replace('{id}', '42'));+ });+ });++ describe('extractResearchIdFromPattern', () => {+ // We can't easily change window.location.pathname in happy-dom,+ // but we can verify the regex pattern construction works for the+ // current path (which is "/" by default → no match).+ it('returns null when pattern not in current path', () => {+ expect(URLBuilder.extractResearchIdFromPattern('results')).toBeNull();+ });+ });++ describe('extractResearchId', () => {+ it('returns null when no ID pattern matches current path', () => {+ // Default happy-dom path is "/"+ expect(URLBuilder.extractResearchId()).toBeNull();+ });+ });++ describe('getCurrentPageType', () => {+ it('returns a valid page type for the current path', () => {+ const validTypes = ['home', 'results', 'details', 'progress',+ 'history', 'settings', 'metrics', 'unknown'];+ expect(validTypes).toContain(URLBuilder.getCurrentPageType());+ });+ });+});++describe('URLS constants — structural sanity (not literal values)', () => {+ // Lightweight invariants that catch typos without asserting exact strings.++ it('all URL templates start with /', () => {+ const collectGroup = (group) => Object.values(group);+ const allUrls = [+ ...collectGroup(URLS.API),+ ...collectGroup(URLS.PAGES),+ ...collectGroup(URLS.HISTORY_API),+ ...collectGroup(URLS.SETTINGS_API),+ ...collectGroup(URLS.METRICS_API),+ ...collectGroup(URLS.LIBRARY_API),+ ];+ for (const url of allUrls) {+ expect(url).toMatch(/^\//);+ }+ });++ it('no URLs contain accidental double slashes', () => {+ const collectGroup = (group) => Object.values(group);+ const allUrls = [+ ...collectGroup(URLS.API),+ ...collectGroup(URLS.PAGES),+ ...collectGroup(URLS.HISTORY_API),+ ...collectGroup(URLS.SETTINGS_API),+ ];+ for (const url of allUrls) {+ expect(url).not.toMatch(/\/\//);+ }+ });++ it('settings API routes are namespaced under /settings/', () => {+ for (const [key, url] of Object.entries(URLS.SETTINGS_API)) {+ expect(url, `SETTINGS_API.${key}`).toMatch(/^\/settings\//);+ }+ });++ it('metrics API routes are namespaced under /metrics/', () => {+ for (const [key, url] of Object.entries(URLS.METRICS_API)) {+ expect(url, `METRICS_API.${key}`).toMatch(/^\/metrics\//);+ }+ });++ it('library API routes are namespaced under /library/', () => {+ for (const [key, url] of Object.entries(URLS.LIBRARY_API)) {+ expect(url, `LIBRARY_API.${key}`).toMatch(/^\/library\//);+ }+ });+});diff --git a/tests/js/deletion/delete-modules.test.js b/tests/js/deletion/delete-modules.test.jsnew file mode 100644index 0000000000..d06c14a040--- /dev/null+++ b/tests/js/deletion/delete-modules.test.js@@ -0,0 +1,384 @@+/**+ * Tests for deletion modules — confirmation_modal.js and delete_manager.js+ *+ * Focuses on actual workflow behavior: API calls, error handling,+ * success/failure callbacks, preview-driven confirmation messages,+ * and the formatBytes utility. Skips trivial "API shape" assertions.+ */++import '@js/deletion/confirmation_modal.js';++describe('DeleteConfirmation tooltip lookup', () => {+ it('returns the configured tooltip for a known action', () => {+ // We test that lookup works without asserting exact tooltip text+ const tooltip = window.DeleteConfirmation.getTooltip('deleteDocument');+ expect(tooltip).toBeTypeOf('string');+ expect(tooltip.length).toBeGreaterThan(0);+ });++ it('returns a generic fallback for unknown actions', () => {+ expect(window.DeleteConfirmation.getTooltip('unknownAction')).toBe('Delete this item');+ });++ it('marks all destructive actions as dangerous', () => {+ const actions = window.DeleteConfirmation.ACTIONS;+ // Behavioral invariant: deletion actions whose name starts with "delete"+ // and which permanently destroy data must be flagged dangerous.+ expect(actions.deleteDocument.dangerous).toBe(true);+ expect(actions.deleteCollection.dangerous).toBe(true);+ expect(actions.bulkDeleteDocuments.dangerous).toBe(true);+ });++ it('marks recoverable actions as not dangerous', () => {+ const actions = window.DeleteConfirmation.ACTIONS;+ // Removing a PDF blob keeps the text content searchable — recoverable.+ expect(actions.deleteBlob.dangerous).toBe(false);+ expect(actions.removeFromCollection.dangerous).toBe(false);+ });+});++// Now load delete_manager and stub its dependencies before importing+let DM;++beforeAll(async () => {+ window.api = {+ fetchWithErrorHandling: vi.fn(),+ getCsrfToken: () => 'test-token',+ };+ window.showToast = vi.fn();++ // Auto-confirm: bypass the modal and just run the action immediately.+ // This lets us test the actual API workflow without the modal UI.+ window.DeleteConfirmation.confirmAndRun = vi.fn(async (opts, action) => {+ await action();+ });++ await import('@js/deletion/delete_manager.js');+ DM = window.DeleteManager;+});++beforeEach(() => {+ window.api.fetchWithErrorHandling.mockReset();+ window.showToast.mockReset();+ window.DeleteConfirmation.confirmAndRun.mockClear();+});++// Flush pending microtasks. delete_manager's skipConfirm path calls+// confirmOptions.onConfirm() WITHOUT awaiting it, so test callers need+// to wait for the inner async work to settle. This is a small wart in+// the source — flushPromises() is the standard workaround.+const flushPromises = () => new Promise(resolve => setTimeout(resolve, 0));++describe('DeleteManager.formatBytes', () => {+ it('formats 0 bytes', () => {+ expect(DM.formatBytes(0)).toBe('0 Bytes');+ });++ it('formats bytes < 1024', () => {+ expect(DM.formatBytes(500)).toBe('500 Bytes');+ });++ it('formats kilobytes with decimal precision', () => {+ expect(DM.formatBytes(1024)).toBe('1 KB');+ expect(DM.formatBytes(1536)).toBe('1.5 KB');+ });++ it('formats megabytes', () => {+ expect(DM.formatBytes(1048576)).toBe('1 MB');+ });++ it('formats gigabytes', () => {+ expect(DM.formatBytes(1073741824)).toBe('1 GB');+ });++ it('chooses the right unit for boundary values', () => {+ expect(DM.formatBytes(1023)).toContain('Bytes');+ expect(DM.formatBytes(1024)).toContain('KB');+ expect(DM.formatBytes(1024 * 1024 - 1)).toContain('KB');+ expect(DM.formatBytes(1024 * 1024)).toContain('MB');+ });+});++describe('DeleteManager.deleteDocument', () => {+ it('calls DELETE on the document endpoint', async () => {+ // First call: preview lookup (GET). Second call: actual DELETE.+ window.api.fetchWithErrorHandling+ .mockResolvedValueOnce({ success: true, title: 'My Doc', has_blob: false, has_text: false })+ .mockResolvedValueOnce({ success: true });++ await DM.deleteDocument('doc-123');++ // Verify a DELETE was made to the right endpoint+ const deleteCall = window.api.fetchWithErrorHandling.mock.calls.find(+ ([url, opts]) => opts && opts.method === 'DELETE'+ );+ expect(deleteCall).toBeDefined();+ expect(deleteCall[0]).toContain('doc-123');+ });++ it('skips the preview when skipConfirm is true', async () => {+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({ success: true });++ await DM.deleteDocument('doc-456', { skipConfirm: true });+ await flushPromises();++ // Only one call (the DELETE), no preview GET+ expect(window.api.fetchWithErrorHandling).toHaveBeenCalledTimes(1);+ expect(window.api.fetchWithErrorHandling.mock.calls[0][1].method).toBe('DELETE');+ });++ it('calls onSuccess callback with API result on success', async () => {+ const onSuccess = vi.fn();+ const apiResult = { success: true, deleted_id: 'doc-789' };+ window.api.fetchWithErrorHandling.mockResolvedValueOnce(apiResult);++ await DM.deleteDocument('doc-789', { skipConfirm: true, onSuccess });+ await flushPromises();++ expect(onSuccess).toHaveBeenCalledWith(apiResult);+ });++ it('calls onError callback when API returns success: false', async () => {+ const onError = vi.fn();+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({+ success: false,+ error: 'Document is locked',+ });++ await DM.deleteDocument('doc-locked', { skipConfirm: true, onError });+ await flushPromises();++ expect(onError).toHaveBeenCalled();+ const err = onError.mock.calls[0][0];+ expect(err.message).toContain('Document is locked');+ });++ it('calls onError when fetch throws', async () => {+ const onError = vi.fn();+ window.api.fetchWithErrorHandling.mockRejectedValueOnce(new Error('Network down'));++ await DM.deleteDocument('doc-net', { skipConfirm: true, onError });+ await flushPromises();++ expect(onError).toHaveBeenCalled();+ });++ it('does not call onSuccess when API call fails', async () => {+ const onSuccess = vi.fn();+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({ success: false, error: 'fail' });++ await DM.deleteDocument('doc-x', { skipConfirm: true, onSuccess, onError: () => {} });++ expect(onSuccess).not.toHaveBeenCalled();+ });+});++describe('DeleteManager.deleteDocumentBlob', () => {+ it('calls DELETE on the document blob endpoint', async () => {+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({ success: true, bytes_freed: 2048 });++ await DM.deleteDocumentBlob('doc-1', { skipConfirm: true });+ await flushPromises();++ const call = window.api.fetchWithErrorHandling.mock.calls[0];+ expect(call[0]).toContain('doc-1');+ expect(call[0]).toContain('blob');+ expect(call[1].method).toBe('DELETE');+ });++ it('passes bytes_freed to onSuccess', async () => {+ const onSuccess = vi.fn();+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({+ success: true,+ bytes_freed: 5000,+ });++ await DM.deleteDocumentBlob('doc-1', { skipConfirm: true, onSuccess });+ await flushPromises();++ expect(onSuccess).toHaveBeenCalledWith(expect.objectContaining({ bytes_freed: 5000 }));+ });+});++describe('DeleteManager.removeFromCollection', () => {+ it('calls DELETE on the collection-document endpoint with both IDs', async () => {+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({+ success: true,+ document_deleted: false,+ });++ await DM.removeFromCollection('doc-1', 'coll-2', { skipConfirm: true });+ await flushPromises();++ const call = window.api.fetchWithErrorHandling.mock.calls[0];+ expect(call[0]).toContain('doc-1');+ expect(call[0]).toContain('coll-2');+ expect(call[1].method).toBe('DELETE');+ });++ it('handles document_deleted: true (last collection removal)', async () => {+ const onSuccess = vi.fn();+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({+ success: true,+ document_deleted: true,+ });++ await DM.removeFromCollection('doc-1', 'coll-2', { skipConfirm: true, onSuccess });+ await flushPromises();++ expect(onSuccess).toHaveBeenCalledWith(expect.objectContaining({ document_deleted: true }));+ });+});++describe('DeleteManager.deleteCollection', () => {+ it('calls DELETE on the collection endpoint', async () => {+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({+ success: true,+ documents_unlinked: 5,+ chunks_deleted: 100,+ });++ await DM.deleteCollection('coll-99', { skipConfirm: true });+ await flushPromises();++ const call = window.api.fetchWithErrorHandling.mock.calls[0];+ expect(call[0]).toContain('coll-99');+ expect(call[1].method).toBe('DELETE');+ });++ it('reports failure via onError', async () => {+ const onError = vi.fn();+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({+ success: false,+ error: 'Collection in use',+ });++ await DM.deleteCollection('coll-used', { skipConfirm: true, onError });+ await flushPromises();++ expect(onError).toHaveBeenCalled();+ });+});++describe('DeleteManager.deleteCollectionIndex', () => {+ it('calls DELETE on the index endpoint', async () => {+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({+ success: true,+ chunks_deleted: 42,+ });++ await DM.deleteCollectionIndex('coll-1', { skipConfirm: true });+ await flushPromises();++ const call = window.api.fetchWithErrorHandling.mock.calls[0];+ expect(call[0]).toContain('coll-1');+ expect(call[0]).toContain('index');+ expect(call[1].method).toBe('DELETE');+ });+});++describe('DeleteManager.bulkDeleteDocuments', () => {+ it('sends document IDs in the request body', async () => {+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({+ success: true,+ deleted: 3,+ total: 3,+ total_bytes_freed: 1024,+ });++ await DM.bulkDeleteDocuments(['a', 'b', 'c'], { skipConfirm: true });+ await flushPromises();++ const call = window.api.fetchWithErrorHandling.mock.calls[0];+ expect(call[1].method).toBe('DELETE');+ const body = JSON.parse(call[1].body);+ expect(body.document_ids).toEqual(['a', 'b', 'c']);+ });++ it('reports partial-success counts via onSuccess', async () => {+ const onSuccess = vi.fn();+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({+ success: true,+ deleted: 2,+ total: 3,+ total_bytes_freed: 2048,+ });++ await DM.bulkDeleteDocuments(['a', 'b', 'c'], { skipConfirm: true, onSuccess });+ await flushPromises();++ expect(onSuccess).toHaveBeenCalledWith(+ expect.objectContaining({ deleted: 2, total: 3 })+ );+ });+});++describe('DeleteManager.bulkDeleteBlobs', () => {+ it('sends document IDs in the request body', async () => {+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({+ success: true,+ deleted: 2,+ total_bytes_freed: 1024,+ });++ await DM.bulkDeleteBlobs(['x', 'y'], { skipConfirm: true });+ await flushPromises();++ const call = window.api.fetchWithErrorHandling.mock.calls[0];+ const body = JSON.parse(call[1].body);+ expect(body.document_ids).toEqual(['x', 'y']);+ });+});++describe('DeleteManager.bulkRemoveFromCollection', () => {+ it('sends collection ID in URL and document IDs in body', async () => {+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({+ success: true,+ unlinked: 3,+ deleted: 1,+ });++ await DM.bulkRemoveFromCollection(['a', 'b', 'c'], 'coll-7', { skipConfirm: true });+ await flushPromises();++ const call = window.api.fetchWithErrorHandling.mock.calls[0];+ expect(call[0]).toContain('coll-7');+ expect(call[1].method).toBe('DELETE');+ const body = JSON.parse(call[1].body);+ expect(body.document_ids).toEqual(['a', 'b', 'c']);+ });+});++describe('DeleteManager confirmation flow', () => {+ it('skipConfirm: true bypasses DeleteConfirmation.confirmAndRun', async () => {+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({ success: true });++ await DM.deleteDocument('doc-1', { skipConfirm: true });+ await flushPromises();++ expect(window.DeleteConfirmation.confirmAndRun).not.toHaveBeenCalled();+ });++ it('skipConfirm: false routes through confirmation', async () => {+ // The first call is the preview lookup+ window.api.fetchWithErrorHandling+ .mockResolvedValueOnce({ success: true, title: 'Doc' })+ .mockResolvedValueOnce({ success: true });++ await DM.deleteDocument('doc-2');++ expect(window.DeleteConfirmation.confirmAndRun).toHaveBeenCalled();+ });++ it('preview failure does not block the deletion (warning only)', async () => {+ // Preview throws, but the deletion should still proceed via confirmAndRun+ window.api.fetchWithErrorHandling+ .mockRejectedValueOnce(new Error('preview failed'))+ .mockResolvedValueOnce({ success: true });++ await DM.deleteDocument('doc-3');++ // confirmAndRun was still called → user still gets the dialog+ expect(window.DeleteConfirmation.confirmAndRun).toHaveBeenCalled();+ });+});diff --git a/tests/js/security/auth-validation.test.js b/tests/js/security/auth-validation.test.jsnew file mode 100644index 0000000000..717dc55093--- /dev/null+++ b/tests/js/security/auth-validation.test.js@@ -0,0 +1,104 @@+/**+ * Tests for security/auth-validation.js+ *+ * window.validatePasswordViaAPI must NEVER block submit on transport failures —+ * server-side validation is the source of truth, this is just a UX hint. So+ * every failure mode (non-OK response, network error) should resolve to+ * { valid: true, errors: [] }.+ */++import '@js/security/auth-validation.js';++describe('validatePasswordViaAPI', () => {+ let originalFetch;++ beforeEach(() => {+ originalFetch = globalThis.fetch;+ });++ afterEach(() => {+ globalThis.fetch = originalFetch;+ });++ it('returns the parsed JSON on a 200 response', async () => {+ const apiResult = { valid: false, errors: ['too short', 'no digits'] };+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve(apiResult),+ });++ const r = await window.validatePasswordViaAPI('weak', 'csrf-abc');+ expect(r).toEqual(apiResult);+ });++ it('returns valid:true on 403 (CSRF expiry) so submit is not blocked', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: false,+ status: 403,+ json: () => Promise.resolve({ error: 'CSRF expired' }),+ });++ const r = await window.validatePasswordViaAPI('whatever', 'stale');+ expect(r).toEqual({ valid: true, errors: [] });+ });++ it('returns valid:true on 500 (server error)', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: false,+ status: 500,+ json: () => Promise.resolve({}),+ });++ const r = await window.validatePasswordViaAPI('x', 't');+ expect(r).toEqual({ valid: true, errors: [] });+ });++ it('returns valid:true when fetch rejects (network error)', async () => {+ globalThis.fetch = vi.fn().mockRejectedValue(new Error('Network down'));++ const r = await window.validatePasswordViaAPI('x', 't');+ expect(r).toEqual({ valid: true, errors: [] });+ });++ it('POSTs FormData with password and csrf_token fields', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ valid: true, errors: [] }),+ });++ await window.validatePasswordViaAPI('hunter2', 'token-xyz');++ expect(globalThis.fetch).toHaveBeenCalledTimes(1);+ const [url, opts] = globalThis.fetch.mock.calls[0];+ expect(url).toBe('/auth/validate-password');+ expect(opts.method).toBe('POST');+ expect(opts.body).toBeInstanceOf(FormData);+ expect(opts.body.get('password')).toBe('hunter2');+ expect(opts.body.get('csrf_token')).toBe('token-xyz');+ });++ it('does not set Content-Type header (FormData sets its own multipart boundary)', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ valid: true, errors: [] }),+ });++ await window.validatePasswordViaAPI('x', 't');++ const [, opts] = globalThis.fetch.mock.calls[0];+ // Either no headers at all, or no Content-Type override+ expect(opts.headers).toBeUndefined();+ });++ it('returns valid:true when JSON parsing throws on a 200 response', async () => {+ // If the server returns 200 but body is malformed, json() throws+ // and the catch returns the safe default+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.reject(new Error('bad JSON')),+ });++ const r = await window.validatePasswordViaAPI('x', 't');+ expect(r).toEqual({ valid: true, errors: [] });+ });+});diff --git a/tests/js/security/safe-fetch.test.js b/tests/js/security/safe-fetch.test.jsnew file mode 100644index 0000000000..ea93569343--- /dev/null+++ b/tests/js/security/safe-fetch.test.js@@ -0,0 +1,67 @@+/**+ * Tests for security/safe-fetch.js+ *+ * Tests the safeFetch wrapper that validates URLs before making+ * fetch requests, blocking unsafe external URLs.+ */++// Load url-validator first (safe-fetch depends on it)+import '@js/security/url-validator.js';+import '@js/security/safe-fetch.js';++describe('safeFetch', () => {+ const originalFetch = globalThis.fetch;++ beforeEach(() => {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve(new Response('ok', { status: 200 }))+ );+ });++ afterEach(() => {+ globalThis.fetch = originalFetch;+ });++ it('allows internal URLs starting with /', async () => {+ await window.safeFetch('/api/research/1');+ expect(globalThis.fetch).toHaveBeenCalledWith('/api/research/1', {});+ });++ it('allows internal URLs with custom options', async () => {+ const opts = { method: 'POST', body: '{}' };+ await window.safeFetch('/api/start', opts);+ expect(globalThis.fetch).toHaveBeenCalledWith('/api/start', opts);+ });++ it('allows safe external URLs (https)', async () => {+ await window.safeFetch('https://example.com/api');+ expect(globalThis.fetch).toHaveBeenCalled();+ });++ it('allows safe external URLs (http)', async () => {+ await window.safeFetch('http://example.com/api');+ expect(globalThis.fetch).toHaveBeenCalled();+ });++ it('blocks javascript: URLs', async () => {+ await expect(window.safeFetch('javascript:alert(1)'))+ .rejects.toThrow('Blocked unsafe URL');+ });++ it('blocks data: URLs', async () => {+ await expect(window.safeFetch('data:text/html,<h1>xss</h1>'))+ .rejects.toThrow('Blocked unsafe URL');+ });++ it('blocks vbscript: URLs', async () => {+ await expect(window.safeFetch('vbscript:msgbox'))+ .rejects.toThrow('Blocked unsafe URL');+ });++ it('does not call fetch for blocked URLs', async () => {+ try {+ await window.safeFetch('javascript:void(0)');+ } catch {}+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });+});diff --git a/tests/js/security/safe-logger.test.js b/tests/js/security/safe-logger.test.jsnew file mode 100644index 0000000000..b10e5c14dc--- /dev/null+++ b/tests/js/security/safe-logger.test.js@@ -0,0 +1,319 @@+/**+ * Tests for security/safe-logger.js+ *+ * Tests the SafeLogger's environment detection, data redaction+ * in production mode, and passthrough in development mode.+ */++// Load SafeLogger — it self-registers on window+import '@js/security/safe-logger.js';++const SL = window.SafeLogger;++describe('SafeLogger', () => {+ afterEach(() => {+ SL.resetProductionMode();+ });++ describe('environment detection', () => {+ it('detects localhost as development', () => {+ // happy-dom defaults to localhost+ SL.resetProductionMode();+ expect(SL.isProduction()).toBe(false);+ });++ it('can be forced to production mode', () => {+ SL.setProductionMode(true);+ expect(SL.isProduction()).toBe(true);+ });++ it('can be forced to development mode', () => {+ SL.setProductionMode(false);+ expect(SL.isProduction()).toBe(false);+ });++ it('returns to auto-detection after reset', () => {+ SL.setProductionMode(true);+ expect(SL.isProduction()).toBe(true);+ SL.resetProductionMode();+ // localhost → development+ expect(SL.isProduction()).toBe(false);+ });++ it('getProductionMode returns null when auto-detecting', () => {+ expect(SL.getProductionMode()).toBeNull();+ });++ it('getProductionMode returns forced value', () => {+ SL.setProductionMode(true);+ expect(SL.getProductionMode()).toBe(true);+ });+ });++ describe('development mode logging', () => {+ beforeEach(() => {+ SL.setProductionMode(false);+ });++ it('passes static message through', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ SL.log('test message');+ expect(spy).toHaveBeenCalledWith('test message');+ spy.mockRestore();+ });++ it('passes dynamic data through in dev mode', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ SL.log('query:', 'climate change');+ expect(spy).toHaveBeenCalledWith('query:', 'climate change');+ spy.mockRestore();+ });++ it('extracts Error properties in dev mode', () => {+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const err = new Error('test error');+ SL.error('Failed:', err);+ const secondArg = spy.mock.calls[0][1];+ expect(secondArg).toHaveProperty('name', 'Error');+ expect(secondArg).toHaveProperty('message', 'test error');+ expect(secondArg).toHaveProperty('stack');+ spy.mockRestore();+ });++ it('extracts .message from error-like objects in dev mode', () => {+ const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ SL.warn('Issue:', { message: 'not found', code: 404 });+ expect(spy).toHaveBeenCalledWith('Issue:', 'not found');+ spy.mockRestore();+ });++ it('stringifies plain objects in dev mode', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ SL.log('Data:', { error: 'not found' });+ expect(spy).toHaveBeenCalledWith('Data:', '{"error":"not found"}');+ spy.mockRestore();+ });++ it('debug messages are emitted in dev mode', () => {+ const spy = vi.spyOn(console, 'debug').mockImplementation(() => {});+ SL.debug('debug info');+ expect(spy).toHaveBeenCalledWith('debug info');+ spy.mockRestore();+ });+ });++ describe('production mode redaction', () => {+ beforeEach(() => {+ SL.setProductionMode(true);+ });++ it('passes first string argument (static message) through', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ SL.log('User searched:', 'sensitive query');+ expect(spy.mock.calls[0][0]).toBe('User searched:');+ spy.mockRestore();+ });++ it('redacts string arguments after the first', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ SL.log('User searched:', 'sensitive query');+ expect(spy.mock.calls[0][1]).toBe('[redacted]');+ spy.mockRestore();+ });++ it('redacts numbers', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ SL.log('Research ID:', 42);+ expect(spy.mock.calls[0][1]).toBe('[redacted]');+ spy.mockRestore();+ });++ it('preserves booleans in production', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ SL.log('Active:', true);+ expect(spy.mock.calls[0][1]).toBe(true);+ spy.mockRestore();+ });++ it('preserves null/undefined in production', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ SL.log('Value:', null);+ expect(spy.mock.calls[0][1]).toBeNull();+ spy.mockRestore();+ });++ it('redacts Error message but keeps name in production', () => {+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});+ SL.error('Failed:', new TypeError('secret details'));+ const secondArg = spy.mock.calls[0][1];+ expect(secondArg.name).toBe('TypeError');+ expect(secondArg.message).toBe('[redacted]');+ spy.mockRestore();+ });++ it('shows array structure but not contents in production', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ SL.log('Items:', [1, 2, 3]);+ expect(spy.mock.calls[0][1]).toBe('[Array(3)]');+ spy.mockRestore();+ });++ it('shows [Object] for objects in production', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ SL.log('Config:', { key: 'value' });+ expect(spy.mock.calls[0][1]).toBe('[Object]');+ spy.mockRestore();+ });++ it('suppresses debug messages entirely in production', () => {+ const spy = vi.spyOn(console, 'debug').mockImplementation(() => {});+ SL.debug('secret debug info');+ expect(spy).not.toHaveBeenCalled();+ spy.mockRestore();+ });+ });++ describe('log methods call correct console methods', () => {+ beforeEach(() => {+ SL.setProductionMode(false);+ });++ it('log → console.log', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ SL.log('test');+ expect(spy).toHaveBeenCalled();+ spy.mockRestore();+ });++ it('info → console.info', () => {+ const spy = vi.spyOn(console, 'info').mockImplementation(() => {});+ SL.info('test');+ expect(spy).toHaveBeenCalled();+ spy.mockRestore();+ });++ it('warn → console.warn', () => {+ const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ SL.warn('test');+ expect(spy).toHaveBeenCalled();+ spy.mockRestore();+ });++ it('error → console.error', () => {+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});+ SL.error('test');+ expect(spy).toHaveBeenCalled();+ spy.mockRestore();+ });+ });++ describe('production redaction invariants (fuzz)', () => {+ // Property-based test: in production mode, no string/number argument+ // after the first should ever appear verbatim in console output.+ // This is the most critical security property of SafeLogger — if+ // it ever regresses, user search queries / API responses leak.++ beforeEach(() => {+ SL.setProductionMode(true);+ });++ const generateRandomString = () => {+ const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%';+ const len = Math.floor(Math.random() * 30) + 5;+ let s = '';+ for (let i = 0; i < len; i++) {+ s += chars[Math.floor(Math.random() * chars.length)];+ }+ return s;+ };++ it('never leaks string arguments after the first (100 random inputs)', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ for (let i = 0; i < 100; i++) {+ const secret = generateRandomString();+ SL.log('Request:', secret);+ const loggedArgs = spy.mock.calls[spy.mock.calls.length - 1];+ // The static message should pass through+ expect(loggedArgs[0]).toBe('Request:');+ // The secret should NOT appear in any logged argument+ for (let j = 1; j < loggedArgs.length; j++) {+ expect(loggedArgs[j]).not.toBe(secret);+ expect(String(loggedArgs[j])).not.toContain(secret);+ }+ }+ spy.mockRestore();+ });++ it('never leaks number arguments after the first', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ for (let i = 0; i < 50; i++) {+ const secretId = Math.floor(Math.random() * 1e9);+ SL.log('User ID:', secretId);+ const loggedArgs = spy.mock.calls[spy.mock.calls.length - 1];+ for (let j = 1; j < loggedArgs.length; j++) {+ expect(loggedArgs[j]).not.toBe(secretId);+ }+ }+ spy.mockRestore();+ });++ it('never leaks object property values', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ for (let i = 0; i < 30; i++) {+ const secret = generateRandomString();+ SL.log('Data:', { token: secret, user: secret });+ const loggedArgs = spy.mock.calls[spy.mock.calls.length - 1];+ // The serialized representation should not contain the secret+ const serialized = JSON.stringify(loggedArgs);+ expect(serialized).not.toContain(secret);+ }+ spy.mockRestore();+ });++ it('never leaks array contents', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ for (let i = 0; i < 30; i++) {+ const secrets = [generateRandomString(), generateRandomString()];+ SL.log('Items:', secrets);+ const loggedArgs = spy.mock.calls[spy.mock.calls.length - 1];+ const serialized = JSON.stringify(loggedArgs);+ for (const secret of secrets) {+ expect(serialized).not.toContain(secret);+ }+ }+ spy.mockRestore();+ });++ it('never leaks Error message contents', () => {+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});+ for (let i = 0; i < 30; i++) {+ const secretMsg = generateRandomString();+ SL.error('Failed:', new Error(secretMsg));+ const loggedArgs = spy.mock.calls[spy.mock.calls.length - 1];+ const serialized = JSON.stringify(loggedArgs);+ expect(serialized).not.toContain(secretMsg);+ }+ spy.mockRestore();+ });+ });++ describe('edge cases', () => {+ it('handles zero arguments', () => {+ SL.setProductionMode(false);+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ SL.log();+ expect(spy).toHaveBeenCalledWith();+ spy.mockRestore();+ });++ it('redacts error-like objects in production', () => {+ SL.setProductionMode(true);+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ SL.log('Issue:', { message: 'secret', name: 'ApiError' });+ const arg = spy.mock.calls[0][1];+ expect(arg.name).toBe('ApiError');+ expect(arg.message).toBe('[redacted]');+ spy.mockRestore();+ });+ });+});diff --git a/tests/js/security/url-validator.test.js b/tests/js/security/url-validator.test.jsnew file mode 100644index 0000000000..e088d91db7--- /dev/null+++ b/tests/js/security/url-validator.test.js@@ -0,0 +1,121 @@+// url-validator.js attaches to window.URLValidator+import '@js/security/url-validator.js';++const { URLValidator } = window;++describe('URLValidator', () => {+ describe('isUnsafeScheme', () => {+ it('detects javascript: scheme', () => {+ expect(URLValidator.isUnsafeScheme('javascript:alert(1)')).toBe(true);+ });++ it('detects data: scheme', () => {+ expect(URLValidator.isUnsafeScheme('data:text/html,<h1>hi</h1>')).toBe(true);+ });++ it('is case-insensitive', () => {+ expect(URLValidator.isUnsafeScheme('JAVASCRIPT:void(0)')).toBe(true);+ });++ it('returns false for safe schemes', () => {+ expect(URLValidator.isUnsafeScheme('https://example.com')).toBe(false);+ });++ it('returns false for empty/null input', () => {+ expect(URLValidator.isUnsafeScheme('')).toBe(false);+ expect(URLValidator.isUnsafeScheme(null)).toBe(false);+ });+ });++ describe('isSafeUrl', () => {+ it('accepts https URLs', () => {+ expect(URLValidator.isSafeUrl('https://example.com')).toBe(true);+ });++ it('accepts http URLs', () => {+ expect(URLValidator.isSafeUrl('http://example.com')).toBe(true);+ });++ it('rejects javascript: URLs', () => {+ expect(URLValidator.isSafeUrl('javascript:alert(1)')).toBe(false);+ });++ it('rejects non-string input', () => {+ expect(URLValidator.isSafeUrl(null)).toBe(false);+ expect(URLValidator.isSafeUrl(123)).toBe(false);+ expect(URLValidator.isSafeUrl(undefined)).toBe(false);+ });++ it('handles fragment-only URLs based on option', () => {+ expect(URLValidator.isSafeUrl('#section', { allowFragments: true })).toBe(true);+ expect(URLValidator.isSafeUrl('#section', { allowFragments: false })).toBe(false);+ });++ it('rejects mailto by default', () => {+ expect(URLValidator.isSafeUrl('mailto:[email protected]')).toBe(false);+ });++ it('allows mailto when option is set', () => {+ expect(URLValidator.isSafeUrl('mailto:[email protected]', { allowMailto: true })).toBe(true);+ });++ it('validates trusted domains', () => {+ const opts = { trustedDomains: ['example.com'] };+ expect(URLValidator.isSafeUrl('https://example.com/page', opts)).toBe(true);+ expect(URLValidator.isSafeUrl('https://sub.example.com/page', opts)).toBe(true);+ expect(URLValidator.isSafeUrl('https://evil.com/page', opts)).toBe(false);+ });+ });++ describe('sanitizeUrl', () => {+ it('returns null for unsafe schemes', () => {+ expect(URLValidator.sanitizeUrl('javascript:alert(1)')).toBeNull();+ });++ it('adds default https scheme when missing', () => {+ expect(URLValidator.sanitizeUrl('example.com')).toBe('https://example.com');+ });++ it('preserves existing scheme', () => {+ expect(URLValidator.sanitizeUrl('http://example.com')).toBe('http://example.com');+ });++ it('returns null for empty input', () => {+ expect(URLValidator.sanitizeUrl('')).toBeNull();+ expect(URLValidator.sanitizeUrl(null)).toBeNull();+ });+ });++ describe('safeAssign', () => {+ it('allows internal paths starting with /', () => {+ const el = {};+ expect(URLValidator.safeAssign(el, 'href', '/settings')).toBe(true);+ expect(el.href).toBe('/settings');+ });++ it('allows fragment URLs', () => {+ const el = {};+ expect(URLValidator.safeAssign(el, 'href', '#top')).toBe(true);+ expect(el.href).toBe('#top');+ });++ it('allows blob URLs for downloads', () => {+ const el = {};+ const blobUrl = 'blob:http://localhost/abc-123';+ expect(URLValidator.safeAssign(el, 'href', blobUrl)).toBe(true);+ expect(el.href).toBe(blobUrl);+ });++ it('blocks unsafe external URLs', () => {+ const el = {};+ expect(URLValidator.safeAssign(el, 'href', 'javascript:alert(1)')).toBe(false);+ expect(el.href).toBeUndefined();+ });++ it('allows safe external URLs', () => {+ const el = {};+ expect(URLValidator.safeAssign(el, 'href', 'https://example.com')).toBe(true);+ expect(el.href).toBe('https://example.com');+ });+ });+});diff --git a/tests/js/security/xss-protection.test.js b/tests/js/security/xss-protection.test.jsnew file mode 100644index 0000000000..9e73e1a5c0--- /dev/null+++ b/tests/js/security/xss-protection.test.js@@ -0,0 +1,271 @@+/**+ * Tests for security/xss-protection.js+ *+ * Tests HTML escaping, sanitization, and safe DOM manipulation+ * functions that protect against XSS attacks.+ */++import '@js/security/xss-protection.js';++const { escapeHtml, escapeHtmlAttribute, sanitizeUserInput,+ safeSetInnerHTML, safeSetTextContent } = window;++describe('escapeHtml', () => {+ it('escapes ampersands', () => {+ expect(escapeHtml('a & b')).toBe('a & b');+ });++ it('escapes angle brackets', () => {+ expect(escapeHtml('<script>alert(1)</script>')).toBe(+ '<script>alert(1)</script>'+ );+ });++ it('escapes double quotes', () => {+ expect(escapeHtml('"hello"')).toBe('"hello"');+ });++ it('escapes single quotes', () => {+ expect(escapeHtml("it's")).toBe('it's');+ });++ it('escapes forward slashes', () => {+ expect(escapeHtml('a/b')).toBe('a/b');+ });++ it('returns empty string for null', () => {+ expect(escapeHtml(null)).toBe('');+ });++ it('returns empty string for undefined', () => {+ expect(escapeHtml(undefined)).toBe('');+ });++ it('converts non-strings to string first', () => {+ expect(escapeHtml(123)).toBe('123');+ expect(escapeHtml(true)).toBe('true');+ });++ it('handles strings with no special characters', () => {+ expect(escapeHtml('hello world')).toBe('hello world');+ });++ it('handles empty string', () => {+ expect(escapeHtml('')).toBe('');+ });++ it('escapes all dangerous characters together', () => {+ expect(escapeHtml('<img onerror="alert(\'xss\')" />')).toBe(+ '<img onerror="alert('xss')" />'+ );+ });+});++describe('escapeHtmlAttribute', () => {+ it('escapes double quotes for attribute context', () => {+ expect(escapeHtmlAttribute('value"with"quotes')).toContain('"');+ });++ it('escapes angle brackets', () => {+ expect(escapeHtmlAttribute('<tag>')).toContain('<');+ });++ it('converts non-strings', () => {+ expect(escapeHtmlAttribute(42)).toBe('42');+ });+});++describe('sanitizeUserInput', () => {+ it('returns empty string for null/undefined', () => {+ expect(sanitizeUserInput(null)).toBe('');+ expect(sanitizeUserInput(undefined)).toBe('');+ });++ it('trims whitespace by default', () => {+ const result = sanitizeUserInput(' hello ');+ expect(result).not.toMatch(/^\s/);+ expect(result).not.toMatch(/\s$/);+ });++ it('does not trim when option is false', () => {+ const result = sanitizeUserInput(' hello ', { trimWhitespace: false });+ // The result is escaped, so check it contains the text+ expect(result).toContain('hello');+ });++ it('enforces maxLength', () => {+ const long = 'a'.repeat(200);+ const result = sanitizeUserInput(long, { maxLength: 10 });+ // After escaping, the core content is truncated to 10 chars+ expect(result.length).toBeLessThanOrEqual(10);+ });++ it('normalizes line breaks', () => {+ const input = 'line1\r\nline2\rline3';+ const result = sanitizeUserInput(input, { allowLineBreaks: true });+ expect(result).not.toContain('\r');+ });++ it('escapes HTML by default (allowHtml=false)', () => {+ const result = sanitizeUserInput('<script>alert(1)</script>');+ expect(result).toContain('<');+ expect(result).not.toContain('<script>');+ });++ it('converts non-string input to string', () => {+ expect(sanitizeUserInput(42)).toBe('42');+ });+});++describe('safeSetInnerHTML', () => {+ it('does nothing when element is null', () => {+ expect(() => safeSetInnerHTML(null, 'content')).not.toThrow();+ });++ it('clears content when content is empty/falsy', () => {+ const el = document.createElement('div');+ el.textContent = 'existing';+ safeSetInnerHTML(el, '');+ expect(el.textContent).toBe('');+ });++ it('sets textContent when allowHtmlTags is false', () => {+ const el = document.createElement('div');+ safeSetInnerHTML(el, '<b>bold</b>', false);+ expect(el.textContent).toBe('<b>bold</b>');+ expect(el.innerHTML).not.toContain('<b>');+ });++ it('sets textContent when content is null', () => {+ const el = document.createElement('div');+ el.textContent = 'existing';+ safeSetInnerHTML(el, null);+ expect(el.textContent).toBe('');+ });+});++describe('safeSetTextContent', () => {+ it('does nothing when element is null', () => {+ expect(() => safeSetTextContent(null, 'content')).not.toThrow();+ });++ it('sets text content safely', () => {+ const el = document.createElement('div');+ safeSetTextContent(el, 'hello world');+ expect(el.textContent).toBe('hello world');+ });++ it('converts content to string', () => {+ const el = document.createElement('div');+ safeSetTextContent(el, 123);+ expect(el.textContent).toBe('123');+ });++ it('handles null content gracefully', () => {+ const el = document.createElement('div');+ safeSetTextContent(el, null);+ expect(el.textContent).toBe('');+ });++ it('handles undefined content gracefully', () => {+ const el = document.createElement('div');+ safeSetTextContent(el, undefined);+ expect(el.textContent).toBe('');+ });+});++describe('escapeHtml fuzz / property tests', () => {+ // The most critical security invariant: after escapeHtml, the result+ // should never contain raw <, >, or unescaped quotes that could break+ // out of an HTML context. We fuzz with random injection-like strings+ // to catch any escaping regression.++ const generatePayload = () => {+ const fragments = [+ '<script>', '</script>', '<img src=x onerror=alert(1)>',+ '"><svg/onload=', "'><iframe", ''', 'javascript:',+ '"', "'", '<', '>', '&', '/', '`', '${', 'data:text/html,',+ '<style>', '</style>', '</textarea>',+ ];+ // Build a random combination+ const len = Math.floor(Math.random() * 5) + 1;+ let payload = '';+ for (let i = 0; i < len; i++) {+ payload += fragments[Math.floor(Math.random() * fragments.length)];+ // Insert random characters between+ const noise = Math.floor(Math.random() * 5);+ for (let j = 0; j < noise; j++) {+ payload += String.fromCharCode(Math.floor(Math.random() * 95) + 32);+ }+ }+ return payload;+ };++ it('escaped output never contains raw < or > (200 random payloads)', () => {+ for (let i = 0; i < 200; i++) {+ const payload = generatePayload();+ const escaped = escapeHtml(payload);+ expect(escaped).not.toMatch(/</);+ expect(escaped).not.toMatch(/>/);+ }+ });++ it('escaped output never contains raw double quotes', () => {+ for (let i = 0; i < 200; i++) {+ const payload = generatePayload();+ const escaped = escapeHtml(payload);+ expect(escaped).not.toMatch(/"/);+ }+ });++ it('escaped output is parseable as text content (round-trips through DOM)', () => {+ // If escaping works, the escaped string parsed as innerHTML and read+ // back via textContent should equal the original input.+ const div = document.createElement('div');+ for (let i = 0; i < 100; i++) {+ const payload = generatePayload();+ const escaped = escapeHtml(payload);+ // eslint-disable-next-line no-unsanitized/property -- test code+ div.innerHTML = escaped;+ // textContent decodes the entities back to the original+ expect(div.textContent).toBe(payload);+ // And no script/element tags were created+ expect(div.children.length).toBe(0);+ }+ });++ it('escaped output never creates executable elements', () => {+ const div = document.createElement('div');+ // Specific known XSS vectors+ const vectors = [+ '<script>alert(1)</script>',+ '<img src=x onerror=alert(1)>',+ '<svg onload=alert(1)>',+ '"><script>alert(1)</script>',+ '<iframe src=javascript:alert(1)>',+ '<a href="javascript:alert(1)">x</a>',+ ];+ for (const vector of vectors) {+ // eslint-disable-next-line no-unsanitized/property -- test code+ div.innerHTML = escapeHtml(vector);+ // No element children should have been created+ expect(div.children.length).toBe(0);+ expect(div.querySelectorAll('script').length).toBe(0);+ expect(div.querySelectorAll('img').length).toBe(0);+ expect(div.querySelectorAll('svg').length).toBe(0);+ expect(div.querySelectorAll('iframe').length).toBe(0);+ }+ });++ it('idempotent: escaping an already-escaped string does not create XSS', () => {+ // Escaping twice should still be safe (no element creation)+ const div = document.createElement('div');+ for (let i = 0; i < 50; i++) {+ const payload = generatePayload();+ const escapedTwice = escapeHtml(escapeHtml(payload));+ // eslint-disable-next-line no-unsanitized/property -- test code+ div.innerHTML = escapedTwice;+ expect(div.children.length).toBe(0);+ }+ });+});diff --git a/tests/js/services/formatting.test.js b/tests/js/services/formatting.test.jsnew file mode 100644index 0000000000..3f20bef8cd--- /dev/null+++ b/tests/js/services/formatting.test.js@@ -0,0 +1,150 @@+/**+ * Tests for services/formatting.js+ *+ * Tests the formatting utility functions used for displaying+ * dates, durations, modes, and numbers throughout the UI.+ */++// Stub ResearchStates (used by formatStatus)+window.RESEARCH_STATUS = {+ IN_PROGRESS: 'in_progress',+ COMPLETED: 'completed',+ FAILED: 'failed',+ SUSPENDED: 'suspended',+ CANCELLED: 'cancelled',+ QUEUED: 'queued',+ PENDING: 'pending',+ ERROR: 'error',+};+window.RESEARCH_TERMINAL_STATES = new Set([+ 'completed', 'suspended', 'failed', 'error', 'cancelled',+]);++// Load constants first (provides ResearchStates), then formatting+import '@js/config/constants.js';+import '@js/services/formatting.js';++const fmt = window.formatting;++describe('formatting', () => {+ describe('formatMode', () => {+ it('maps quick to Quick Summary', () => {+ expect(fmt.formatMode('quick')).toBe('Quick Summary');+ });++ it('maps detailed to Detailed Report', () => {+ expect(fmt.formatMode('detailed')).toBe('Detailed Report');+ });++ it('capitalizes unknown modes', () => {+ expect(fmt.formatMode('custom')).toBe('Custom');+ });+ });++ describe('formatDate', () => {+ it('returns Unknown for falsy input', () => {+ expect(fmt.formatDate(null)).toBe('Unknown');+ expect(fmt.formatDate('')).toBe('Unknown');+ expect(fmt.formatDate(undefined)).toBe('Unknown');+ });++ it('formats a valid ISO date', () => {+ const result = fmt.formatDate('2025-01-15T10:30:00Z');+ // Should contain month, day, and year+ expect(result).toMatch(/Jan/);+ expect(result).toMatch(/15/);+ expect(result).toMatch(/2025/);+ });++ it('appends duration in minutes and seconds', () => {+ const result = fmt.formatDate('2025-01-15T10:30:00Z', 125);+ expect(result).toContain('2m 5s');+ });++ it('appends duration in seconds only when < 60s', () => {+ const result = fmt.formatDate('2025-01-15T10:30:00Z', 45);+ expect(result).toContain('45s');+ expect(result).not.toContain('m');+ });++ it('does not append duration when null', () => {+ const result = fmt.formatDate('2025-01-15T10:30:00Z', null);+ expect(result).not.toContain('s)');+ });+ });++ describe('formatDuration', () => {+ it('returns Unknown for falsy input', () => {+ expect(fmt.formatDuration(null)).toBe('Unknown');+ expect(fmt.formatDuration(undefined)).toBe('Unknown');+ expect(fmt.formatDuration(0)).toBe('Unknown');+ });++ it('returns Unknown for NaN', () => {+ expect(fmt.formatDuration(NaN)).toBe('Unknown');+ });++ it('formats seconds only when < 60', () => {+ expect(fmt.formatDuration(45)).toBe('45s');+ });++ it('formats minutes and seconds', () => {+ expect(fmt.formatDuration(125)).toBe('2m 5s');+ });++ it('handles exact minutes', () => {+ expect(fmt.formatDuration(120)).toBe('2m 0s');+ });++ it('floors fractional seconds', () => {+ expect(fmt.formatDuration(45.7)).toBe('45s');+ });+ });++ describe('capitalizeFirstLetter', () => {+ it('capitalizes lowercase string', () => {+ expect(fmt.capitalizeFirstLetter('hello')).toBe('Hello');+ });++ it('returns empty string for falsy input', () => {+ expect(fmt.capitalizeFirstLetter('')).toBe('');+ expect(fmt.capitalizeFirstLetter(null)).toBe('');+ expect(fmt.capitalizeFirstLetter(undefined)).toBe('');+ });++ it('preserves already capitalized strings', () => {+ expect(fmt.capitalizeFirstLetter('Hello')).toBe('Hello');+ });++ it('handles single character', () => {+ expect(fmt.capitalizeFirstLetter('a')).toBe('A');+ });+ });++ describe('formatNumber', () => {+ it('returns "0" for null/undefined', () => {+ expect(fmt.formatNumber(null)).toBe('0');+ expect(fmt.formatNumber(undefined)).toBe('0');+ });++ it('returns number as-is when < 1000', () => {+ expect(fmt.formatNumber(999)).toBe('999');+ });++ it('adds comma separators for thousands', () => {+ expect(fmt.formatNumber(1000)).toBe('1,000');+ expect(fmt.formatNumber(1234567)).toBe('1,234,567');+ });++ it('handles zero', () => {+ expect(fmt.formatNumber(0)).toBe('0');+ });+ });++ describe('formatStatus', () => {+ it('delegates to ResearchStates.formatStatus', () => {+ expect(fmt.formatStatus('completed')).toBe('Completed');+ expect(fmt.formatStatus('in_progress')).toBe('In Progress');+ });+ });+});diff --git a/tests/js/services/help.test.js b/tests/js/services/help.test.jsnew file mode 100644index 0000000000..c3de8feda6--- /dev/null+++ b/tests/js/services/help.test.js@@ -0,0 +1,150 @@+/**+ * Tests for services/help.js+ *+ * Tests the HelpService for collapsible help panels:+ * togglePanel, dismissPanel, isPanelDismissed, expandAll, collapseAll, reset.+ */++let HelpService;++beforeAll(async () => {+ // Stub fetch — initPanelStates calls /settings/api/bulk on init+ globalThis.fetch = vi.fn(() =>+ Promise.resolve({+ ok: true,+ json: () => Promise.resolve({ success: true, settings: {} }),+ })+ );+ window.api = { getCsrfToken: () => 'test-token' };+ window.ui = { showMessage: vi.fn() };++ await import('@js/services/help.js');+ HelpService = window.HelpService;+});++afterEach(() => {+ // Clean up any panels created in tests+ document.querySelectorAll('.ldr-help-panel').forEach(p => p.remove());+ localStorage.clear();+});++describe('HelpService', () => {+ function createPanel(id, collapsed = false) {+ const panel = document.createElement('div');+ panel.className = 'ldr-help-panel' + (collapsed ? ' collapsed' : '');+ panel.id = 'help-panel-' + id;+ panel.setAttribute('data-panel-id', id);++ const header = document.createElement('div');+ header.className = 'ldr-help-panel-header';+ header.setAttribute('aria-expanded', collapsed ? 'false' : 'true');+ panel.appendChild(header);++ document.body.appendChild(panel);+ return panel;+ }++ describe('togglePanel', () => {+ it('toggles the collapsed class', () => {+ const panel = createPanel('test1');+ expect(panel.classList.contains('collapsed')).toBe(false);++ HelpService.togglePanel('test1');+ expect(panel.classList.contains('collapsed')).toBe(true);++ HelpService.togglePanel('test1');+ expect(panel.classList.contains('collapsed')).toBe(false);+ });++ it('updates aria-expanded on header', () => {+ const panel = createPanel('test2');+ const header = panel.querySelector('.ldr-help-panel-header');++ HelpService.togglePanel('test2');+ expect(header.getAttribute('aria-expanded')).toBe('false');++ HelpService.togglePanel('test2');+ expect(header.getAttribute('aria-expanded')).toBe('true');+ });++ it('persists collapsed state to localStorage', () => {+ createPanel('test3');+ HelpService.togglePanel('test3');+ expect(localStorage.getItem('ldr_panel_collapsed_test3')).toBe('true');++ HelpService.togglePanel('test3');+ expect(localStorage.getItem('ldr_panel_collapsed_test3')).toBe('false');+ });++ it('does nothing for non-existent panel', () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ expect(() => HelpService.togglePanel('nonexistent')).not.toThrow();+ warnSpy.mockRestore();+ });+ });++ describe('expandAll', () => {+ it('removes collapsed class from all panels', () => {+ const p1 = createPanel('e1', true);+ const p2 = createPanel('e2', true);+ const p3 = createPanel('e3', false);++ HelpService.expandAll();++ expect(p1.classList.contains('collapsed')).toBe(false);+ expect(p2.classList.contains('collapsed')).toBe(false);+ expect(p3.classList.contains('collapsed')).toBe(false);+ });++ it('updates aria-expanded to true on all expanded panels', () => {+ const p = createPanel('e4', true);+ HelpService.expandAll();+ const header = p.querySelector('.ldr-help-panel-header');+ expect(header.getAttribute('aria-expanded')).toBe('true');+ });+ });++ describe('collapseAll', () => {+ it('adds collapsed class to all panels', () => {+ const p1 = createPanel('c1', false);+ const p2 = createPanel('c2', false);++ HelpService.collapseAll();++ expect(p1.classList.contains('collapsed')).toBe(true);+ expect(p2.classList.contains('collapsed')).toBe(true);+ });++ it('updates aria-expanded to false', () => {+ const p = createPanel('c3', false);+ HelpService.collapseAll();+ const header = p.querySelector('.ldr-help-panel-header');+ expect(header.getAttribute('aria-expanded')).toBe('false');+ });++ it('does not affect already-collapsed panels', () => {+ const p = createPanel('c4', true);+ HelpService.collapseAll();+ expect(p.classList.contains('collapsed')).toBe(true);+ });+ });++ describe('isPanelDismissed', () => {+ it('returns false for unknown panels', () => {+ expect(HelpService.isPanelDismissed('unknown')).toBe(false);+ });+ });++ describe('dismissPanel', () => {+ it('hides the panel and marks it dismissed', async () => {+ const panel = createPanel('dismiss1');+ globalThis.fetch = vi.fn(() =>+ Promise.resolve({ ok: true, status: 200 })+ );++ await HelpService.dismissPanel('dismiss1');+ expect(panel.style.display).toBe('none');+ expect(HelpService.isPanelDismissed('dismiss1')).toBe(true);+ });+ });+});diff --git a/tests/js/services/keyboard.test.js b/tests/js/services/keyboard.test.jsnew file mode 100644index 0000000000..7db75a852b--- /dev/null+++ b/tests/js/services/keyboard.test.js@@ -0,0 +1,117 @@+/**+ * Tests for services/keyboard.js+ *+ * Tests the keyboard shortcut matching logic and service API.+ * We can't test the full initialization (which binds to document),+ * but we can test the shortcut matching and public API.+ */++// Stub URLS needed by keyboard.js handlers+window.URLS = {+ PAGES: {+ HOME: '/',+ HISTORY: '/history/',+ METRICS: '/metrics/',+ SETTINGS: '/settings/',+ }+};++import '@js/services/keyboard.js';++const KS = window.KeyboardService;++describe('KeyboardService', () => {+ describe('shortcuts registry invariants', () => {+ it('every registered shortcut has a callable handler', () => {+ // Catches accidental refactors that drop the handler field.+ const shortcuts = KS.shortcuts();+ for (const [name, shortcut] of Object.entries(shortcuts)) {+ expect(shortcut.handler, `${name} missing handler`).toBeTypeOf('function');+ expect(shortcut.keys, `${name} missing keys`).toBeInstanceOf(Array);+ expect(shortcut.keys.length, `${name} has empty keys`).toBeGreaterThan(0);+ }+ });+ });++ describe('addShortcut / removeShortcut', () => {+ afterEach(() => {+ KS.removeShortcut('testShortcut');+ });++ it('adds a custom shortcut', () => {+ KS.addShortcut('testShortcut', {+ keys: ['ctrl+t'],+ description: 'Test shortcut',+ handler: () => {}+ });+ const shortcuts = KS.shortcuts();+ expect(shortcuts.testShortcut).toBeDefined();+ expect(shortcuts.testShortcut.keys).toEqual(['ctrl+t']);+ });++ it('removes a custom shortcut', () => {+ KS.addShortcut('testShortcut', {+ keys: ['ctrl+t'],+ description: 'Test',+ handler: () => {}+ });+ KS.removeShortcut('testShortcut');+ const shortcuts = KS.shortcuts();+ expect(shortcuts.testShortcut).toBeUndefined();+ });+ });++ describe('keyboard event handling', () => {+ it('Escape key triggers newSearch shortcut', () => {+ // The shortcut sets window.location.href, which we can spy on+ const originalHref = window.location.href;++ // Create a keydown event for Escape+ const event = new KeyboardEvent('keydown', {+ key: 'Escape',+ code: 'Escape',+ bubbles: true,+ });++ // We can verify the event doesn't throw+ expect(() => document.dispatchEvent(event)).not.toThrow();+ });++ it('ignores shortcuts when typing in input fields', () => {+ const input = document.createElement('input');+ input.type = 'text';+ document.body.appendChild(input);+ input.focus();++ const event = new KeyboardEvent('keydown', {+ key: 'Escape',+ code: 'Escape',+ bubbles: true,+ });++ // Should not throw or cause navigation when typing+ expect(() => input.dispatchEvent(event)).not.toThrow();+ input.remove();+ });++ it('allows Ctrl+Shift navigation shortcuts even in input', () => {+ const input = document.createElement('input');+ input.type = 'text';+ document.body.appendChild(input);+ input.focus();++ const event = new KeyboardEvent('keydown', {+ key: '1',+ code: 'Digit1',+ ctrlKey: true,+ shiftKey: true,+ bubbles: true,+ });++ // Should not throw+ expect(() => input.dispatchEvent(event)).not.toThrow();+ input.remove();+ });+ });++});diff --git a/tests/js/services/theme.test.js b/tests/js/services/theme.test.jsnew file mode 100644index 0000000000..faee2db1ac--- /dev/null+++ b/tests/js/services/theme.test.js@@ -0,0 +1,159 @@+/**+ * Tests for services/theme.js+ *+ * Tests theme resolution, validation, cycling, and storage.+ * Network calls (server sync) are not tested here as they+ * require a running backend.+ */++// Theme metadata must be set BEFORE the module IIFE runs.+// ES module imports are hoisted, so we use dynamic import in beforeAll.++let theme;++beforeAll(async () => {+ // Set up theme metadata before loading the module+ window.LDR_THEME_METADATA = {+ 'hashed': { label: 'Hashed', icon: 'fa-hashtag', group: 'core' },+ 'light': { label: 'Light', icon: 'fa-sun', group: 'core' },+ 'sepia': { label: 'Sepia', icon: 'fa-book', group: 'research' },+ 'nord': { label: 'Nord', icon: 'fa-snowflake', group: 'dev' },+ 'dracula': { label: 'Dracula', icon: 'fa-ghost', group: 'dev' },+ 'system': { label: 'System', icon: 'fa-desktop', group: 'system' },+ };++ // Stub fetch for server sync calls+ globalThis.fetch = vi.fn(() =>+ Promise.resolve({ ok: false, status: 404, json: () => Promise.resolve({}) })+ );++ // Stub api for CSRF+ window.api = { getCsrfToken: () => '' };++ await import('@js/services/theme.js');+ theme = window.themeService;+});++describe('themeService', () => {+ afterEach(() => {+ localStorage.clear();+ });++ describe('VALID_THEMES is derived from injected metadata', () => {+ it('contains every key from window.LDR_THEME_METADATA', () => {+ // Catches a regression where the derivation is removed/hardcoded.+ const metadataKeys = Object.keys(window.LDR_THEME_METADATA);+ for (const key of metadataKeys) {+ expect(theme.VALID_THEMES).toContain(key);+ }+ });+ });++ describe('getEffectiveTheme', () => {+ it('resolves system to sepia when prefers-color-scheme is light', () => {+ // happy-dom matchMedia returns false for dark mode by default+ expect(theme.getEffectiveTheme('system')).toBe('sepia');+ });++ it('returns the theme itself for non-system themes', () => {+ expect(theme.getEffectiveTheme('hashed')).toBe('hashed');+ expect(theme.getEffectiveTheme('light')).toBe('light');+ expect(theme.getEffectiveTheme('nord')).toBe('nord');+ });+ });++ describe('getCurrentTheme / setTheme', () => {+ it('defaults to system when no theme stored', () => {+ localStorage.clear();+ expect(theme.getCurrentTheme()).toBe('system');+ });++ it('stores and retrieves theme', () => {+ theme.setTheme('nord', false);+ expect(theme.getCurrentTheme()).toBe('nord');+ });++ it('falls back to hashed for invalid theme', () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ theme.setTheme('nonexistent-theme', false);+ expect(theme.getCurrentTheme()).toBe('hashed');+ warnSpy.mockRestore();+ });+ });++ describe('applyTheme', () => {+ it('sets data-theme attribute on documentElement', () => {+ theme.applyTheme('nord');+ expect(document.documentElement.getAttribute('data-theme')).toBe('nord');+ });++ it('resolves system theme before applying', () => {+ theme.applyTheme('system');+ const applied = document.documentElement.getAttribute('data-theme');+ expect(['sepia', 'hashed']).toContain(applied);+ });++ it('dispatches themechange event', () => {+ const handler = vi.fn();+ window.addEventListener('themechange', handler);+ theme.applyTheme('light');+ expect(handler).toHaveBeenCalledTimes(1);+ expect(handler.mock.calls[0][0].detail.theme).toBe('light');+ window.removeEventListener('themechange', handler);+ });+ });++ describe('cycleTheme', () => {+ it('cycles through THEME_CYCLE order', () => {+ theme.setTheme('hashed', false);+ const next = theme.cycleTheme();+ expect(next).toBe('light');+ });++ it('wraps around to first theme after last', () => {+ theme.setTheme('dracula', false);+ const next = theme.cycleTheme();+ expect(next).toBe('hashed');+ });++ it('starts from beginning when current theme is not in cycle', () => {+ theme.setTheme('sepia', false);+ const next = theme.cycleTheme();+ // sepia is not in cycle, index=-1 → becomes 0 → 'hashed'+ expect(next).toBe('hashed');+ });+ });++ describe('clearTheme', () => {+ it('removes theme from localStorage', () => {+ theme.setTheme('nord', false);+ expect(theme.getCurrentTheme()).toBe('nord');+ theme.clearTheme();+ expect(theme.getCurrentTheme()).toBe('system');+ });+ });++ describe('clearAllThemes', () => {+ it('removes all theme keys from localStorage', () => {+ theme.setTheme('nord', false);+ localStorage.setItem('ldr-theme-user2', 'light');+ theme.clearAllThemes();+ expect(localStorage.getItem('ldr-theme-user2')).toBeNull();+ });+ });++ describe('populateThemeDropdown', () => {+ it('populates a select element with theme options', () => {+ const select = document.createElement('select');+ theme.populateThemeDropdown(select);+ const optgroups = select.querySelectorAll('optgroup');+ expect(optgroups.length).toBeGreaterThan(0);+ const options = select.querySelectorAll('option');+ expect(options.length).toBe(Object.keys(window.LDR_THEME_METADATA).length);+ });++ it('does nothing when element is null', () => {+ expect(() => theme.populateThemeDropdown(null)).not.toThrow();+ });+ });+});diff --git a/tests/js/services/ui.test.js b/tests/js/services/ui.test.jsnew file mode 100644index 0000000000..0012b06568--- /dev/null+++ b/tests/js/services/ui.test.js@@ -0,0 +1,275 @@+/**+ * Tests for services/ui.js+ *+ * Tests UI utility functions: progress bars, spinners, error display,+ * inline errors, escapeHtmlFallback, and notification system.+ */++import '@js/security/xss-protection.js';+import '@js/services/ui.js';++const ui = window.ui;++describe('ui service', () => {+ describe('updateProgressBar', () => {+ let fill, pct;++ beforeEach(() => {+ fill = document.createElement('div');+ fill.id = 'test-fill';+ pct = document.createElement('span');+ pct.id = 'test-pct';+ document.body.appendChild(fill);+ document.body.appendChild(pct);+ });++ afterEach(() => {+ fill.remove();+ pct.remove();+ });++ it('sets width and text for percentage', () => {+ ui.updateProgressBar(fill, pct, 42);+ expect(fill.style.width).toBe('42%');+ expect(pct.textContent).toBe('42%');+ });++ it('clamps percentage to 0-100', () => {+ ui.updateProgressBar(fill, pct, -10);+ expect(fill.style.width).toBe('0%');+ expect(pct.textContent).toBe('0%');++ ui.updateProgressBar(fill, pct, 150);+ expect(fill.style.width).toBe('100%');+ expect(pct.textContent).toBe('100%');+ });++ it('handles null/undefined percentage as 0', () => {+ ui.updateProgressBar(fill, pct, null);+ expect(fill.style.width).toBe('0%');+ });++ it('adds ldr-complete class at 100%', () => {+ ui.updateProgressBar(fill, pct, 100);+ expect(fill.classList.contains('ldr-complete')).toBe(true);+ });++ it('removes ldr-complete class when below 100%', () => {+ fill.classList.add('ldr-complete');+ ui.updateProgressBar(fill, pct, 50);+ expect(fill.classList.contains('ldr-complete')).toBe(false);+ });++ it('accepts string IDs instead of elements', () => {+ ui.updateProgressBar('test-fill', 'test-pct', 75);+ expect(fill.style.width).toBe('75%');+ expect(pct.textContent).toBe('75%');+ });++ it('rounds percentage text', () => {+ ui.updateProgressBar(fill, pct, 33.7);+ expect(pct.textContent).toBe('34%');+ });+ });++ describe('showSpinner / hideSpinner', () => {+ let container;++ beforeEach(() => {+ container = document.createElement('div');+ container.id = 'spinner-container';+ document.body.appendChild(container);+ });++ afterEach(() => {+ container.remove();+ });++ it('creates a spinner element in the container', () => {+ ui.showSpinner(container, 'Loading data...');+ expect(container.querySelector('.ldr-loading-spinner')).not.toBeNull();+ });++ it('displays the message text', () => {+ ui.showSpinner(container, 'Please wait');+ expect(container.textContent).toContain('Please wait');+ });++ it('escapes HTML in the message', () => {+ ui.showSpinner(container, '<script>alert(1)</script>');+ expect(container.innerHTML).not.toContain('<script>');+ });++ it('hideSpinner removes the spinner', () => {+ ui.showSpinner(container);+ expect(container.querySelector('.ldr-loading-spinner')).not.toBeNull();+ ui.hideSpinner(container);+ expect(container.querySelector('.ldr-loading-spinner')).toBeNull();+ });++ it('hideSpinner does nothing when no spinner exists', () => {+ expect(() => ui.hideSpinner(container)).not.toThrow();+ });++ it('accepts string IDs', () => {+ ui.showSpinner('spinner-container', 'Test');+ expect(container.querySelector('.ldr-loading-spinner')).not.toBeNull();+ ui.hideSpinner('spinner-container');+ expect(container.querySelector('.ldr-loading-spinner')).toBeNull();+ });+ });++ describe('showError', () => {+ let container;++ beforeEach(() => {+ container = document.createElement('div');+ container.id = 'error-container';+ document.body.appendChild(container);+ });++ afterEach(() => {+ container.remove();+ });++ it('shows error message in container', () => {+ ui.showError(container, 'Something went wrong');+ expect(container.textContent).toContain('Something went wrong');+ });++ it('escapes HTML in error message', () => {+ ui.showError(container, '<img onerror="xss">');+ expect(container.innerHTML).not.toContain('<img');+ });++ it('creates error element with icon', () => {+ ui.showError(container, 'Error');+ expect(container.querySelector('.ldr-error-message')).not.toBeNull();+ expect(container.querySelector('.fa-exclamation-circle')).not.toBeNull();+ });+ });++ describe('showInlineError / clearInlineError', () => {+ let container;++ beforeEach(() => {+ container = document.createElement('div');+ container.id = 'inline-error-container';+ document.body.appendChild(container);+ });++ afterEach(() => {+ container.remove();+ });++ it('creates an inline error element', () => {+ const el = ui.showInlineError(container, 'Field is required');+ expect(el).not.toBeNull();+ expect(el.classList.contains('ldr-inline-error')).toBe(true);+ expect(el.textContent).toContain('Field is required');+ });++ it('sets role="alert" for accessibility', () => {+ const el = ui.showInlineError(container, 'Error');+ expect(el.getAttribute('role')).toBe('alert');+ });++ it('adds dismiss button by default', () => {+ const el = ui.showInlineError(container, 'Error');+ const closeBtn = el.querySelector('.ldr-inline-error-close');+ expect(closeBtn).not.toBeNull();+ expect(closeBtn.getAttribute('aria-label')).toBe('Dismiss error');+ });++ it('dismiss button removes error', () => {+ const el = ui.showInlineError(container, 'Error');+ const closeBtn = el.querySelector('.ldr-inline-error-close');+ closeBtn.click();+ expect(container.querySelector('.ldr-inline-error')).toBeNull();+ });++ it('replaces existing inline error', () => {+ ui.showInlineError(container, 'First error');+ ui.showInlineError(container, 'Second error');+ const errors = container.querySelectorAll('.ldr-inline-error');+ expect(errors.length).toBe(1);+ expect(errors[0].textContent).toContain('Second error');+ });++ it('clearInlineError removes all errors', () => {+ ui.showInlineError(container, 'Error 1');+ ui.clearInlineError(container);+ expect(container.querySelector('.ldr-inline-error')).toBeNull();+ });++ it('returns null for non-existent container', () => {+ expect(ui.showInlineError('#nonexistent', 'Error')).toBeNull();+ });++ it('accepts string ID for container', () => {+ const el = ui.showInlineError('inline-error-container', 'Test');+ expect(el).not.toBeNull();+ });++ it('uses textContent (not innerHTML) for message', () => {+ const el = ui.showInlineError(container, '<script>xss</script>');+ const span = el.querySelector('span');+ expect(span.textContent).toBe('<script>xss</script>');+ expect(span.innerHTML).not.toContain('<script>');+ });+ });++ describe('showMessage', () => {+ afterEach(() => {+ const banner = document.getElementById('notification-banner');+ if (banner) banner.remove();+ });++ it('creates a notification banner', () => {+ ui.showMessage('Saved!', 'success');+ const banner = document.getElementById('notification-banner');+ expect(banner).not.toBeNull();+ expect(banner.textContent).toContain('Saved!');+ });++ it('sets role="alert" for error/warning types', () => {+ ui.showMessage('Error occurred', 'error');+ const banner = document.getElementById('notification-banner');+ expect(banner.getAttribute('role')).toBe('alert');+ });++ it('sets role="status" for success/info types', () => {+ ui.showMessage('Done', 'success');+ const banner = document.getElementById('notification-banner');+ expect(banner.getAttribute('role')).toBe('status');+ });++ it('escapes HTML in message', () => {+ ui.showMessage('<img src=x onerror=alert(1)>', 'info');+ const banner = document.getElementById('notification-banner');+ expect(banner.innerHTML).not.toContain('<img');+ });++ it('replaces previous banner', () => {+ ui.showMessage('First', 'success');+ ui.showMessage('Second', 'info');+ const banners = document.querySelectorAll('#notification-banner');+ expect(banners.length).toBe(1);+ expect(banners[0].textContent).toContain('Second');+ });+ });+});++describe('renderMarkdown', () => {+ it('returns warning HTML for null/empty input', () => {+ const result = ui.renderMarkdown(null);+ expect(result).toContain('No content available');+ });++ it('returns plaintext fallback when marked is unavailable', () => {+ // happy-dom doesn't have `marked` loaded+ const result = ui.renderMarkdown('# Hello World');+ // Should escape HTML and show as plaintext+ expect(result).toContain('Hello World');+ });+});diff --git a/tests/js/setup.js b/tests/js/setup.jsnew file mode 100644index 0000000000..a1bd5f5591--- /dev/null+++ b/tests/js/setup.js@@ -0,0 +1,15 @@+/**+ * Global test setup for Vitest + happy-dom+ *+ * Stubs browser globals that the app code expects to exist+ * (e.g. SafeLogger, which is loaded as a <script> tag in production).+ */++// Minimal SafeLogger stub — tests can spy on these via vi.spyOn()+globalThis.SafeLogger = {+ log: () => {},+ warn: () => {},+ error: () => {},+ info: () => {},+ debug: () => {},+};diff --git a/tests/js/utils/form-validation.test.js b/tests/js/utils/form-validation.test.jsnew file mode 100644index 0000000000..3747a3bc4b--- /dev/null+++ b/tests/js/utils/form-validation.test.js@@ -0,0 +1,288 @@+/**+ * Tests for utils/form-validation.js+ *+ * Tests the FormValidator class and built-in validator functions+ * used for inline form validation with ARIA support.+ */++import '@js/utils/form-validation.js';++const FormValidator = window.FormValidator;+const validators = window.formValidators;++describe('FormValidator', () => {+ let form;+ let input;+ let validator;++ beforeEach(() => {+ form = document.createElement('form');+ input = document.createElement('input');+ input.type = 'text';+ input.id = 'test-field';+ form.appendChild(input);+ document.body.appendChild(form);+ validator = new FormValidator();+ });++ afterEach(() => {+ document.body.removeChild(form);+ });++ describe('addValidation', () => {+ it('creates an error element next to the field', () => {+ validator.addValidation(input, () => null);+ const errorEl = document.getElementById('test-field-error');+ expect(errorEl).not.toBeNull();+ expect(errorEl.className).toBe('ldr-field-error');+ });++ it('sets aria-describedby on the field', () => {+ validator.addValidation(input, () => null);+ expect(input.getAttribute('aria-describedby')).toContain('test-field-error');+ });++ it('sets aria-live on error element', () => {+ validator.addValidation(input, () => null);+ const errorEl = document.getElementById('test-field-error');+ expect(errorEl.getAttribute('aria-live')).toBe('polite');+ });++ it('accepts selector string instead of element', () => {+ validator.addValidation('#test-field', () => null);+ const errorEl = document.getElementById('test-field-error');+ expect(errorEl).not.toBeNull();+ });++ it('does nothing for non-existent selector', () => {+ expect(() => {+ validator.addValidation('#nonexistent', () => null);+ }).not.toThrow();+ });++ it('generates an id for fields without one', () => {+ const noIdInput = document.createElement('input');+ noIdInput.type = 'text';+ form.appendChild(noIdInput);+ validator.addValidation(noIdInput, () => null);+ expect(noIdInput.id).toMatch(/^form-field-/);+ });+ });++ describe('validateField', () => {+ it('returns true when validator returns null (valid)', () => {+ validator.addValidation(input, () => null);+ expect(validator.validateField(input)).toBe(true);+ });++ it('returns false when validator returns error message', () => {+ validator.addValidation(input, () => 'Error!');+ expect(validator.validateField(input)).toBe(false);+ });++ it('adds ldr-field-invalid class on error', () => {+ validator.addValidation(input, () => 'Error!');+ validator.validateField(input);+ expect(input.classList.contains('ldr-field-invalid')).toBe(true);+ });++ it('sets aria-invalid on error', () => {+ validator.addValidation(input, () => 'Error!');+ validator.validateField(input);+ expect(input.getAttribute('aria-invalid')).toBe('true');+ });++ it('displays error message in error element', () => {+ validator.addValidation(input, () => 'Field is required');+ validator.validateField(input);+ const errorEl = document.getElementById('test-field-error');+ expect(errorEl.textContent).toBe('Field is required');+ expect(errorEl.style.display).toBe('block');+ });++ it('clears error state when field becomes valid', () => {+ validator.addValidation(input, (val) => val ? null : 'Required');+ input.value = '';+ validator.validateField(input);+ expect(input.classList.contains('ldr-field-invalid')).toBe(true);++ input.value = 'filled';+ validator.validateField(input);+ expect(input.classList.contains('ldr-field-invalid')).toBe(false);+ expect(input.hasAttribute('aria-invalid')).toBe(false);+ });++ it('returns true for unregistered elements', () => {+ const unknownInput = document.createElement('input');+ expect(validator.validateField(unknownInput)).toBe(true);+ });+ });++ describe('validateAll', () => {+ it('returns true when all fields are valid', () => {+ const input2 = document.createElement('input');+ input2.id = 'field-2';+ form.appendChild(input2);++ validator.addValidation(input, () => null);+ validator.addValidation(input2, () => null);++ expect(validator.validateAll()).toBe(true);+ });++ it('returns false when any field is invalid', () => {+ const input2 = document.createElement('input');+ input2.id = 'field-2';+ form.appendChild(input2);++ validator.addValidation(input, () => null);+ validator.addValidation(input2, () => 'Error');++ expect(validator.validateAll()).toBe(false);+ });++ it('validates all fields (not short-circuit)', () => {+ const input2 = document.createElement('input');+ input2.id = 'field-2';+ form.appendChild(input2);++ validator.addValidation(input, () => 'Error 1');+ validator.addValidation(input2, () => 'Error 2');++ validator.validateAll();++ // Both should show errors+ expect(input.classList.contains('ldr-field-invalid')).toBe(true);+ expect(input2.classList.contains('ldr-field-invalid')).toBe(true);+ });+ });++ describe('clearErrors', () => {+ it('removes error classes and messages from all fields', () => {+ validator.addValidation(input, () => 'Error');+ validator.validateField(input);+ expect(input.classList.contains('ldr-field-invalid')).toBe(true);++ validator.clearErrors();+ expect(input.classList.contains('ldr-field-invalid')).toBe(false);+ expect(input.hasAttribute('aria-invalid')).toBe(false);+ const errorEl = document.getElementById('test-field-error');+ expect(errorEl.textContent).toBe('');+ expect(errorEl.style.display).toBe('none');+ });+ });++ describe('showError', () => {+ it('shows custom error on a field', () => {+ validator.addValidation(input, () => null);+ validator.showError(input, 'Custom error');+ expect(input.classList.contains('ldr-field-invalid')).toBe(true);+ expect(input.getAttribute('aria-invalid')).toBe('true');+ const errorEl = document.getElementById('test-field-error');+ expect(errorEl.textContent).toBe('Custom error');+ });++ it('accepts selector string', () => {+ validator.addValidation(input, () => null);+ validator.showError('#test-field', 'Custom error');+ expect(input.classList.contains('ldr-field-invalid')).toBe(true);+ });++ it('does nothing for non-existent selector', () => {+ expect(() => {+ validator.showError('#nonexistent', 'Error');+ }).not.toThrow();+ });+ });+});++describe('Built-in validators', () => {+ describe('required', () => {+ const required = validators.required();++ it('returns null for non-empty value', () => {+ expect(required('hello')).toBeNull();+ });++ it('returns error for empty string', () => {+ expect(required('')).toBe('This field is required');+ });++ it('returns error for whitespace-only string', () => {+ expect(required(' ')).toBe('This field is required');+ });++ it('returns error for null/undefined', () => {+ expect(required(null)).toBe('This field is required');+ expect(required(undefined)).toBe('This field is required');+ });++ it('accepts custom message', () => {+ const custom = validators.required('Please fill this in');+ expect(custom('')).toBe('Please fill this in');+ });+ });++ describe('minLength', () => {+ const minLen = validators.minLength(3);++ it('returns null for values meeting minimum', () => {+ expect(minLen('abc')).toBeNull();+ expect(minLen('abcd')).toBeNull();+ });++ it('returns error for short values', () => {+ expect(minLen('ab')).toBe('Must be at least 3 characters');+ });++ it('returns null for empty value (let required handle it)', () => {+ expect(minLen('')).toBeNull();+ expect(minLen(null)).toBeNull();+ });++ it('accepts custom message', () => {+ const custom = validators.minLength(5, 'Too short!');+ expect(custom('abc')).toBe('Too short!');+ });+ });++ describe('maxLength', () => {+ const maxLen = validators.maxLength(5);++ it('returns null for values within limit', () => {+ expect(maxLen('abc')).toBeNull();+ expect(maxLen('abcde')).toBeNull();+ });++ it('returns error for values exceeding limit', () => {+ expect(maxLen('abcdef')).toBe('Must be no more than 5 characters');+ });++ it('returns null for empty value', () => {+ expect(maxLen('')).toBeNull();+ expect(maxLen(null)).toBeNull();+ });+ });++ describe('pattern', () => {+ const emailLike = validators.pattern(/^[^@]+@[^@]+$/, 'Invalid email');++ it('returns null for matching values', () => {+ expect(emailLike('[email protected]')).toBeNull();+ });++ it('returns error for non-matching values', () => {+ expect(emailLike('not-an-email')).toBe('Invalid email');+ });++ it('returns null for empty value', () => {+ expect(emailLike('')).toBeNull();+ expect(emailLike(null)).toBeNull();+ });++ it('uses default message when none provided', () => {+ const digits = validators.pattern(/^\d+$/);+ expect(digits('abc')).toBe('Invalid format');+ });+ });+});diff --git a/vite.config.js b/vite.config.jsindex 04b47b8107..6df7a9d287 100644--- a/vite.config.js+++ b/vite.config.js@@ -1,3 +1,4 @@+/// <reference types="vitest/config" />import { defineConfig } from 'vite';import { resolve } from 'path';@@ -65,5 +66,13 @@ export default defineConfig({'@js': resolve(__dirname, 'src/local_deep_research/web/static/js'),'@css': resolve(__dirname, 'src/local_deep_research/web/static/css'),}+ },++ test: {+ environment: 'happy-dom',+ globals: true,+ root: resolve(__dirname),+ include: ['tests/js/**/*.test.js'],+ setupFiles: ['tests/js/setup.js'],}});