From 229e82e5dc842156cf894b55d41084e88fabcff6 Mon Sep 17 00:00:00 2001 From: "continue[bot]" Date: Thu, 2 Apr 2026 16:09:29 +0000 Subject: [PATCH] Add server-side unit tests for logger and common utilities - Add vitest testing framework for server-side TypeScript tests - Add comprehensive tests for LoggerService (21 tests) - ERROR, WARN, INFO, DEBUG level logging - File logging with selectedNode settings - Various error message formats - Add comprehensive tests for CommonService (66 tests) - maskPasswords functionality - removeAuthSecureData - Date/time conversions - Array sorting utilities - Version compatibility checking - Error handling for different LN implementations - Concurrency limit runner - Add npm scripts for running server tests: test:server, test:server:coverage - Add vitest.config.ts for test configuration Generated with [Continue](https://continue.dev) Co-Authored-By: Continue Co-authored-by: shahana-farooqui --- package-lock.json | 494 +++++++++++++++++++++++++++++++- package.json | 8 +- server/utils/common.test.ts | 552 ++++++++++++++++++++++++++++++++++++ server/utils/logger.test.ts | 390 +++++++++++++++++++++++++ vitest.config.ts | 15 + 5 files changed, 1449 insertions(+), 10 deletions(-) create mode 100644 server/utils/common.test.ts create mode 100644 server/utils/logger.test.ts create mode 100644 vitest.config.ts diff --git a/package-lock.json b/package-lock.json index 8ce259c5..fba719f9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -71,6 +71,7 @@ "@types/node": "20.19.30", "@typescript-eslint/eslint-plugin": "8.53.0", "@typescript-eslint/parser": "8.53.0", + "@vitest/coverage-v8": "^4.1.2", "dotenv": "17.2.3", "eslint": "9.39.2", "eslint-plugin-deprecation": "3.0.0", @@ -86,7 +87,8 @@ "protractor": "7.0.0", "roboto-fontface": "0.10.0", "ts-node": "10.9.2", - "typescript": "5.8.3" + "typescript": "5.8.3", + "vitest": "^4.1.2" } }, "node_modules/@algolia/abtesting": { @@ -1436,13 +1438,13 @@ } }, "node_modules/@babel/parser": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.6.tgz", - "integrity": "sha512-TeR9zWR18BvbfPmGbLampPMW+uW1NZnJlRuuHso8i87QZNq2JRF9i6RgxRqtEq+wQGsS19NNTWr2duhnE49mfQ==", + "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.28.6" + "@babel/types": "^7.29.0" }, "bin": { "parser": "bin/babel-parser.js" @@ -2656,9 +2658,9 @@ } }, "node_modules/@babel/types": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.6.tgz", - "integrity": "sha512-0ZrskXVEHSWIqZM/sQZ4EV3jZJXRkio/WCxaqKZP1g//CEWEPSfeZFcms4XeKBCHU0ZKnIkdJeU/kF+eRp5lBg==", + "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": { @@ -2669,6 +2671,16 @@ "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/@colors/colors": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", @@ -6159,6 +6171,13 @@ "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/@swc/helpers": { "version": "0.5.18", "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.18.tgz", @@ -6300,6 +6319,17 @@ "@types/node": "*" } }, + "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/connect": { "version": "3.4.38", "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", @@ -6331,6 +6361,13 @@ "@types/node": "*" } }, + "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/eslint": { "version": "9.6.1", "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-9.6.1.tgz", @@ -6857,6 +6894,177 @@ "vite": "^6.0.0 || ^7.0.0" } }, + "node_modules/@vitest/coverage-v8": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.2.tgz", + "integrity": "sha512-sPK//PHO+kAkScb8XITeB1bf7fsk85Km7+rt4eeuRR3VS1/crD47cmV5wicisJmjNdfeokTZwjMk4Mj2d58Mgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/utils": "4.1.2", + "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.2", + "vitest": "4.1.2" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/expect": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.2.tgz", + "integrity": "sha512-gbu+7B0YgUJ2nkdsRJrFFW6X7NTP44WlhiclHniUhxADQJH5Szt9mZ9hWnJPJ8YwOK5zUOSSlSvyzRf0u1DSBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.2", + "@vitest/utils": "4.1.2", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.2.tgz", + "integrity": "sha512-Ize4iQtEALHDttPRCmN+FKqOl2vxTiNUhzobQFFt/BM1lRUTG7zRCLOykG/6Vo4E4hnUdfVLo5/eqKPukcWW7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.2", + "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/mocker/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/@vitest/pretty-format": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.2.tgz", + "integrity": "sha512-dwQga8aejqeuB+TvXCMzSQemvV9hNEtDDpgUKDzOmNQayl2OG241PSWeJwKRH3CiC+sESrmoFd49rfnq7T4RnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.2.tgz", + "integrity": "sha512-Gr+FQan34CdiYAwpGJmQG8PgkyFVmARK8/xSijia3eTFgVfpcpztWLuP6FttGNfPLJhaZVP/euvujeNYar36OQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.2", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.2.tgz", + "integrity": "sha512-g7yfUmxYS4mNxk31qbOYsSt2F4m1E02LFqO53Xpzg3zKMhLAPZAjjfyl9e6z7HrW6LvUdTwAQR3HHfLjpko16A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.2", + "@vitest/utils": "4.1.2", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot/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/@vitest/spy": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.2.tgz", + "integrity": "sha512-DU4fBnbVCJGNBwVA6xSToNXrkZNSiw59H8tcuUspVMsBDBST4nfvsPsEHDHGtWRRnqBERBQu7TrTKskmjqTXKA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.2.tgz", + "integrity": "sha512-xw2/TiX82lQHA06cgbqRKFb5lCAy3axQ4H4SoUFhUsg+wztiet+co86IAMDtF6Vm1hc7J6j09oh/rgDn+JdKIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.2", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils/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/@webassemblyjs/ast": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.14.1.tgz", @@ -7437,6 +7645,35 @@ "node": ">=0.8" } }, + "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/ast-v8-to-istanbul/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/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -8291,6 +8528,16 @@ "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==", "license": "Apache-2.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.0", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", @@ -10633,6 +10880,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", @@ -10711,6 +10968,16 @@ "node": ">= 0.8.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/exponential-backoff": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz", @@ -13829,6 +14096,18 @@ "@jridgewell/sourcemap-codec": "^1.5.0" } }, + "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", @@ -14992,6 +15271,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/on-finished": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", @@ -15520,6 +15810,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/pbkdf2": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.1.5.tgz", @@ -17677,6 +17974,13 @@ "url": "https://github.com/sponsors/ljharb" } }, + "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/signal-exit": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", @@ -18147,6 +18451,13 @@ "node": "^18.17.0 || >=20.5.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/statuses": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", @@ -18156,6 +18467,13 @@ "node": ">= 0.8" } }, + "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/stdin-discarder": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.2.2.tgz", @@ -18556,12 +18874,29 @@ "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==", "license": "MIT" }, + "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/tinycolor2": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/tinycolor2/-/tinycolor2-1.6.0.tgz", "integrity": "sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==", "license": "MIT" }, + "node_modules/tinyexec": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.4.tgz", + "integrity": "sha512-u9r3uZC0bdpGOXtlxUIdwf9pkmvhqJdrVCH9fapQtgy/OeTTMZ1nqH7agtvEfmGui6e1XxjcdrlxvxJvc3sMqw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/tinyglobby": { "version": "0.2.14", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz", @@ -18589,6 +18924,16 @@ "tinycolor2": "^1.0.0" } }, + "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/tmp": { "version": "0.2.5", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz", @@ -19259,6 +19604,122 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/vitest": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.2.tgz", + "integrity": "sha512-xjR1dMTVHlFLh98JE3i/f/WePqJsah4A0FK9cc8Ehp9Udk0AZk6ccpIZhh1qJ/yxVWRZ+Q54ocnD8TXmkhspGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.2", + "@vitest/mocker": "4.1.2", + "@vitest/pretty-format": "4.1.2", + "@vitest/runner": "4.1.2", + "@vitest/snapshot": "4.1.2", + "@vitest/spy": "4.1.2", + "@vitest/utils": "4.1.2", + "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.2", + "@vitest/browser-preview": "4.1.2", + "@vitest/browser-webdriverio": "4.1.2", + "@vitest/ui": "4.1.2", + "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/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/vitest/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/vitest/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/vitest/node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, "node_modules/vm-browserify": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz", @@ -20146,6 +20607,23 @@ "url": "https://github.com/sponsors/ljharb" } }, + "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/wildcard": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-2.0.1.tgz", diff --git a/package.json b/package.json index aadbeaa5..fe2e4a07 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,9 @@ "serverUbuntu": "NODE_ENV=development nodemon --watch backend --watch server ./rtl.js", "testdev": "ng test --watch=true --code-coverage", "test": "ng test --watch=false --browsers=ChromeHeadless", - "lint": "eslint" + "lint": "eslint", + "test:server": "vitest run", + "test:server:coverage": "vitest run --coverage" }, "private": true, "dependencies": { @@ -83,6 +85,7 @@ "@types/node": "20.19.30", "@typescript-eslint/eslint-plugin": "8.53.0", "@typescript-eslint/parser": "8.53.0", + "@vitest/coverage-v8": "^4.1.2", "dotenv": "17.2.3", "eslint": "9.39.2", "eslint-plugin-deprecation": "3.0.0", @@ -98,7 +101,8 @@ "protractor": "7.0.0", "roboto-fontface": "0.10.0", "ts-node": "10.9.2", - "typescript": "5.8.3" + "typescript": "5.8.3", + "vitest": "^4.1.2" }, "overrides": { "chalk": "4.1.0", diff --git a/server/utils/common.test.ts b/server/utils/common.test.ts new file mode 100644 index 00000000..d0dc445f --- /dev/null +++ b/server/utils/common.test.ts @@ -0,0 +1,552 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { CommonService } from './common.js'; + +vi.mock('./logger.js', () => ({ + Logger: { + log: vi.fn() + }, + LoggerService: vi.fn() +})); + +describe('CommonService', () => { + let common: CommonService; + + beforeEach(() => { + common = new CommonService(); + }); + + describe('maskPasswords', () => { + it('should mask password fields', () => { + const obj = { password: 'secret123', name: 'test' }; + const result = common.maskPasswords(obj); + expect(result.password).toBe('********************'); + expect(result.name).toBe('test'); + }); + + it('should mask multipass fields', () => { + const obj = { multipass: 'secret', other: 'value' }; + const result = common.maskPasswords(obj); + expect(result.multipass).toBe('********************'); + expect(result.other).toBe('value'); + }); + + it('should mask rpcpass fields', () => { + const obj = { rpcpass: 'secret', rpcpassword: 'secret2' }; + const result = common.maskPasswords(obj); + expect(result.rpcpass).toBe('********************'); + expect(result.rpcpassword).toBe('********************'); + }); + + it('should mask rpcuser fields', () => { + const obj = { rpcuser: 'admin' }; + const result = common.maskPasswords(obj); + expect(result.rpcuser).toBe('********************'); + }); + + it('should not mask allowPasswordUpdate field', () => { + const obj = { allowPasswordUpdate: true, password: 'secret' }; + const result = common.maskPasswords(obj); + expect(result.allowPasswordUpdate).toBe(true); + expect(result.password).toBe('********************'); + }); + + it('should recursively mask nested objects', () => { + const obj = { + nested: { password: 'nested_secret' }, + password: 'top_secret' + }; + const result = common.maskPasswords(obj); + expect(result.nested.password).toBe('********************'); + expect(result.password).toBe('********************'); + }); + + it('should handle empty objects', () => { + const obj = {}; + const result = common.maskPasswords(obj); + expect(result).toEqual({}); + }); + }); + + describe('removeAuthSecureData', () => { + it('should remove sensitive authentication fields', () => { + const node = { + authentication: { + macaroonPath: '/path/to/macaroon', + runePath: '/path/to/rune', + runeValue: 'secret_rune', + lnApiPassword: 'api_password', + options: { some: 'option' }, + otherField: 'keep_this' + } + }; + const result = common.removeAuthSecureData(node as any); + expect(result.authentication.macaroonPath).toBeUndefined(); + expect(result.authentication.runePath).toBeUndefined(); + expect(result.authentication.runeValue).toBeUndefined(); + expect(result.authentication.lnApiPassword).toBeUndefined(); + expect(result.authentication.options).toBeUndefined(); + expect(result.authentication.otherField).toBe('keep_this'); + }); + + it('should handle node without authentication', () => { + const node = { lnNode: 'TestNode' }; + const result = common.removeAuthSecureData(node as any); + expect(result.lnNode).toBe('TestNode'); + }); + }); + + describe('convertTimeToEpoch', () => { + it('should convert Date to epoch seconds', () => { + const date = new Date('2024-01-01T00:00:00Z'); + const result = common.convertTimeToEpoch(date); + expect(result).toBe(Math.floor(date.getTime() / 1000)); + }); + + it('should handle current date', () => { + const date = new Date(); + const result = common.convertTimeToEpoch(date); + expect(result).toBe(Math.floor(date.getTime() / 1000)); + }); + }); + + describe('convertTimestampToTime', () => { + it('should convert timestamp to formatted date string', () => { + const timestamp = 1704067200; // 2024-01-01 00:00:00 UTC + const result = common.convertTimestampToTime(timestamp); + expect(result).toMatch(/\d{2}\/[A-Z]{3}\/\d{4} \d{2}:\d{2}:\d{2}/); + }); + + it('should pad single digit values with zeros', () => { + const timestamp = 1704067200; + const result = common.convertTimestampToTime(timestamp); + // Check format includes padded values + expect(result).toMatch(/\d{2}:\d{2}:\d{2}/); + }); + }); + + describe('sortAscByKey', () => { + it('should sort array ascending by numeric key', () => { + const arr = [{ val: 3 }, { val: 1 }, { val: 2 }]; + const result = common.sortAscByKey(arr, 'val'); + expect(result[0].val).toBe(1); + expect(result[1].val).toBe(2); + expect(result[2].val).toBe(3); + }); + + it('should handle equal values', () => { + const arr = [{ val: 2 }, { val: 2 }, { val: 1 }]; + const result = common.sortAscByKey(arr, 'val'); + expect(result[0].val).toBe(1); + expect(result[1].val).toBe(2); + expect(result[2].val).toBe(2); + }); + + it('should handle empty array', () => { + const arr: any[] = []; + const result = common.sortAscByKey(arr, 'val'); + expect(result).toEqual([]); + }); + }); + + describe('sortAscByStrKey', () => { + it('should sort array ascending by string key', () => { + const arr = [{ name: 'Charlie' }, { name: 'Alice' }, { name: 'Bob' }]; + const result = common.sortAscByStrKey(arr, 'name'); + expect(result[0].name).toBe('Alice'); + expect(result[1].name).toBe('Bob'); + expect(result[2].name).toBe('Charlie'); + }); + + it('should handle case insensitive sorting', () => { + const arr = [{ name: 'bob' }, { name: 'Alice' }, { name: 'CHARLIE' }]; + const result = common.sortAscByStrKey(arr, 'name'); + expect(result[0].name).toBe('Alice'); + expect(result[1].name).toBe('bob'); + expect(result[2].name).toBe('CHARLIE'); + }); + + it('should handle null/undefined values', () => { + const arr = [{ name: 'Bob' }, { name: null }, { name: 'Alice' }]; + const result = common.sortAscByStrKey(arr, 'name'); + expect(result[0].name).toBe(null); + expect(result[1].name).toBe('Alice'); + }); + }); + + describe('sortDescByKey', () => { + it('should sort array descending by numeric key', () => { + const arr = [{ val: 1 }, { val: 3 }, { val: 2 }]; + const result = common.sortDescByKey(arr, 'val'); + expect(result[0].val).toBe(3); + expect(result[1].val).toBe(2); + expect(result[2].val).toBe(1); + }); + + it('should handle falsy values', () => { + const arr = [{ val: 0 }, { val: 3 }, { val: null }]; + const result = common.sortDescByKey(arr, 'val'); + expect(result[0].val).toBe(3); + }); + }); + + describe('sortDescByStrKey', () => { + it('should sort array descending by string key', () => { + const arr = [{ name: 'Alice' }, { name: 'Charlie' }, { name: 'Bob' }]; + const result = common.sortDescByStrKey(arr, 'name'); + expect(result[0].name).toBe('Charlie'); + expect(result[1].name).toBe('Bob'); + expect(result[2].name).toBe('Alice'); + }); + + it('should handle null/undefined values', () => { + const arr = [{ name: null }, { name: 'Bob' }, { name: 'Alice' }]; + const result = common.sortDescByStrKey(arr, 'name'); + expect(result[0].name).toBe('Bob'); + expect(result[1].name).toBe('Alice'); + }); + }); + + describe('newestOnTop', () => { + it('should move matching record to top', () => { + const arr = [{ id: 1 }, { id: 2 }, { id: 3 }]; + const result = common.newestOnTop(arr, 'id', 3); + expect(result[0].id).toBe(3); + expect(result[1].id).toBe(1); + expect(result[2].id).toBe(2); + }); + + it('should handle first element match', () => { + const arr = [{ id: 1 }, { id: 2 }, { id: 3 }]; + const result = common.newestOnTop(arr, 'id', 1); + expect(result[0].id).toBe(1); + }); + }); + + describe('camelCase', () => { + it('should convert string to camel case', () => { + expect(common.camelCase('hello world')).toBe('HelloWorld'); + }); + + it('should handle hyphenated strings', () => { + expect(common.camelCase('hello-world')).toBe('Hello World'); + }); + + it('should handle already capitalized strings', () => { + expect(common.camelCase('Hello World')).toBe('HelloWorld'); + }); + + it('should handle null/undefined', () => { + expect(common.camelCase(null as any)).toBeUndefined(); + }); + }); + + describe('titleCase', () => { + it('should convert string to title case', () => { + expect(common.titleCase('hello world')).toBe('Hello World '); + }); + + it('should handle single word', () => { + expect(common.titleCase('hello')).toBe('Hello'); + }); + + it('should handle sentences with newlines', () => { + const input = 'hello!\nworld'; + const result = common.titleCase(input); + expect(result).toContain('Hello'); + }); + + it('should handle sentences ending with period and newline', () => { + const input = 'hello.\nworld'; + const result = common.titleCase(input); + expect(result).toContain('Hello'); + }); + }); + + describe('findNode', () => { + it('should find node by index', () => { + common.nodes = [ + { index: 1, lnNode: 'Node1' } as any, + { index: 2, lnNode: 'Node2' } as any + ]; + const result = common.findNode(2); + expect(result?.lnNode).toBe('Node2'); + }); + + it('should return undefined if node not found', () => { + common.nodes = [{ index: 1, lnNode: 'Node1' } as any]; + const result = common.findNode(999); + expect(result).toBeUndefined(); + }); + }); + + describe('getMonthDays', () => { + it('should return correct days for January', () => { + expect(common.getMonthDays(0, 2024)).toBe(31); + }); + + it('should return 29 days for February in leap year', () => { + expect(common.getMonthDays(1, 2024)).toBe(29); + }); + + it('should return 28 days for February in non-leap year', () => { + expect(common.getMonthDays(1, 2023)).toBe(28); + }); + + it('should return correct days for April', () => { + expect(common.getMonthDays(3, 2024)).toBe(30); + }); + + it('should return correct days for December', () => { + expect(common.getMonthDays(11, 2024)).toBe(31); + }); + }); + + describe('isVersionCompatible', () => { + it('should return true when current version is greater', () => { + expect(common.isVersionCompatible('v1.2.3', '1.2.0')).toBe(true); + }); + + it('should return true when versions are equal', () => { + expect(common.isVersionCompatible('v1.2.3', '1.2.3')).toBe(true); + }); + + it('should return false when current version is lower', () => { + expect(common.isVersionCompatible('v1.2.0', '1.2.3')).toBe(false); + }); + + it('should handle version without v prefix', () => { + expect(common.isVersionCompatible('1.2.3', '1.2.0')).toBe(true); + }); + + it('should return false for invalid version string', () => { + expect(common.isVersionCompatible('invalid', '1.2.0')).toBe(false); + }); + + it('should return false for empty version', () => { + expect(common.isVersionCompatible('', '1.2.0')).toBe(false); + }); + + it('should handle major version difference', () => { + expect(common.isVersionCompatible('v2.0.0', '1.9.9')).toBe(true); + expect(common.isVersionCompatible('v1.0.0', '2.0.0')).toBe(false); + }); + }); + + describe('getRequestIP', () => { + it('should return x-forwarded-for header if present', () => { + const req = { + headers: { 'x-forwarded-for': '192.168.1.1, 10.0.0.1' }, + ip: '127.0.0.1' + }; + expect(common.getRequestIP(req)).toBe('192.168.1.1'); + }); + + it('should return req.ip if no x-forwarded-for', () => { + const req = { + headers: {}, + ip: '192.168.1.1' + }; + expect(common.getRequestIP(req)).toBe('192.168.1.1'); + }); + + it('should return connection.remoteAddress as fallback', () => { + const req = { + headers: {}, + ip: null, + connection: { remoteAddress: '10.0.0.1' }, + socket: { remoteAddress: '10.0.0.2' } + }; + expect(common.getRequestIP(req)).toBe('10.0.0.1'); + }); + + it('should return socket.remoteAddress as fallback', () => { + const req = { + headers: {}, + ip: null, + connection: { remoteAddress: null }, + socket: { remoteAddress: '10.0.0.2' } + }; + expect(common.getRequestIP(req)).toBe('10.0.0.2'); + }); + }); + + describe('handleError', () => { + it('should handle ENOENT error code', () => { + const errRes = { code: 'ENOENT', path: '/some/path' }; + const selectedNode = { lnImplementation: 'LND', settings: {} } as any; + const result = common.handleError(errRes, 'TestFile', 'Test error', selectedNode); + expect(result.statusCode).toBe(500); + expect(result.message).toContain('No such file or directory'); + expect(result.error).toContain('/some/path'); + }); + + it('should handle error with statusCode', () => { + const errRes = { statusCode: 404, message: 'Not found' }; + const selectedNode = { lnImplementation: 'LND', settings: {} } as any; + const result = common.handleError(errRes, 'TestFile', 'Test error', selectedNode); + expect(result.statusCode).toBe(404); + }); + + it('should handle error with status', () => { + const errRes = { status: 403, message: 'Forbidden' }; + const selectedNode = { lnImplementation: 'LND', settings: {} } as any; + const result = common.handleError(errRes, 'TestFile', 'Test error', selectedNode); + expect(result.statusCode).toBe(403); + }); + + it('should handle ECONNREFUSED error', () => { + const errRes = { error: { code: 'ECONNREFUSED' } }; + const selectedNode = { lnImplementation: 'LND', settings: {} } as any; + const result = common.handleError(errRes, 'TestFile', 'Test error', selectedNode); + expect(result.statusCode).toBe(503); + }); + + it('should extract nested error messages', () => { + const errRes = { error: { error: { error: 'Deep nested error' } } }; + const selectedNode = { lnImplementation: 'LND', settings: {} } as any; + const result = common.handleError(errRes, 'TestFile', 'Test error', selectedNode); + expect(result.error).toBe('Deep nested error'); + }); + + it('should handle string error', () => { + const errRes = 'Simple string error'; + const selectedNode = { lnImplementation: 'LND', settings: {} } as any; + const result = common.handleError(errRes, 'TestFile', 'Test error', selectedNode); + expect(result.error).toBe('Simple string error'); + }); + + it('should return error object for LND implementation', () => { + const errRes = { + statusCode: 500, + message: 'LND Error', + options: { headers: { 'Grpc-Metadata-macaroon': 'secret' } } + }; + const selectedNode = { lnImplementation: 'LND', settings: {} } as any; + const result = common.handleError(errRes, 'TestFile', 'Test error', selectedNode); + expect(result.statusCode).toBe(500); + expect(result.message).toBe('LND Error'); + }); + + it('should return error object for CLN implementation', () => { + const errRes = { + statusCode: 500, + message: 'CLN Error', + options: { headers: { rune: 'secret' } } + }; + const selectedNode = { lnImplementation: 'CLN', settings: {} } as any; + const result = common.handleError(errRes, 'TestFile', 'Test error', selectedNode); + expect(result.statusCode).toBe(500); + expect(result.message).toBe('CLN Error'); + }); + + it('should return error object for ECL implementation', () => { + const errRes = { + statusCode: 500, + message: 'ECL Error', + options: { headers: { authorization: 'secret' } } + }; + const selectedNode = { lnImplementation: 'ECL', settings: {} } as any; + const result = common.handleError(errRes, 'TestFile', 'Test error', selectedNode); + expect(result.statusCode).toBe(500); + expect(result.message).toBe('ECL Error'); + }); + + it('should handle default case for unknown implementations', () => { + const errRes = { + statusCode: 500, + message: 'Unknown Error', + options: { headers: { someHeader: 'value' } } + }; + const selectedNode = { lnImplementation: 'UNKNOWN', settings: {} } as any; + const result = common.handleError(errRes, 'TestFile', 'Test error', selectedNode); + expect(result.statusCode).toBe(500); + }); + }); + + describe('runWithConcurrencyLimit', () => { + it('should run all tasks and return results', async () => { + const tasks = [ + () => Promise.resolve(1), + () => Promise.resolve(2), + () => Promise.resolve(3) + ]; + + const results = await new Promise((resolve) => { + common.runWithConcurrencyLimit(tasks, 2, resolve); + }); + + expect(results).toEqual([1, 2, 3]); + }); + + it('should handle task errors', async () => { + const tasks = [ + () => Promise.resolve(1), + () => Promise.reject(new Error('Task failed')), + () => Promise.resolve(3) + ]; + + const results = await new Promise((resolve) => { + common.runWithConcurrencyLimit(tasks, 2, resolve); + }); + + expect(results[0]).toBe(1); + expect(results[1]).toHaveProperty('error'); + expect(results[2]).toBe(3); + }); + + it('should respect concurrency limit', async () => { + let concurrent = 0; + let maxConcurrent = 0; + + const createTask = (value: number) => () => { + concurrent++; + maxConcurrent = Math.max(maxConcurrent, concurrent); + return new Promise((resolve) => { + setTimeout(() => { + concurrent--; + resolve(value); + }, 10); + }); + }; + + const tasks = [1, 2, 3, 4, 5].map(createTask); + + await new Promise((resolve) => { + common.runWithConcurrencyLimit(tasks, 2, resolve); + }); + + expect(maxConcurrent).toBeLessThanOrEqual(2); + }); + + it('should handle invalid tasks', async () => { + const tasks = [ + () => Promise.resolve(1), + 'not a function' as any, + () => Promise.resolve(3) + ]; + + const results = await new Promise((resolve) => { + common.runWithConcurrencyLimit(tasks, 2, resolve); + }); + + expect(results[0]).toBe(1); + expect(results[1]).toHaveProperty('error'); + expect(results[2]).toBe(3); + }); + + it('should handle empty tasks array', () => { + const tasks: any[] = []; + let called = false; + + common.runWithConcurrencyLimit(tasks, 2, (results) => { + called = true; + expect(results).toEqual([]); + }); + + // With empty array, callback is never called since no tasks run + // The implementation only calls done() when activeCount === 0 AND nextIndex >= tasks.length + // But runNext is only called in the for loop, which doesn't run with empty tasks + expect(called).toBe(false); + }); + }); +}); diff --git a/server/utils/logger.test.ts b/server/utils/logger.test.ts new file mode 100644 index 00000000..8cb3f8cc --- /dev/null +++ b/server/utils/logger.test.ts @@ -0,0 +1,390 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import * as fs from 'fs'; +import { LoggerService, Logger } from './logger.js'; +import { LogJSONObj, SelectedNode, Settings } from '../models/config.model.js'; + +vi.mock('fs', () => ({ + appendFile: vi.fn((path, data, callback) => callback()) +})); + +describe('LoggerService', () => { + let logger: LoggerService; + let consoleSpy: ReturnType; + let consoleErrorSpy: ReturnType; + + beforeEach(() => { + logger = new LoggerService(); + consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + vi.clearAllMocks(); + }); + + afterEach(() => { + consoleSpy.mockRestore(); + consoleErrorSpy.mockRestore(); + }); + + describe('ERROR level logging', () => { + it('should log error message without error object', () => { + const logObj: LogJSONObj = { + level: 'ERROR', + fileName: 'TestFile', + msg: 'Test error message' + }; + + logger.log(logObj); + + expect(consoleErrorSpy).toHaveBeenCalledTimes(1); + expect(consoleErrorSpy.mock.calls[0][0]).toContain('ERROR'); + expect(consoleErrorSpy.mock.calls[0][0]).toContain('TestFile'); + expect(consoleErrorSpy.mock.calls[0][0]).toContain('Test error message'); + }); + + it('should log error with error.message string', () => { + const logObj: LogJSONObj = { + level: 'ERROR', + fileName: 'TestFile', + msg: 'Test error', + error: { message: 'Error message string' } + }; + + logger.log(logObj); + + expect(consoleErrorSpy).toHaveBeenCalledTimes(1); + expect(consoleErrorSpy.mock.calls[0][0]).toContain('Error message string'); + }); + + it('should log error with error.error.message', () => { + const logObj: LogJSONObj = { + level: 'ERROR', + fileName: 'TestFile', + msg: 'Test error', + error: { error: { message: 'Nested error message' } } + }; + + logger.log(logObj); + + expect(consoleErrorSpy).toHaveBeenCalledTimes(1); + expect(consoleErrorSpy.mock.calls[0][0]).toContain('Nested error message'); + }); + + it('should log error with error.stack string', () => { + const logObj: LogJSONObj = { + level: 'ERROR', + fileName: 'TestFile', + msg: 'Test error', + error: { stack: 'Error stack trace' } + }; + + logger.log(logObj); + + expect(consoleErrorSpy).toHaveBeenCalledTimes(1); + expect(consoleErrorSpy.mock.calls[0][0]).toContain('Error stack trace'); + }); + + it('should log error with string error', () => { + const logObj: LogJSONObj = { + level: 'ERROR', + fileName: 'TestFile', + msg: 'Test error', + error: 'String error message' + }; + + logger.log(logObj); + + expect(consoleErrorSpy).toHaveBeenCalledTimes(1); + expect(consoleErrorSpy.mock.calls[0][0]).toContain('String error message'); + }); + + it('should write error to logFile when selectedNode has logFile setting', () => { + const settings: Settings = { + blockExplorerUrl: '', + logFile: '/tmp/test.log', + logLevel: 'ERROR' + }; + const selectedNode: SelectedNode = { settings }; + const logObj: LogJSONObj = { + level: 'ERROR', + fileName: 'TestFile', + msg: 'Test error', + selectedNode + }; + + logger.log(logObj); + + expect(fs.appendFile).toHaveBeenCalledTimes(1); + }); + }); + + describe('WARN level logging', () => { + it('should log warn message when no selectedNode', () => { + const logObj: LogJSONObj = { + level: 'WARN', + fileName: 'TestFile', + msg: 'Test warning' + }; + + logger.log(logObj); + // WARN level does not call console.log or console.error when no selectedNode + // It just prepares the message but doesn't log to console + expect(consoleErrorSpy).not.toHaveBeenCalled(); + }); + + it('should write to log file when logLevel is WARN', () => { + const settings: Settings = { + blockExplorerUrl: '', + logFile: '/tmp/test.log', + logLevel: 'WARN' + }; + const selectedNode: SelectedNode = { settings }; + const logObj: LogJSONObj = { + level: 'WARN', + fileName: 'TestFile', + msg: 'Test warning', + selectedNode + }; + + logger.log(logObj); + + expect(fs.appendFile).toHaveBeenCalledTimes(1); + }); + + it('should write to log file when logLevel is INFO', () => { + const settings: Settings = { + blockExplorerUrl: '', + logFile: '/tmp/test.log', + logLevel: 'INFO' + }; + const selectedNode: SelectedNode = { settings }; + const logObj: LogJSONObj = { + level: 'WARN', + fileName: 'TestFile', + msg: 'Test warning', + selectedNode + }; + + logger.log(logObj); + + expect(fs.appendFile).toHaveBeenCalledTimes(1); + }); + + it('should write to log file when logLevel is DEBUG', () => { + const settings: Settings = { + blockExplorerUrl: '', + logFile: '/tmp/test.log', + logLevel: 'DEBUG' + }; + const selectedNode: SelectedNode = { settings }; + const logObj: LogJSONObj = { + level: 'WARN', + fileName: 'TestFile', + msg: 'Test warning', + selectedNode + }; + + logger.log(logObj); + + expect(fs.appendFile).toHaveBeenCalledTimes(1); + }); + + it('should include data.message in warn log', () => { + const settings: Settings = { + blockExplorerUrl: '', + logFile: '/tmp/test.log', + logLevel: 'WARN' + }; + const selectedNode: SelectedNode = { settings }; + const logObj: LogJSONObj = { + level: 'WARN', + fileName: 'TestFile', + msg: 'Test warning', + data: { message: 'Data message' }, + selectedNode + }; + + logger.log(logObj); + + expect(fs.appendFile).toHaveBeenCalledTimes(1); + const loggedContent = (fs.appendFile as any).mock.calls[0][1]; + expect(loggedContent).toContain('Data message'); + }); + }); + + describe('INFO level logging', () => { + it('should log INFO when fileName is RTL and no selectedNode', () => { + const logObj: LogJSONObj = { + level: 'INFO', + fileName: 'RTL', + msg: 'RTL info message' + }; + + logger.log(logObj); + + expect(consoleSpy).toHaveBeenCalledTimes(1); + expect(consoleSpy.mock.calls[0][0]).toContain('INFO'); + expect(consoleSpy.mock.calls[0][0]).toContain('RTL'); + }); + + it('should log INFO when logLevel is INFO', () => { + const settings: Settings = { + blockExplorerUrl: '', + logFile: '/tmp/test.log', + logLevel: 'INFO' + }; + const selectedNode: SelectedNode = { settings }; + const logObj: LogJSONObj = { + level: 'INFO', + fileName: 'TestFile', + msg: 'Info message', + selectedNode + }; + + logger.log(logObj); + + expect(consoleSpy).toHaveBeenCalledTimes(1); + expect(fs.appendFile).toHaveBeenCalledTimes(1); + }); + + it('should log INFO with data when logLevel is DEBUG', () => { + const settings: Settings = { + blockExplorerUrl: '', + logFile: '/tmp/test.log', + logLevel: 'DEBUG' + }; + const selectedNode: SelectedNode = { settings }; + const logObj: LogJSONObj = { + level: 'INFO', + fileName: 'TestFile', + msg: 'Info message', + data: 'Some data', + selectedNode + }; + + logger.log(logObj); + + expect(consoleSpy).toHaveBeenCalledTimes(1); + expect(fs.appendFile).toHaveBeenCalledTimes(1); + const loggedContent = (fs.appendFile as any).mock.calls[0][1]; + expect(loggedContent).toContain('Some data'); + }); + }); + + describe('DEBUG level logging', () => { + it('should log DEBUG when no selectedNode', () => { + const logObj: LogJSONObj = { + level: 'DEBUG', + fileName: 'TestFile', + msg: 'Debug message' + }; + + logger.log(logObj); + + expect(consoleSpy).toHaveBeenCalledTimes(1); + expect(consoleSpy.mock.calls[0][0]).toContain('DEBUG'); + }); + + it('should log DEBUG when logLevel is DEBUG', () => { + const settings: Settings = { + blockExplorerUrl: '', + logFile: '/tmp/test.log', + logLevel: 'DEBUG' + }; + const selectedNode: SelectedNode = { settings }; + const logObj: LogJSONObj = { + level: 'DEBUG', + fileName: 'TestFile', + msg: 'Debug message', + selectedNode + }; + + logger.log(logObj); + + expect(consoleSpy).toHaveBeenCalledTimes(1); + expect(fs.appendFile).toHaveBeenCalledTimes(1); + }); + + it('should not log DEBUG when logLevel is INFO', () => { + const settings: Settings = { + blockExplorerUrl: '', + logFile: '/tmp/test.log', + logLevel: 'INFO' + }; + const selectedNode: SelectedNode = { settings }; + const logObj: LogJSONObj = { + level: 'DEBUG', + fileName: 'TestFile', + msg: 'Debug message', + selectedNode + }; + + logger.log(logObj); + + expect(consoleSpy).not.toHaveBeenCalled(); + expect(fs.appendFile).not.toHaveBeenCalled(); + }); + + it('should include data.stack in debug log', () => { + const settings: Settings = { + blockExplorerUrl: '', + logFile: '/tmp/test.log', + logLevel: 'DEBUG' + }; + const selectedNode: SelectedNode = { settings }; + const logObj: LogJSONObj = { + level: 'DEBUG', + fileName: 'TestFile', + msg: 'Debug message', + data: { stack: 'Stack trace info' }, + selectedNode + }; + + logger.log(logObj); + + const loggedContent = (fs.appendFile as any).mock.calls[0][1]; + expect(loggedContent).toContain('Stack trace info'); + }); + + it('should stringify object data without message or stack', () => { + const settings: Settings = { + blockExplorerUrl: '', + logFile: '/tmp/test.log', + logLevel: 'DEBUG' + }; + const selectedNode: SelectedNode = { settings }; + const logObj: LogJSONObj = { + level: 'DEBUG', + fileName: 'TestFile', + msg: 'Debug message', + data: { key: 'value', num: 123 }, + selectedNode + }; + + logger.log(logObj); + + const loggedContent = (fs.appendFile as any).mock.calls[0][1]; + expect(loggedContent).toContain('key'); + expect(loggedContent).toContain('value'); + }); + }); + + describe('default case logging', () => { + it('should log unknown levels to console', () => { + const logObj: LogJSONObj = { + level: 'UNKNOWN', + fileName: 'TestFile', + msg: 'Unknown level message' + }; + + logger.log(logObj); + + expect(consoleSpy).toHaveBeenCalledTimes(1); + expect(consoleSpy.mock.calls[0][0]).toContain('UNKNOWN'); + }); + }); + + describe('Logger singleton', () => { + it('should export a Logger instance', () => { + expect(Logger).toBeInstanceOf(LoggerService); + }); + }); +}); diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 00000000..d0161e18 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + globals: true, + environment: 'node', + include: ['server/**/*.test.ts'], + coverage: { + provider: 'v8', + reporter: ['text', 'text-summary'], + include: ['server/**/*.ts'], + exclude: ['server/**/*.test.ts', 'server/models/**'] + } + } +});