From 8ec43bf964cabb073bdf6c9ad94b475bc33da056 Mon Sep 17 00:00:00 2001 From: Mochamad Noor Syamsu Date: Sun, 24 Dec 2023 16:52:57 +0700 Subject: [PATCH] clean up all warnings --- custom_types/pg/index.d.ts | 25 ------ package-lock.json | 81 +++++++++++++++++++ package.json | 1 + src/components/logger/history.ts | 6 +- src/components/notification/alert-message.ts | 5 +- src/components/probe/index.test.ts | 21 +++-- .../probe/prober/http/index.test.ts | 5 +- src/components/probe/prober/http/index.ts | 2 +- .../probe/prober/http/request.test.ts | 16 ++-- src/components/probe/prober/http/request.ts | 10 +-- src/components/probe/prober/mariadb/index.ts | 5 +- src/components/probe/prober/mongo/request.ts | 2 +- src/components/probe/prober/postgres/index.ts | 10 +-- .../probe/prober/postgres/request.ts | 8 +- src/components/probe/prober/redis/request.ts | 2 +- src/components/probe/prober/socket/request.ts | 6 +- src/interfaces/request.ts | 12 ++- src/interfaces/response.ts | 23 ------ src/loaders/jobs.ts | 4 +- src/plugins/metrics/prometheus/collector.ts | 11 +-- .../__tests__/query-expression.test.ts | 2 +- .../checkers/query-expression.ts | 5 +- src/symon/index.test.ts | 4 +- src/symon/index.ts | 3 +- src/utils/events.ts | 1 + src/utils/expression-parser.ts | 4 +- src/utils/fakes.ts | 12 ++- src/utils/hash.ts | 2 +- src/utils/ping.ts | 4 +- src/utils/pino.ts | 5 +- src/utils/probe-state.ts | 2 +- src/utils/public-ip.ts | 5 +- test/index.test.ts | 4 +- .../validate-sample-configs.test.ts | 2 +- test/others/change-config-loop.ts | 6 +- test/others/hide-ip.test.ts | 4 +- 36 files changed, 191 insertions(+), 129 deletions(-) delete mode 100644 custom_types/pg/index.d.ts delete mode 100644 src/interfaces/response.ts diff --git a/custom_types/pg/index.d.ts b/custom_types/pg/index.d.ts deleted file mode 100644 index 288f823e0..000000000 --- a/custom_types/pg/index.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -/********************************************************************************** - * MIT License * - * * - * Copyright (c) 2021 Hyperjump Technology * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy * - * of this software and associated documentation files (the "Software"), to deal * - * in the Software without restriction, including without limitation the rights * - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included in all * - * copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * - * SOFTWARE. * - **********************************************************************************/ - -declare module 'pg' diff --git a/package-lock.json b/package-lock.json index 07382a5df..2b2d16a46 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,6 +18,7 @@ "@oclif/plugin-help": "5.2.20", "@oclif/plugin-version": "1.3.10", "@sendgrid/mail": "^7.4.2", + "@types/pg": "^8.10.9", "ajv": "^8.11.0", "axios": "^0.27.2", "boxen": "^5.0.0", @@ -3969,6 +3970,68 @@ "integrity": "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==", "dev": true }, + "node_modules/@types/pg": { + "version": "8.10.9", + "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.10.9.tgz", + "integrity": "sha512-UksbANNE/f8w0wOMxVKKIrLCbEMV+oM1uKejmwXr39olg4xqcfBDbXxObJAt6XxHbDa4XTKOlUEcEltXDX+XLQ==", + "dependencies": { + "@types/node": "*", + "pg-protocol": "*", + "pg-types": "^4.0.1" + } + }, + "node_modules/@types/pg/node_modules/pg-types": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-4.0.1.tgz", + "integrity": "sha512-hRCSDuLII9/LE3smys1hRHcu5QGcLs9ggT7I/TCs0IE+2Eesxi9+9RWAAwZ0yaGjxoWICF/YHLOEjydGujoJ+g==", + "dependencies": { + "pg-int8": "1.0.1", + "pg-numeric": "1.0.2", + "postgres-array": "~3.0.1", + "postgres-bytea": "~3.0.0", + "postgres-date": "~2.0.1", + "postgres-interval": "^3.0.0", + "postgres-range": "^1.1.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@types/pg/node_modules/postgres-array": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-3.0.2.tgz", + "integrity": "sha512-6faShkdFugNQCLwucjPcY5ARoW1SlbnrZjmGl0IrrqewpvxvhSLHimCVzqeuULCbG0fQv7Dtk1yDbG3xv7Veog==", + "engines": { + "node": ">=12" + } + }, + "node_modules/@types/pg/node_modules/postgres-bytea": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-3.0.0.tgz", + "integrity": "sha512-CNd4jim9RFPkObHSjVHlVrxoVQXz7quwNFpz7RY1okNNme49+sVyiTvTRobiLV548Hx/hb1BG+iE7h9493WzFw==", + "dependencies": { + "obuf": "~1.1.2" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/@types/pg/node_modules/postgres-date": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-2.0.1.tgz", + "integrity": "sha512-YtMKdsDt5Ojv1wQRvUhnyDJNSr2dGIC96mQVKz7xufp07nfuFONzdaowrMHjlAzY6GDLd4f+LUHHAAM1h4MdUw==", + "engines": { + "node": ">=12" + } + }, + "node_modules/@types/pg/node_modules/postgres-interval": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-3.0.0.tgz", + "integrity": "sha512-BSNDnbyZCXSxgA+1f5UU2GmwhoI0aU5yMxRGO8CdFEcY2BQF9xm/7MqKnYoM1nJDk8nONNWDk9WeSmePFhQdlw==", + "engines": { + "node": ">=12" + } + }, "node_modules/@types/qs": { "version": "6.9.11", "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.11.tgz", @@ -12588,6 +12651,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/obuf": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/obuf/-/obuf-1.1.2.tgz", + "integrity": "sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg==" + }, "node_modules/oclif": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/oclif/-/oclif-4.1.0.tgz", @@ -13276,6 +13344,14 @@ "node": ">=4.0.0" } }, + "node_modules/pg-numeric": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pg-numeric/-/pg-numeric-1.0.2.tgz", + "integrity": "sha512-BM/Thnrw5jm2kKLE5uJkXqqExRUY/toLHda65XgFTBTFYZyopbKjBe29Ii3RbkvlsMoFwD+tHeGaCjjv0gHlyw==", + "engines": { + "node": ">=4" + } + }, "node_modules/pg-pool": { "version": "3.6.1", "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.6.1.tgz", @@ -13690,6 +13766,11 @@ "node": ">=0.10.0" } }, + "node_modules/postgres-range": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/postgres-range/-/postgres-range-1.1.3.tgz", + "integrity": "sha512-VdlZoocy5lCP0c/t66xAfclglEapXPCIVhqqJRncYpvbCgImF0w67aPKfbqUMr72tO2k5q0TdTZwCLjPTI6C9g==" + }, "node_modules/prebuild-install": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.1.tgz", diff --git a/package.json b/package.json index 66ff80548..d5188e0d6 100644 --- a/package.json +++ b/package.json @@ -63,6 +63,7 @@ "@oclif/plugin-help": "5.2.20", "@oclif/plugin-version": "1.3.10", "@sendgrid/mail": "^7.4.2", + "@types/pg": "^8.10.9", "ajv": "^8.11.0", "axios": "^0.27.2", "boxen": "^5.0.0", diff --git a/src/components/logger/history.ts b/src/components/logger/history.ts index 39faea616..c2e625ba5 100644 --- a/src/components/logger/history.ts +++ b/src/components/logger/history.ts @@ -135,6 +135,8 @@ export function setDatabase( async function migrate() { await database().migrate({ + // TODO: Current vercel/pkg is dependent with CommonJS + // eslint-disable-next-line unicorn/prefer-module migrationsPath: path.join(__dirname, '../../../db/migrations'), }) } @@ -468,7 +470,9 @@ export async function saveProbeRequestLog({ JSON.stringify(probeRes.headers), responseBody, probeRes?.responseTime ?? 0, - probeRes.headers['content-length'], + typeof probeRes.headers === 'string' + ? probeRes.headers + : probeRes.headers['content-length'], errorResp, probe.socket ? 'tcp' : 'http', probe.socket?.host || '', diff --git a/src/components/notification/alert-message.ts b/src/components/notification/alert-message.ts index e6be3a835..e9aeb64a4 100644 --- a/src/components/notification/alert-message.ts +++ b/src/components/notification/alert-message.ts @@ -78,7 +78,10 @@ const getExpectedMessage = ( return Handlebars.compile(alert.message)({ response: { - size: Number(headers['content-length']), + size: + typeof headers === 'string' + ? undefined + : Number(headers['content-length']), status, time: responseTime, body: data, diff --git a/src/components/probe/index.test.ts b/src/components/probe/index.test.ts index 0a4045da3..ea36134a6 100644 --- a/src/components/probe/index.test.ts +++ b/src/components/probe/index.test.ts @@ -39,7 +39,10 @@ import type { MonikaFlags } from '../../flag' import { FAILED_REQUEST_ASSERTION } from '../../looper' import { closeLog, openLogfile } from '../logger/history' -let notificationAlert: Record> = {} +let notificationAlert: Record< + string, + Record> +> = {} const server = setupServer( rest.get('https://example.com', (_, res, ctx) => res(ctx.status(200))), rest.post('https://example.com/webhook', async (req, res, ctx) => { @@ -444,7 +447,7 @@ describe('Base Probe processing', () => { async connect() {}, on: () => '', ping: async () => 'PONG', - } as any) + } as never) ) const probes = [ { @@ -483,7 +486,7 @@ describe('Base Probe processing', () => { async connect() {}, on: () => '', ping: async () => 'PONG', - } as any) + } as never) ) const probes = [ { @@ -514,16 +517,18 @@ describe('Base Probe processing', () => { it('should probe socket', async () => { const requestStub = sinon.stub(net, 'createConnection').callsFake(() => { - let data = '' - + let data: Buffer | Uint8Array return { - write(d: any) { + write(d: Buffer | Uint8Array) { data = d }, setTimeout(timeoutMs: number) { return timeoutMs }, - on(type: string, callback: (data?: any) => void) { + on( + type: string, + callback: (data?: Buffer | Uint8Array | Error) => void + ) { switch (type) { case 'data': { callback(data) @@ -541,7 +546,7 @@ describe('Base Probe processing', () => { } case 'error': { - callback('error') + callback(new Error('Stub Error')) break } diff --git a/src/components/probe/prober/http/index.test.ts b/src/components/probe/prober/http/index.test.ts index 139bf9208..6683cfff6 100644 --- a/src/components/probe/prober/http/index.test.ts +++ b/src/components/probe/prober/http/index.test.ts @@ -37,7 +37,10 @@ import { FAILED_REQUEST_ASSERTION } from '../../../../looper' import { closeLog, openLogfile } from '../../../logger/history' let urlRequestTotal = 0 -let notificationAlert: Record> = {} +let notificationAlert: Record< + string, + Record> +> = {} const server = setupServer( rest.get('https://example.com', (_, res, ctx) => { urlRequestTotal += 1 diff --git a/src/components/probe/prober/http/index.ts b/src/components/probe/prober/http/index.ts index 9a14b8703..05e4f8db6 100644 --- a/src/components/probe/prober/http/index.ts +++ b/src/components/probe/prober/http/index.ts @@ -262,7 +262,7 @@ function getProbeResultMessage({ }: ProbeResultMessageParams): string { // TODO: make this more generic not probe dependent if (request?.ping) { - return response?.body + return response?.body as string } if (getContext().flags.verbose) { diff --git a/src/components/probe/prober/http/request.test.ts b/src/components/probe/prober/http/request.test.ts index 7f5643499..293fc5b9a 100644 --- a/src/components/probe/prober/http/request.test.ts +++ b/src/components/probe/prober/http/request.test.ts @@ -123,7 +123,7 @@ describe('probingHTTP', () => { return res(ctx.status(200)) }) ) - const request: any = { + const request = { url: 'http://localhost:4000/login', method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, @@ -162,7 +162,7 @@ describe('probingHTTP', () => { url: 'https://example.com', method: 'POST', headers: { 'content-type': 'multipart/form-data' }, - body: { username: 'john@example.com', password: 'drowssap' } as any, + body: { username: 'john@example.com', password: 'drowssap' } as never, timeout: 10_000, } @@ -200,7 +200,7 @@ describe('probingHTTP', () => { url: 'https://example.com', method: 'POST', headers: { 'content-type': 'text/plain' }, - body: 'multiline string\nexample' as any, + body: 'multiline string\nexample', timeout: 10_000, } @@ -238,7 +238,7 @@ describe('probingHTTP', () => { url: 'https://example.com', method: 'POST', headers: { 'content-type': 'text/yaml' }, - body: { username: 'john@example.com', password: 'secret' } as any, + body: { username: 'john@example.com', password: 'secret' } as never, timeout: 10_000, } @@ -276,7 +276,7 @@ describe('probingHTTP', () => { url: 'https://example.com', method: 'POST', headers: { 'content-type': 'application/xml' }, - body: { username: 'john@example.com', password: 'secret' } as any, + body: { username: 'john@example.com', password: 'secret' } as never, timeout: 10_000, } @@ -314,7 +314,7 @@ describe('probingHTTP', () => { url: 'https://example.com', method: 'POST', headers: { 'content-type': 'text/plain' }, - body: 'multiline string\nexample' as any, + body: 'multiline string\nexample', timeout: 10_000, allowUnauthorized: true, } @@ -335,9 +335,9 @@ describe('probingHTTP', () => { it('should generate request chaining body', () => { // arrange type TestTable = { - body: Record | string + body: Record | string responses: ProbeRequestResponse[] - expected: Record | string + expected: Record | string } const testTables: TestTable[] = [ { diff --git a/src/components/probe/prober/http/request.ts b/src/components/probe/prober/http/request.ts index 81b35e44d..b1ebb7da3 100644 --- a/src/components/probe/prober/http/request.ts +++ b/src/components/probe/prober/http/request.ts @@ -122,7 +122,7 @@ export async function httpRequest({ if (contentTypeKey) { const { content, contentType } = transformContentByType( - newReq.body, + newReq?.body, (headers || {})[contentTypeKey] ) @@ -233,7 +233,7 @@ export async function httpRequest({ } export function generateRequestChainingBody( - body: JSON | string, + body: object | string, responses: ProbeRequestResponse[] ): JSON | string { const isString = typeof body === 'string' @@ -244,13 +244,13 @@ export function generateRequestChainingBody( } function transformContentByType( - content: any, + content: object | string, contentType?: string | number | boolean ) { switch (contentType) { case 'application/x-www-form-urlencoded': { return { - content: qs.stringify(content), + content: qs.stringify(content as never), contentType, } } @@ -259,7 +259,7 @@ function transformContentByType( const form = new FormData() for (const contentKey of Object.keys(content)) { - form.append(contentKey, content[contentKey]) + form.append(contentKey, (content as Record)[contentKey]) } return { content: form, contentType: form.getHeaders()['content-type'] } diff --git a/src/components/probe/prober/mariadb/index.ts b/src/components/probe/prober/mariadb/index.ts index 8d1b21217..8a3dd75b7 100644 --- a/src/components/probe/prober/mariadb/index.ts +++ b/src/components/probe/prober/mariadb/index.ts @@ -30,9 +30,8 @@ export class MariaDBProber extends BaseProber { } private getConnectionDetails(): string { - const connectionDetails = this.probeConfig?.mariadb - ? this.probeConfig?.mariadb - : this.probeConfig?.mysql + const connectionDetails = + this.probeConfig?.mariadb || this.probeConfig?.mysql return ( connectionDetails diff --git a/src/components/probe/prober/mongo/request.ts b/src/components/probe/prober/mongo/request.ts index c9fd77b44..e9aad5fb9 100644 --- a/src/components/probe/prober/mongo/request.ts +++ b/src/components/probe/prober/mongo/request.ts @@ -132,7 +132,7 @@ async function sendMongoRequest(params: MongoRequest): Promise { try { await client.connect() - client.on('error', (error: any) => { + client.on('error', (error: string | undefined) => { result.message = error }) diff --git a/src/components/probe/prober/postgres/index.ts b/src/components/probe/prober/postgres/index.ts index 5b2126a80..60476de24 100644 --- a/src/components/probe/prober/postgres/index.ts +++ b/src/components/probe/prober/postgres/index.ts @@ -96,10 +96,10 @@ function getPostgresConnectionDetails(postgres: Postgres) { const { database, host, password, port, user } = parse(uri) return { - host: host ?? '0.0.0.0', - port: Number(port) ?? 5432, - database: database ?? '', - username: user ?? '', - password: password ?? '', + host: host || '0.0.0.0', + port: Number(port) || 5432, + database: database || '', + username: user || '', + password: password || '', } } diff --git a/src/components/probe/prober/postgres/request.ts b/src/components/probe/prober/postgres/request.ts index e47aefb84..2007af1fe 100644 --- a/src/components/probe/prober/postgres/request.ts +++ b/src/components/probe/prober/postgres/request.ts @@ -22,7 +22,7 @@ * SOFTWARE. * **********************************************************************************/ -import { Pool } from 'pg' +import { Pool, PoolClient } from 'pg' import type { ProbeRequestResponse } from '../../../../interfaces/request' import { probeRequestResult } from '../../../../interfaces/request' import { differenceInMilliseconds } from 'date-fns' @@ -83,7 +83,7 @@ async function sendPsqlRequest(params: PostgresParam): Promise { message: '', } - let client: any = false + let client: PoolClient | undefined try { const pool = new Pool({ host: params.host, @@ -102,9 +102,9 @@ async function sendPsqlRequest(params: PostgresParam): Promise { } catch (error: unknown) { result.message = getErrorMessage(error) } finally { - if (client !== false) { + if (client) { // release if connect was previously successful. - await client.release(true) + client.release(true) } } diff --git a/src/components/probe/prober/redis/request.ts b/src/components/probe/prober/redis/request.ts index 3bbd18317..ca0cc784b 100644 --- a/src/components/probe/prober/redis/request.ts +++ b/src/components/probe/prober/redis/request.ts @@ -102,7 +102,7 @@ async function sendRedisRequest(params: Redis): Promise { await client.connect() - client.on('error', (error: any) => { + client.on('error', (error: string | undefined) => { result.message = error }) diff --git a/src/components/probe/prober/socket/request.ts b/src/components/probe/prober/socket/request.ts index 9dfc0bf2d..8ee582775 100644 --- a/src/components/probe/prober/socket/request.ts +++ b/src/components/probe/prober/socket/request.ts @@ -45,7 +45,7 @@ type TCPResult = { // tcpRequest sends out the tcp request and returns a monika standard request response export async function tcpRequest( param: TCPRequest -): Promise> { +): Promise> { const { host, port, data, timeout } = param const tcpResp = await tcpCheck({ host, port, data, timeout }) @@ -95,7 +95,7 @@ async function tcpCheck(tcpRequest: TCPRequest): Promise { const SOCKETTIMEOUTMS = 10_000 -async function sendTCP(tcpRequest: TCPRequest): Promise { +async function sendTCP(tcpRequest: TCPRequest): Promise { const { host, port, data, timeout } = tcpRequest return new Promise((resolve, reject) => { @@ -106,7 +106,7 @@ async function sendTCP(tcpRequest: TCPRequest): Promise { client.setTimeout(timeout || SOCKETTIMEOUTMS) client.on('data', (data) => { - resolve(data.toString()) + resolve(data) client.end() }) diff --git a/src/interfaces/request.ts b/src/interfaces/request.ts index 7ed2d47cd..9daba4a88 100644 --- a/src/interfaces/request.ts +++ b/src/interfaces/request.ts @@ -22,7 +22,11 @@ * SOFTWARE. * **********************************************************************************/ -import { AxiosRequestConfig, AxiosRequestHeaders } from 'axios' +import { + AxiosRequestConfig, + AxiosRequestHeaders, + AxiosResponseHeaders, +} from 'axios' import { ProbeAlert } from './probe' // RequestTypes are used to define the type of request that is being made. @@ -45,12 +49,12 @@ export enum probeRequestResult { } // ProbeRequestResponse is used to define the response from a probe requests. -export interface ProbeRequestResponse { +export interface ProbeRequestResponse { requestType?: RequestTypes // is this for http (default) or icmp or others data: T body: T status: number - headers: any + headers: string | AxiosResponseHeaders responseTime: number error?: string // any error message from drivers result: probeRequestResult // did the probe succeed or fail? @@ -61,7 +65,7 @@ export interface RequestConfig extends Omit { id?: string saveBody?: boolean // save response body to db? url: string - body: JSON | string + body: object | string timeout: number // request timeout alerts?: ProbeAlert[] headers?: AxiosRequestHeaders diff --git a/src/interfaces/response.ts b/src/interfaces/response.ts deleted file mode 100644 index 9eb8c53fb..000000000 --- a/src/interfaces/response.ts +++ /dev/null @@ -1,23 +0,0 @@ -/********************************************************************************** - * MIT License * - * * - * Copyright (c) 2021 Hyperjump Technology * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy * - * of this software and associated documentation files (the "Software"), to deal * - * in the Software without restriction, including without limitation the rights * - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included in all * - * copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * - * SOFTWARE. * - **********************************************************************************/ diff --git a/src/loaders/jobs.ts b/src/loaders/jobs.ts index 0e5ca776d..7a26355e2 100644 --- a/src/loaders/jobs.ts +++ b/src/loaders/jobs.ts @@ -21,12 +21,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * * SOFTWARE. * **********************************************************************************/ -import cron from 'node-cron' +import * as cron from 'node-cron' import { tlsChecker } from '../jobs/tls-check' import { checkDBSize } from '../jobs/check-database' import { getConfig } from '../components/config' -export function jobsLoader(): any { +export function jobsLoader() { const config = getConfig() // schedule TLS checker every day at 00:00 cron.schedule('0 0 * * *', tlsChecker) diff --git a/src/plugins/metrics/prometheus/collector.ts b/src/plugins/metrics/prometheus/collector.ts index 9e1a5276f..e4abf04bb 100644 --- a/src/plugins/metrics/prometheus/collector.ts +++ b/src/plugins/metrics/prometheus/collector.ts @@ -142,8 +142,11 @@ export class PrometheusCollector { const { headers, responseTime, status } = response const result = response.result ?? probeRequestResult.unknown const milliSecond = 1000 - const responseTimeInSecond = responseTime / milliSecond ?? 0 - const responseSizeBytes = Number(headers['content-length']) + const responseTimeInSecond = responseTime / milliSecond || 0 + const responseSizeBytes = + typeof headers === 'string' + ? undefined + : Number(headers['content-length']) const labels = { id, name, @@ -177,9 +180,7 @@ export class PrometheusCollector { }) .set(result) resposeTimeCollector?.labels(labels).observe(responseTimeInSecond) - responseSize - ?.labels(labels) - .set(Number.isNaN(responseSizeBytes) ? 0 : responseSizeBytes) + responseSize?.labels(labels).set(responseSizeBytes || 0) } collectTriggeredAlert( diff --git a/src/plugins/validate-response/checkers/__tests__/query-expression.test.ts b/src/plugins/validate-response/checkers/__tests__/query-expression.test.ts index a05786828..bbd935fd2 100644 --- a/src/plugins/validate-response/checkers/__tests__/query-expression.test.ts +++ b/src/plugins/validate-response/checkers/__tests__/query-expression.test.ts @@ -62,7 +62,7 @@ describe('queryExpression', () => { data: '', body: '', status: 200, - headers: { 'content-length': 2000 }, + headers: { 'content-length': '2000' }, responseTime: 200, result: probeRequestResult.success, } diff --git a/src/plugins/validate-response/checkers/query-expression.ts b/src/plugins/validate-response/checkers/query-expression.ts index 17fba2caf..f2fc67e79 100644 --- a/src/plugins/validate-response/checkers/query-expression.ts +++ b/src/plugins/validate-response/checkers/query-expression.ts @@ -34,7 +34,10 @@ import { ProbeRequestResponse } from '../../../interfaces/request' const queryExpression = (res: ProbeRequestResponse, query: string): boolean => { const object = { response: { - size: Number(res.headers['content-length']), + size: + typeof res.headers === 'string' + ? undefined + : Number(res.headers['content-length']), status: res.status, time: res.responseTime, body: res.data, diff --git a/src/symon/index.test.ts b/src/symon/index.test.ts index ac329904f..9c3ea0f5c 100644 --- a/src/symon/index.test.ts +++ b/src/symon/index.test.ts @@ -139,7 +139,7 @@ describe('Symon initiate', () => { symonKey: 'random-key', } as MonikaFlags, }) - let body: any + let body: Record = {} // mock the outgoing requests server.use( rest.post( @@ -239,7 +239,7 @@ describe('Symon initiate', () => { it('should send event to Symon when incident or recovery happens', async () => { // arrange - let body: any + let body: Record = {} server.use( rest.post( 'http://localhost:4000/api/v1/monika/events', diff --git a/src/symon/index.ts b/src/symon/index.ts index db869e2c6..1494200d1 100644 --- a/src/symon/index.ts +++ b/src/symon/index.ts @@ -300,7 +300,8 @@ export default class SymonClient { response: { body: data, headers: typeof headers === 'object' ? headers : {}, - size: headers['content-length'], + size: + typeof headers === 'object' ? headers['content-length'] : undefined, status, // status is http status code time: responseTime, }, diff --git a/src/utils/events.ts b/src/utils/events.ts index 0b7157574..4652b8558 100644 --- a/src/utils/events.ts +++ b/src/utils/events.ts @@ -28,6 +28,7 @@ let em: NodeJS.EventEmitter export const getEventEmitter = (): EventEmitter => { if (!em) { + // eslint-disable-next-line unicorn/prefer-event-target em = new EventEmitter() } diff --git a/src/utils/expression-parser.ts b/src/utils/expression-parser.ts index 83724688d..d44f281ad 100644 --- a/src/utils/expression-parser.ts +++ b/src/utils/expression-parser.ts @@ -53,8 +53,8 @@ export const sanitizeExpression = ( } export const compileExpression = - (expression: string, objectKeys: string[] = []): any => - (obj: any): any => { + (expression: string, objectKeys: string[] = []) => + (obj: object | object[]) => { const sanitizedExpression = sanitizeExpression(expression, objectKeys) return _compileExpression(sanitizedExpression, { diff --git a/src/utils/fakes.ts b/src/utils/fakes.ts index f18721efc..d0a8c984f 100644 --- a/src/utils/fakes.ts +++ b/src/utils/fakes.ts @@ -33,8 +33,12 @@ import { faker } from '@faker-js/faker' * @returns Handlebars-helper-friendly function */ const wrapFunctionWithDefaultAndTransform = - (originFn: any, defaultArgs: any, transformArgs?: (args: any[]) => any) => - (...arg: any) => { + ( + originFn: (...arg: unknown[]) => unknown, + defaultArgs: unknown[], + transformArgs?: (args: unknown[]) => unknown + ) => + (...arg: unknown[]) => { let newArgs = [...arg.slice(0, -1), ...defaultArgs.slice(arg.length - 1)] // If there is transformArgs method, transform the newArgs @@ -68,7 +72,7 @@ const helpers = [ fn: faker.datatype.number, expr: 'number', default: [0, 100], - transformArgs: (args: any[]) => ({ min: args[0], max: args[1] }), + transformArgs: (args: unknown[]) => ({ min: args[0], max: args[1] }), }, { fn: faker.database.mongodbObjectId, expr: 'objectId' }, { fn: faker.internet.httpStatusCode, expr: 'statusCode' }, @@ -95,7 +99,7 @@ export default function registerFakes( handlebarsInstance.registerHelper( helper.expr, wrapFunctionWithDefaultAndTransform( - helper.fn, + helper.fn as (...args: unknown[]) => string, helper.default || [], helper.transformArgs ) diff --git a/src/utils/hash.ts b/src/utils/hash.ts index 040dd0e40..b849eb2b4 100644 --- a/src/utils/hash.ts +++ b/src/utils/hash.ts @@ -24,7 +24,7 @@ import { createHash } from 'crypto' -export const md5Hash = (data: string | Record): string => { +export const md5Hash = (data: string | object): string => { const str = typeof data === 'string' ? data : JSON.stringify(data) return createHash('md5').update(str).digest('hex') } diff --git a/src/utils/ping.ts b/src/utils/ping.ts index 6761b49bf..1639a6a84 100644 --- a/src/utils/ping.ts +++ b/src/utils/ping.ts @@ -30,7 +30,7 @@ export const PING_TIMEOUT_S = 10 // 10 seconds timeout * @param host is a string * @returns result of ping.promise.probe() */ -export async function sendPing(host: string): Promise { - const cleanUrl: any = host.replace(/^https?:\/\//, '') // sanitize url +export async function sendPing(host: string) { + const cleanUrl = host.replace(/^https?:\/\//, '') // sanitize url return ping.promise.probe(cleanUrl, { timeout: PING_TIMEOUT_S }) } diff --git a/src/utils/pino.ts b/src/utils/pino.ts index 7bd82fd89..c536b353e 100644 --- a/src/utils/pino.ts +++ b/src/utils/pino.ts @@ -24,7 +24,7 @@ import fs from 'fs' import path from 'path' -import pino, { transport } from 'pino' +import { pino, transport } from 'pino' export const log = pino(getOptions()) @@ -42,6 +42,9 @@ function getOptions() { ignore: 'hostname,pid,time', hideObject: true, } + + // TODO: Current vercel/pkg is dependent with CommonJS + // eslint-disable-next-line unicorn/prefer-module const project = path.join(__dirname, '../../tsconfig.json') const dev = fs.existsSync(project) diff --git a/src/utils/probe-state.ts b/src/utils/probe-state.ts index 2727d1888..da9f8a518 100644 --- a/src/utils/probe-state.ts +++ b/src/utils/probe-state.ts @@ -26,7 +26,7 @@ import { assign, createMachine, type EventObject, interpret } from 'xstate' import type { Probe } from '../interfaces/probe' -type ProbeStateValue = any +type ProbeStateValue = unknown type ProbeStateContext = { cycle: number diff --git a/src/utils/public-ip.ts b/src/utils/public-ip.ts index 1613a00ba..d3b2306ed 100644 --- a/src/utils/public-ip.ts +++ b/src/utils/public-ip.ts @@ -89,7 +89,7 @@ export async function getPublicNetworkInfo(): Promise { * getPublicIP sends a request to stun server getting IP address * @returns Promise */ -export async function getPublicIp(): Promise { +export async function getPublicIp() { const { flags } = getContext() const time = new Date().toISOString() const isSymonMode = isSymonModeFrom(flags) @@ -111,8 +111,5 @@ export async function getPublicIp(): Promise { } catch { isConnectedToSTUNServer = false log.warn(`${time} STUN Server is temporarily unreachable. Check network.`) - return // couldn't access public stun but resolve and retry } - - return null } diff --git a/test/index.test.ts b/test/index.test.ts index ba573aeea..96286eba2 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -35,8 +35,8 @@ const { resolve } = path chai.use(spies) describe('monika', () => { - let getPublicIPStub: any - let getPublicNetworkInfoStub: any + let getPublicIPStub: sinon.SinonStub + let getPublicNetworkInfoStub: sinon.SinonStub beforeEach(() => { getPublicIPStub = sinon.stub(IpUtil, 'getPublicIp' as never) getPublicNetworkInfoStub = sinon diff --git a/test/json-schema/validate-sample-configs.test.ts b/test/json-schema/validate-sample-configs.test.ts index 391c47e8c..76376f366 100644 --- a/test/json-schema/validate-sample-configs.test.ts +++ b/test/json-schema/validate-sample-configs.test.ts @@ -55,7 +55,7 @@ describe('validate example configs', () => { it('should detect examples that does not conform to the schema', () => { const files = getAllFiles('./config_sample', []) - let sampleFile: any + let sampleFile: unknown for (const file of files) { switch (path.extname(file)) { diff --git a/test/others/change-config-loop.ts b/test/others/change-config-loop.ts index b11a64801..b62ad765b 100644 --- a/test/others/change-config-loop.ts +++ b/test/others/change-config-loop.ts @@ -70,11 +70,11 @@ notifications: ` function changefile() { - writeFileSync('./testchange.yml', changeFile, 'utf-8') + writeFileSync('./testchange.yml', changeFile, 'utf8') } function restorefile() { - writeFileSync('./testchange.yml', initFile, 'utf-8') + writeFileSync('./testchange.yml', initFile, 'utf8') } function sleep(ms: number) { @@ -106,4 +106,4 @@ async function test() { } } -test() +await test() diff --git a/test/others/hide-ip.test.ts b/test/others/hide-ip.test.ts index b6e380484..dab3a58ce 100644 --- a/test/others/hide-ip.test.ts +++ b/test/others/hide-ip.test.ts @@ -38,8 +38,8 @@ chai.use(spies) let interceptor: RequestInterceptor describe('Monika should hide ip unless verbose', () => { - let getPublicIPStub: any - let getPublicNetworkInfoStub: any + let getPublicIPStub: sinon.SinonStub + let getPublicNetworkInfoStub: sinon.SinonStub beforeEach(() => { interceptor = new RequestInterceptor(withDefaultInterceptors)