From 520d00de1d7c202d6287744f48de309d0f606cff Mon Sep 17 00:00:00 2001 From: Drew Davis Date: Mon, 23 Nov 2026 06:10:15 -0500 Subject: [PATCH 1/2] chore(app): Remove mechanical unsafe type assertions Co-Authored-By: Claude Opus 5.5 --- packages/app/package.json | 2 +- .../src/components/__tests__/ColorRulesEditor.test.tsx | 8 +++----- .../app/src/components/__tests__/SourceSelect.test.tsx | 6 +++--- .../src/components/__tests__/sourceSelectUtils.test.tsx | 5 +++-- packages/app/src/setupTests.tsx | 3 +-- .../e2e/features/search/json-viewer-whitespace.spec.ts | 8 ++++---- 6 files changed, 15 insertions(+), 17 deletions(-) diff --git a/packages/app/package.json b/packages/app/package.json index 0f815432e1..1cd36e75e2 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -14,7 +14,7 @@ "build:clickhouse": "NEXT_PUBLIC_IS_LOCAL_MODE=true NEXT_PUBLIC_CLICKHOUSE_BUILD=true next build --webpack && node scripts/prepare-clickhouse-build-export.js", "run:clickhouse": "test -d out && npx rimraf tmp && mkdir tmp && cp -r out tmp/clickstack && echo 'visit http://localhost:3000/clickstack to start' && npx serve tmp -l 3000 || echo 'run build:clickhouse first'", "start": "next start", - "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 199 && yarn run -T oxfmt --check '**/*.{ts,tsx,css,scss}'", + "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 192 && yarn run -T oxfmt --check '**/*.{ts,tsx,css,scss}'", "lint:fix": "yarn run -T oxlint --fix && yarn run -T oxfmt '**/*.{ts,tsx,css,scss}'", "lint:styles": "stylelint **/*/*.{css,scss}", "ci:lint": "yarn lint && yarn tsc --noEmit && yarn lint:styles --quiet", diff --git a/packages/app/src/components/__tests__/ColorRulesEditor.test.tsx b/packages/app/src/components/__tests__/ColorRulesEditor.test.tsx index 70c3a3fad4..caadd2551c 100644 --- a/packages/app/src/components/__tests__/ColorRulesEditor.test.tsx +++ b/packages/app/src/components/__tests__/ColorRulesEditor.test.tsx @@ -1,6 +1,7 @@ import React from 'react'; import { screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; +import { fromAny } from '@total-typescript/shoehorn'; import { ColorRulesEditor, @@ -8,20 +9,17 @@ import { } from '@/components/ColorRulesEditor'; // Stable localIds so tests can reference them by index. -// Uses `as ColorRuleWithId` because spreading Partial over a -// concrete rule base widens the discriminated union in TS's view; the cast is safe -// because callers always supply valid operator/value combinations. function makeRule( overrides: Partial = {}, id = crypto.randomUUID(), ): ColorRuleWithId { - return { + return fromAny>({ localId: id, operator: 'gt', value: 0, color: 'chart-blue', ...overrides, - } as ColorRuleWithId; + }); } describe('ColorRulesEditor', () => { diff --git a/packages/app/src/components/__tests__/SourceSelect.test.tsx b/packages/app/src/components/__tests__/SourceSelect.test.tsx index dcc733df7c..c5ab3b8ada 100644 --- a/packages/app/src/components/__tests__/SourceSelect.test.tsx +++ b/packages/app/src/components/__tests__/SourceSelect.test.tsx @@ -7,7 +7,7 @@ import { } from '@hyperdx/common-utils/dist/types'; import { screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { fromPartial } from '@total-typescript/shoehorn'; +import { fromAny, fromPartial } from '@total-typescript/shoehorn'; import { SourceManagementMenu, @@ -29,13 +29,13 @@ const makeSource = ( kind: SourceKind, overrides: Partial = {}, ): TSource => - ({ + fromAny>({ id, name, kind, connection: 'conn-a', ...overrides, - }) as unknown as TSource; + }); describe('SourceManagementMenu', () => { it('does not render the kebab trigger when no actions are wired', () => { diff --git a/packages/app/src/components/__tests__/sourceSelectUtils.test.tsx b/packages/app/src/components/__tests__/sourceSelectUtils.test.tsx index 899eddd237..f38f23f4cf 100644 --- a/packages/app/src/components/__tests__/sourceSelectUtils.test.tsx +++ b/packages/app/src/components/__tests__/sourceSelectUtils.test.tsx @@ -1,5 +1,6 @@ import { SourceKind, TSource } from '@hyperdx/common-utils/dist/types'; import { renderHook } from '@testing-library/react'; +import { fromAny } from '@total-typescript/shoehorn'; import { firstSourceItemValue, @@ -15,13 +16,13 @@ const makeSource = ( kind: SourceKind, overrides: Partial = {}, ): TSource => - ({ + fromAny>({ id, name, kind, connection: 'conn-a', ...overrides, - }) as unknown as TSource; + }); describe('useSourceKindMap', () => { it('returns an empty map when sources is undefined', () => { diff --git a/packages/app/src/setupTests.tsx b/packages/app/src/setupTests.tsx index 9200b1c174..7461f84da0 100644 --- a/packages/app/src/setupTests.tsx +++ b/packages/app/src/setupTests.tsx @@ -8,8 +8,7 @@ import { render } from '@testing-library/react'; import structuredClone from '@ungap/structured-clone'; import '@testing-library/jest-dom'; -global.TextEncoder = TextEncoder as any; -global.TextDecoder = TextDecoder as any; +Object.assign(global, { TextEncoder, TextDecoder }); /* Mocks for mantine */ class ResizeObserver { diff --git a/packages/app/tests/e2e/features/search/json-viewer-whitespace.spec.ts b/packages/app/tests/e2e/features/search/json-viewer-whitespace.spec.ts index ebc663acc5..e68da1d92d 100644 --- a/packages/app/tests/e2e/features/search/json-viewer-whitespace.spec.ts +++ b/packages/app/tests/e2e/features/search/json-viewer-whitespace.spec.ts @@ -118,10 +118,10 @@ test.describe('JSON Viewer WhiteSpace Toggle', { tag: ['@search'] }, () => { }); // In pre-wrap mode (default): element should wrap, so scrollWidth <= clientWidth of container - const preWrapDimensions = await stringEl.evaluate(el => ({ + const preWrapDimensions = await stringEl.evaluate((el: HTMLElement) => ({ scrollWidth: el.scrollWidth, clientWidth: el.clientWidth, - offsetHeight: (el as HTMLElement).offsetHeight, + offsetHeight: el.offsetHeight, })); // Toggle to pre mode (no wrap) @@ -135,10 +135,10 @@ test.describe('JSON Viewer WhiteSpace Toggle', { tag: ['@search'] }, () => { } }); - const preDimensions = await stringEl.evaluate(el => ({ + const preDimensions = await stringEl.evaluate((el: HTMLElement) => ({ scrollWidth: el.scrollWidth, clientWidth: el.clientWidth, - offsetHeight: (el as HTMLElement).offsetHeight, + offsetHeight: el.offsetHeight, })); // In pre-wrap mode: text should wrap, making the element taller From 15036203f13d182e00f55f37e86c4645adca9466 Mon Sep 17 00:00:00 2001 From: Drew Davis Date: Mon, 23 Nov 2026 06:15:24 -0500 Subject: [PATCH 2/2] chore(api): Remove mechanical unsafe type assertions Co-Authored-By: Claude Opus 5.5 --- packages/api/package.json | 3 +- .../api/src/controllers/__tests__/ai.test.ts | 9 +-- .../__tests__/timeseriesEngine.test.ts | 5 +- .../dashboards/patchDashboard.int.test.ts | 12 ++-- .../__tests__/dashboards/validation.test.ts | 13 ++-- .../__tests__/dashboards/variables.test.ts | 5 +- .../src/mcp/__tests__/deltasTool.int.test.ts | 21 +++---- .../__tests__/describeSourceTimeout.test.ts | 43 +++++++------- packages/api/src/mcp/__tests__/query.test.ts | 2 +- .../api/src/mcp/__tests__/sources.int.test.ts | 8 +-- .../src/middleware/__tests__/error.test.ts | 9 +-- .../routers/api/__tests__/alerts.int.test.ts | 4 +- .../api/__tests__/dashboard.int.test.ts | 8 ++- .../api/__tests__/prometheus.int.test.ts | 41 +++++++------ .../routers/api/__tests__/sources.int.test.ts | 5 +- .../__tests__/dashboards.int.test.ts | 9 +-- .../__tests__/savedSearches-crud.int.test.ts | 9 ++- .../__tests__/sources-crud.int.test.ts | 3 +- .../__tests__/webhooks.int.test.ts | 45 ++++++++------ .../utils/__tests__/alertChartConfig.test.ts | 24 ++++---- .../v2/utils/__tests__/dashboards.test.ts | 5 +- packages/api/src/tasks/__tests__/util.test.ts | 6 +- .../__tests__/checkAlerts.int.test.ts | 59 ++++++++++--------- .../__tests__/checkAlertsTask.test.ts | 59 ++++++++++--------- .../__tests__/renderAlertTemplate.int.test.ts | 11 ++-- .../singleInvocationAlert.int.test.ts | 15 ++--- .../providers/__tests__/default.int.test.ts | 7 ++- .../transports/__tests__/registry.test.ts | 13 ++-- .../__tests__/provisionDashboards.int.test.ts | 25 ++++---- .../src/utils/__tests__/externalApi.test.ts | 5 +- .../src/utils/__tests__/filterSources.test.ts | 3 +- .../utils/__tests__/iacTileAlerts.int.test.ts | 35 ++++++----- .../api/src/utils/__tests__/logParser.test.ts | 4 +- .../api/src/utils/__tests__/retry.test.ts | 22 ++++--- .../src/utils/__tests__/validators.test.ts | 5 +- yarn.lock | 1 + 36 files changed, 301 insertions(+), 252 deletions(-) diff --git a/packages/api/package.json b/packages/api/package.json index e655a31edf..6cd9d59163 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -72,6 +72,7 @@ "devDependencies": { "@opentelemetry/sdk-trace-base": "^2.8.0", "@stoplight/spectral-cli": "^6.15.0", + "@total-typescript/shoehorn": "^0.1.2", "@types/compression": "^1.7.3", "@types/cors": "^2.8.14", "@types/express": "^4.17.13", @@ -106,7 +107,7 @@ "dev-task": "DOTENV_CONFIG_PATH=.env.development nodemon --exec 'ts-node' --transpile-only -r tsconfig-paths/register -r dotenv-expand/config -r ./src/telemetry.ts ./src/tasks/index.ts", "build": "rimraf ./build && tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json && cp -r ./src/opamp/proto ./build/opamp/", "build:vercel": "rimraf ./build && tsc -p tsconfig.vercel.json && tsc-alias -p tsconfig.vercel.json && cp -r ./src/opamp/proto ./build/opamp/", - "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 302 && yarn run -T oxfmt --check 'src/**/*.ts' 'scripts/**/*.ts'", + "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 173 && yarn run -T oxfmt --check 'src/**/*.ts' 'scripts/**/*.ts'", "lint:fix": "yarn run -T oxlint --fix && yarn run -T oxfmt 'src/**/*.ts' 'scripts/**/*.ts'", "ci:lint": "yarn lint && yarn tsc --noEmit && yarn lint:openapi", "ci:unit": "jest --ci --coverage", diff --git a/packages/api/src/controllers/__tests__/ai.test.ts b/packages/api/src/controllers/__tests__/ai.test.ts index 34387aa3ba..b8f985de06 100644 --- a/packages/api/src/controllers/__tests__/ai.test.ts +++ b/packages/api/src/controllers/__tests__/ai.test.ts @@ -1,12 +1,13 @@ +import { fromPartial } from '@total-typescript/shoehorn'; import type { LanguageModel } from 'ai'; -const mockAnthropicModel = { +const mockAnthropicModel: LanguageModel = fromPartial({ modelId: 'claude-sonnet-4-5-20250929', -} as unknown as LanguageModel; +}); -const mockOpenAIModel = { +const mockOpenAIModel: LanguageModel = fromPartial({ modelId: 'gpt-4o', -} as unknown as LanguageModel; +}); const mockAnthropicFactory = jest.fn((_model?: string) => mockAnthropicModel); const mockCreateAnthropic = jest.fn( diff --git a/packages/api/src/controllers/__tests__/timeseriesEngine.test.ts b/packages/api/src/controllers/__tests__/timeseriesEngine.test.ts index 499d2aebc1..04d8694345 100644 --- a/packages/api/src/controllers/__tests__/timeseriesEngine.test.ts +++ b/packages/api/src/controllers/__tests__/timeseriesEngine.test.ts @@ -1,5 +1,6 @@ import { ClickHouseError } from '@clickhouse/client-common'; import { ClickHouseQueryError } from '@hyperdx/common-utils/dist/clickhouse'; +import { fromAny } from '@total-typescript/shoehorn'; import { formatMatrixResponse, @@ -50,7 +51,7 @@ describe('formatMatrixResponse', () => { ] as [string | number, number][], }, ]; - expect(formatMatrixResponse(rows as any)).toEqual([ + expect(formatMatrixResponse(fromAny(rows))).toEqual([ { metric: { __name__: 'http_requests_total', method: 'GET' }, values: [ @@ -72,7 +73,7 @@ describe('formatVectorResponse', () => { { tags: [['service', 'api']], timestamp: 1700000000, value: 42 }, { tags: [], timestamp: '2023-11-14T22:13:20.000Z', value: 3 }, ]; - expect(formatVectorResponse(rows as any)).toEqual([ + expect(formatVectorResponse(fromAny(rows))).toEqual([ { metric: { service: 'api' }, value: [1700000000, '42'] }, { metric: {}, value: [1700000000, '3'] }, ]); diff --git a/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts index 1285ec729f..b1758c53e3 100644 --- a/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts @@ -445,7 +445,7 @@ describe('MCP Dashboard Tools - clickstack_patch_dashboard', () => { // Snapshot the raw tiles from the DB before patching const beforePatch = await Dashboard.findById(dashboardId).lean(); - const tilesBeforePatch = (beforePatch as any).tiles; + const tilesBeforePatch = beforePatch!.tiles; const tileBBefore = tilesBeforePatch[1]; const tileCBefore = tilesBeforePatch[2]; @@ -470,7 +470,7 @@ describe('MCP Dashboard Tools - clickstack_patch_dashboard', () => { // Read raw DB tiles again; tiles B and C should be byte-identical const afterPatch = await Dashboard.findById(dashboardId).lean(); - const tilesAfterPatch = (afterPatch as any).tiles; + const tilesAfterPatch = afterPatch!.tiles; expect(tilesAfterPatch).toHaveLength(3); // Tile B (index 1) and Tile C (index 2) should be untouched @@ -943,10 +943,10 @@ describe('MCP Dashboard Tools - clickstack_patch_dashboard', () => { const output = JSON.parse(getFirstText(patchResult)); expect(output.patchedTile.name).toBe('Static SQL'); const dashboard = await Dashboard.findById(created.id); - const persistedConfig = dashboard?.tiles?.[0]?.config as { - sqlTemplate?: string; - }; - expect(persistedConfig?.sqlTemplate).toBe('SELECT 1 AS value LIMIT 1'); + expect(dashboard?.tiles?.[0]?.config).toHaveProperty( + 'sqlTemplate', + 'SELECT 1 AS value LIMIT 1', + ); expect(Array.isArray(output.warnings)).toBe(true); expect(output.warnings).toHaveLength(1); diff --git a/packages/api/src/mcp/__tests__/dashboards/validation.test.ts b/packages/api/src/mcp/__tests__/dashboards/validation.test.ts index 31ab9695fd..08e4a307c6 100644 --- a/packages/api/src/mcp/__tests__/dashboards/validation.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/validation.test.ts @@ -1,4 +1,5 @@ import { DASHBOARD_VARIABLE_NAME_MAX_LENGTH } from '@hyperdx/common-utils/dist/types'; +import { fromAny } from '@total-typescript/shoehorn'; import mongoose from 'mongoose'; import { @@ -64,7 +65,7 @@ function makeSqlTile(overrides: { sourceId?: string; displayType?: string; }): ExternalDashboardTileWithId { - return { + return fromAny({ id: 'sql-tile', x: 0, y: 0, @@ -78,7 +79,7 @@ function makeSqlTile(overrides: { sqlTemplate: overrides.sqlTemplate, ...(overrides.sourceId ? { sourceId: overrides.sourceId } : {}), }, - } as ExternalDashboardTileWithId; + }); } describe('tile-level where rejection (builder tiles)', () => { @@ -251,7 +252,7 @@ describe('getRawSqlTilesMissingRequiredSource', () => { }); it('ignores builder (non-SQL) tiles entirely', () => { - const builderTile = { + const builderTile: ExternalDashboardTileWithId = fromAny({ id: 'builder', x: 0, y: 0, @@ -263,7 +264,7 @@ describe('getRawSqlTilesMissingRequiredSource', () => { sourceId, select: [{ aggFn: 'count', valueExpression: '', where: '' }], }, - } as unknown as ExternalDashboardTileWithId; + }); expect(getRawSqlTilesMissingRequiredSource([builderTile])).toEqual([]); }); @@ -433,7 +434,7 @@ describe('getRawSqlTileMacroHints', () => { }); it('ignores builder (non-SQL) tiles entirely', () => { - const builderTile = { + const builderTile: ExternalDashboardTileWithId = fromAny({ id: 'builder', x: 0, y: 0, @@ -445,7 +446,7 @@ describe('getRawSqlTileMacroHints', () => { sourceId, select: [{ aggFn: 'count', valueExpression: '', where: '' }], }, - } as unknown as ExternalDashboardTileWithId; + }); expect(getRawSqlTileMacroWarnings([builderTile])).toEqual([]); }); diff --git a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts index 9d5e0e45a2..d50a56e33d 100644 --- a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts @@ -1,4 +1,5 @@ import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { fromAny } from '@total-typescript/shoehorn'; import mongoose from 'mongoose'; import { @@ -17,7 +18,7 @@ const sourceId = new mongoose.Types.ObjectId().toString(); function filter( overrides: Partial = {}, ): ExternalDashboardFilterWithId { - return { + return fromAny({ id: new mongoose.Types.ObjectId().toString(), type: 'QUERY_EXPRESSION', name: 'Service', @@ -25,7 +26,7 @@ function filter( sourceId, whereLanguage: 'sql', ...overrides, - } as ExternalDashboardFilterWithId; + }); } const variableFilter = filter({ diff --git a/packages/api/src/mcp/__tests__/deltasTool.int.test.ts b/packages/api/src/mcp/__tests__/deltasTool.int.test.ts index 345b020081..a805b17daa 100644 --- a/packages/api/src/mcp/__tests__/deltasTool.int.test.ts +++ b/packages/api/src/mcp/__tests__/deltasTool.int.test.ts @@ -186,23 +186,16 @@ describe('MCP Event Deltas Tool', () => { expect(severity.baseline).toBeUndefined(); expect(severity.targetCount).toBeGreaterThan(0); expect(severity.baselineCount).toBeGreaterThan(0); - const errorDelta = ( - severity.topDeltas as Array<{ - value: string; - targetPct: number; - baselinePct: number; - }> - ).find(v => v.value === 'ERROR'); + const topDeltas: Array<{ + value: string; + targetPct: number; + baselinePct: number; + }> = severity.topDeltas; + const errorDelta = topDeltas.find(v => v.value === 'ERROR'); expect(errorDelta).toBeDefined(); // Target window planted ERROR, baseline window planted INFO. expect(errorDelta!.targetPct).toBeGreaterThan(errorDelta!.baselinePct); - const infoDelta = ( - severity.topDeltas as Array<{ - value: string; - targetPct: number; - baselinePct: number; - }> - ).find(v => v.value === 'INFO'); + const infoDelta = topDeltas.find(v => v.value === 'INFO'); expect(infoDelta).toBeDefined(); expect(infoDelta!.baselinePct).toBeGreaterThan(infoDelta!.targetPct); }); diff --git a/packages/api/src/mcp/__tests__/describeSourceTimeout.test.ts b/packages/api/src/mcp/__tests__/describeSourceTimeout.test.ts index f06bde491c..8e33f47f69 100644 --- a/packages/api/src/mcp/__tests__/describeSourceTimeout.test.ts +++ b/packages/api/src/mcp/__tests__/describeSourceTimeout.test.ts @@ -26,6 +26,7 @@ jest.mock('@/utils/trimToolResponse', () => ({ })); import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { fromAny, fromPartial } from '@total-typescript/shoehorn'; import { getConnectionById } from '@/controllers/connection'; import { getPromqlLabelCatalog } from '@/controllers/promql'; @@ -36,7 +37,7 @@ import { registerDescribeSource, } from '@/mcp/tools/sources/describeSource'; import { sampleMetricNamesWithLookback } from '@/mcp/tools/sources/metricNames'; -import type { ToolRegistrar, ToolResult } from '@/mcp/tools/types'; +import type { ToolResult } from '@/mcp/tools/types'; const COLUMNS = [ { name: 'Timestamp', type: 'DateTime64(9)' }, @@ -81,13 +82,15 @@ const rejectOnAbort = (signal: AbortSignal) => function getHandler() { let handler: ((args: { sourceId: string }) => Promise) | null = null; - registerDescribeSource({ - server: {}, - context: { teamId: 'team-1', userId: 'user-1', promqlEnabled: true }, - registerTool: (_name: string, _config: unknown, h: typeof handler) => { - handler = h; - }, - } as unknown as ToolRegistrar); + registerDescribeSource( + fromAny({ + server: {}, + context: { teamId: 'team-1', userId: 'user-1', promqlEnabled: true }, + registerTool: (_name: string, _config: unknown, h: typeof handler) => { + handler = h; + }, + }), + ); return handler!; } @@ -102,16 +105,14 @@ const parse = (result: ToolResult) => JSON.parse(result.content[0].text); describe('clickstack_describe_source deadline', () => { beforeEach(() => { jest.useFakeTimers(); - jest - .mocked(getSource) - .mockResolvedValue( - traceSource as unknown as Awaited>, - ); - jest.mocked(getConnectionById).mockResolvedValue({ - host: 'http://localhost:8123', - username: 'default', - password: '', - } as unknown as Awaited>); + jest.mocked(getSource).mockResolvedValue(fromAny(traceSource)); + jest.mocked(getConnectionById).mockResolvedValue( + fromPartial({ + host: 'http://localhost:8123', + username: 'default', + password: '', + }), + ); mockMetadata.getColumns.mockResolvedValue(COLUMNS); mockMetadata.getMapKeys.mockResolvedValue(['http.method']); mockMetadata.getAllKeyValues.mockResolvedValue([ @@ -297,11 +298,7 @@ describe('clickstack_describe_source deadline', () => { describe('metric sources', () => { beforeEach(() => { - jest - .mocked(getSource) - .mockResolvedValue( - metricSource as unknown as Awaited>, - ); + jest.mocked(getSource).mockResolvedValue(fromAny(metricSource)); mockMetadata.getColumns.mockResolvedValue([ { name: 'TimeUnix', type: 'DateTime64(9)' }, { name: 'MetricName', type: 'LowCardinality(String)' }, diff --git a/packages/api/src/mcp/__tests__/query.test.ts b/packages/api/src/mcp/__tests__/query.test.ts index 3789da7f2e..dc64e1ade7 100644 --- a/packages/api/src/mcp/__tests__/query.test.ts +++ b/packages/api/src/mcp/__tests__/query.test.ts @@ -688,7 +688,7 @@ describe('isServerError', () => { const a = new Error('a'); const b = new Error('b', { cause: a }); // Create circular reference: a.cause -> b -> a -> ... - (a as any).cause = b; + a.cause = b; // Should terminate and return false (no server error codes) expect(isServerError(a)).toBe(false); }); diff --git a/packages/api/src/mcp/__tests__/sources.int.test.ts b/packages/api/src/mcp/__tests__/sources.int.test.ts index 3f710f1694..a72dd60777 100644 --- a/packages/api/src/mcp/__tests__/sources.int.test.ts +++ b/packages/api/src/mcp/__tests__/sources.int.test.ts @@ -962,10 +962,10 @@ describe('MCP Source Tools', () => { expect(second.isError).toBeFalsy(); const secondOutput = JSON.parse(getFirstText(second)); // The second page must not repeat the first page's last name. - const firstNames = new Set( - (firstOutput.metrics as { name: string }[]).map(m => m.name), - ); - for (const entry of secondOutput.metrics as { name: string }[]) { + const firstMetrics: { name: string }[] = firstOutput.metrics; + const secondMetrics: { name: string }[] = secondOutput.metrics; + const firstNames = new Set(firstMetrics.map(m => m.name)); + for (const entry of secondMetrics) { expect(firstNames.has(entry.name)).toBe(false); } }); diff --git a/packages/api/src/middleware/__tests__/error.test.ts b/packages/api/src/middleware/__tests__/error.test.ts index 3427ff64ea..df7cd14242 100644 --- a/packages/api/src/middleware/__tests__/error.test.ts +++ b/packages/api/src/middleware/__tests__/error.test.ts @@ -1,4 +1,5 @@ -import type { Request, Response } from 'express'; +import { fromAny, fromPartial } from '@total-typescript/shoehorn'; +import type { Response } from 'express'; // --- mocks (hoisted; names must be prefixed with `mock`) --- const mockCounterAdd = jest.fn(); @@ -27,12 +28,12 @@ import { appErrorHandler } from '@/middleware/error'; import { Api404Error } from '@/utils/errors'; const invoke = (err: unknown): Response => { - const res = { + const res: Response = fromPartial({ headersSent: false, status: jest.fn().mockReturnThis(), json: jest.fn(), - } as unknown as Response; - appErrorHandler(err as any, {} as Request, res, jest.fn()); + }); + appErrorHandler(fromAny(err), fromPartial({}), res, jest.fn()); return res; }; diff --git a/packages/api/src/routers/api/__tests__/alerts.int.test.ts b/packages/api/src/routers/api/__tests__/alerts.int.test.ts index 763a4806e2..4e77efdfdb 100644 --- a/packages/api/src/routers/api/__tests__/alerts.int.test.ts +++ b/packages/api/src/routers/api/__tests__/alerts.int.test.ts @@ -1411,7 +1411,7 @@ describe('alerts router', () => { }); describe('GET /alerts/:id/history', () => { - const createTileAlert = async () => { + const createTileAlert = async (): Promise => { const dashboard = await agent .post('/dashboards') .send(MOCK_DASHBOARD) @@ -1426,7 +1426,7 @@ describe('alerts router', () => { }), ) .expect(200); - return alert.body.data._id as string; + return alert.body.data._id; }; it('returns firing and recovery transitions within the range', async () => { diff --git a/packages/api/src/routers/api/__tests__/dashboard.int.test.ts b/packages/api/src/routers/api/__tests__/dashboard.int.test.ts index 3f516bf17d..9b4fbb1dc9 100644 --- a/packages/api/src/routers/api/__tests__/dashboard.int.test.ts +++ b/packages/api/src/routers/api/__tests__/dashboard.int.test.ts @@ -6,6 +6,7 @@ import { SourceKind, TSource, } from '@hyperdx/common-utils/dist/types'; +import { fromAny } from '@total-typescript/shoehorn'; import { omit } from 'lodash'; import mongoose, { Types } from 'mongoose'; @@ -100,7 +101,7 @@ describe('dashboard router', () => { const tileWithLegacyColor = makeTile(); tileWithLegacyColor.config = { ...tileWithLegacyColor.config, - color: 'chart-1' as any, + color: fromAny('chart-1'), }; const created = await agent @@ -151,7 +152,10 @@ describe('dashboard router', () => { // PATCH, so a follow-up no-op PATCH would surface a regression. it('returns hue-named tokens on GET (list) for a Mongo-seeded legacy chart-N tile', async () => { const tileWithLegacy = makeTile(); - (tileWithLegacy.config as any).color = 'chart-1'; + tileWithLegacy.config = { + ...tileWithLegacy.config, + color: fromAny('chart-1'), + }; const seeded = await Dashboard.create({ name: 'Pre-rename Dashboard', team: team._id, diff --git a/packages/api/src/routers/api/__tests__/prometheus.int.test.ts b/packages/api/src/routers/api/__tests__/prometheus.int.test.ts index 3c67422fa2..3611814701 100644 --- a/packages/api/src/routers/api/__tests__/prometheus.int.test.ts +++ b/packages/api/src/routers/api/__tests__/prometheus.int.test.ts @@ -7,6 +7,7 @@ import { type PromqlSourceBackend, SourceKind, } from '@hyperdx/common-utils/dist/types'; +import { fromPartial } from '@total-typescript/shoehorn'; import { Types } from 'mongoose'; import * as config from '@/config'; @@ -55,14 +56,14 @@ function fakeUpstreamResponse( controller.close(); }, }); - return { + return fromPartial({ ok: status >= 200 && status < 300, status, headers: new Headers({ 'content-type': contentType }), body, text: jest.fn().mockResolvedValue(JSON.stringify(payload)), json: jest.fn().mockResolvedValue(payload), - } as unknown as Response; + }); } // What ClickHouse's prometheus_api_v1 handler answers the router's @@ -529,7 +530,7 @@ describe('prometheus router', () => { .expect(200); expect(mockFetch).toHaveBeenCalledTimes(1); - expect(mockFetch.mock.calls[0][0] as string).toMatch( + expect(String(mockFetch.mock.calls[0][0])).toMatch( /^http:\/\/vmselect:8481\/select\/0\/prometheus\/api\/v1\/query_range/, ); }); @@ -594,7 +595,7 @@ describe('prometheus router', () => { }) .expect(200); - const requested = new URL(mockFetch.mock.calls[0][0] as string); + const requested = new URL(String(mockFetch.mock.calls[0][0])); expect(requested.searchParams.get('extra_label')).toBe('namespace=prod'); expect(requested.searchParams.get('query')).toBe('up'); }); @@ -629,7 +630,7 @@ describe('prometheus router', () => { }) .expect(200); - const requested = new URL(mockFetch.mock.calls[0][0] as string); + const requested = new URL(String(mockFetch.mock.calls[0][0])); expect(requested.searchParams.get('query')).toBe('up'); }); @@ -664,7 +665,7 @@ describe('prometheus router', () => { }) .expect(200); - const requested = new URL(mockFetch.mock.calls[0][0] as string); + const requested = new URL(String(mockFetch.mock.calls[0][0])); expect(requested.searchParams.get('timeout')).toBe('30s'); }); @@ -697,7 +698,7 @@ describe('prometheus router', () => { }) .expect(200); - const requested = new URL(mockFetch.mock.calls[0][0] as string); + const requested = new URL(String(mockFetch.mock.calls[0][0])); expect(requested.searchParams.get('stats')).toBe('none'); }); @@ -734,7 +735,7 @@ describe('prometheus router', () => { }) .expect(200); - const requested = new URL(mockFetch.mock.calls[0][0] as string); + const requested = new URL(String(mockFetch.mock.calls[0][0])); expect(requested.searchParams.get('extra_label')).toBe('namespace=prod'); expect(requested.searchParams.get('query')).toBe('up'); }); @@ -764,7 +765,7 @@ describe('prometheus router', () => { }) .expect(200); - const requested = new URL(mockFetch.mock.calls[0][0] as string); + const requested = new URL(String(mockFetch.mock.calls[0][0])); expect(requested.searchParams.get('step')).toBe('15s'); }); @@ -920,14 +921,16 @@ describe('prometheus router', () => { tableName: 'no_such_table_for_fallback', }); // A stock ClickHouse answers the probe with a plain-text 404. - mockFetch.mockResolvedValueOnce({ - status: 404, - text: jest - .fn() - .mockResolvedValue( - 'There is no handle /prometheus/api/v1/format_query', - ), - } as unknown as Response); + mockFetch.mockResolvedValueOnce( + fromPartial({ + status: 404, + text: jest + .fn() + .mockResolvedValue( + 'There is no handle /prometheus/api/v1/format_query', + ), + }), + ); const res = await agent .get('/v1/prometheus/query_range') @@ -2531,7 +2534,7 @@ describe('prometheus router', () => { }) .expect(200); - const requested = new URL(mockFetch.mock.calls[0][0] as string); + const requested = new URL(String(mockFetch.mock.calls[0][0])); const sentStart = Number(requested.searchParams.get('start')); expect(Number(requested.searchParams.get('end'))).toBe(end); expect(sentStart).toBeGreaterThan(end - thirtyDays); @@ -2565,7 +2568,7 @@ describe('prometheus router', () => { }) .expect(200); - const requested = new URL(mockFetch.mock.calls[0][0] as string); + const requested = new URL(String(mockFetch.mock.calls[0][0])); const sentStart = Number(requested.searchParams.get('start')); expect(Number(requested.searchParams.get('end'))).toBe(end); expect(end - sentStart).toBe(PROMETHEUS_MAX_EXEMPLAR_WINDOW_SEC); diff --git a/packages/api/src/routers/api/__tests__/sources.int.test.ts b/packages/api/src/routers/api/__tests__/sources.int.test.ts index 9b4ca14c43..39a5550d96 100644 --- a/packages/api/src/routers/api/__tests__/sources.int.test.ts +++ b/packages/api/src/routers/api/__tests__/sources.int.test.ts @@ -3,6 +3,7 @@ import { TSource, UseTextIndex, } from '@hyperdx/common-utils/dist/types'; +import { fromAny } from '@total-typescript/shoehorn'; import express from 'express'; import mongoose, { Types } from 'mongoose'; import request from 'supertest'; @@ -1319,11 +1320,11 @@ describe('sources router', () => { const app = express(); app.use(express.json()); app.use((req, _res, next) => { - req.user = { + req.user = fromAny({ _id: '_local_user_', email: 'local-user@hyperdx.io', team: LOCAL_APP_TEAM_ID, - } as unknown as Express.User; + }); next(); }); app.use('/sources', sourcesRouter); diff --git a/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts index 5c53b3f1ee..92ee40d569 100644 --- a/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts @@ -3326,7 +3326,7 @@ describe('External API v2 Dashboards - new format', () => { response.body.data.id, ).lean(); - expect((dashboardInDb!.tiles[0].config as any).where).toBe(''); + expect(dashboardInDb!.tiles[0].config).toHaveProperty('where', ''); }); it('persists select-item where as empty string when omitted', async () => { @@ -3355,9 +3355,10 @@ describe('External API v2 Dashboards - new format', () => { response.body.data.id, ).lean(); - expect( - (dashboardInDb!.tiles[0].config as any).select[0].aggCondition, - ).toBe(''); + expect(dashboardInDb!.tiles[0].config).toHaveProperty( + ['select', 0, 'aggCondition'], + '', + ); }); it('does not silently downgrade a corrupted heatmap to line on GET', async () => { diff --git a/packages/api/src/routers/external-api/__tests__/savedSearches-crud.int.test.ts b/packages/api/src/routers/external-api/__tests__/savedSearches-crud.int.test.ts index bdca00deb8..505b95d838 100644 --- a/packages/api/src/routers/external-api/__tests__/savedSearches-crud.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/savedSearches-crud.int.test.ts @@ -1,4 +1,5 @@ import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { fromAny } from '@total-typescript/shoehorn'; import mongoose from 'mongoose'; import request, { SuperAgentTest } from 'supertest'; @@ -585,9 +586,11 @@ describe('External API v2 Saved Searches CRUD', () => { .mockImplementation(() => {}); const deleteSpy = jest .spyOn(SavedSearch, 'deleteOne') - .mockImplementationOnce((() => { - throw new Error('simulated deleteOne failure'); - }) as any); + .mockImplementationOnce( + fromAny(() => { + throw new Error('simulated deleteOne failure'); + }), + ); try { await authRequest('delete', `${BASE_URL}/${savedSearchId}`).expect(500); diff --git a/packages/api/src/routers/external-api/__tests__/sources-crud.int.test.ts b/packages/api/src/routers/external-api/__tests__/sources-crud.int.test.ts index d188607f9f..a2b1f7474f 100644 --- a/packages/api/src/routers/external-api/__tests__/sources-crud.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/sources-crud.int.test.ts @@ -1,4 +1,5 @@ import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { fromAny } from '@total-typescript/shoehorn'; import mongoose from 'mongoose'; import request, { SuperAgentTest } from 'supertest'; @@ -553,7 +554,7 @@ describe('External API v2 Sources CRUD', () => { .spyOn(Source.collection, 'replaceOne') .mockImplementationOnce(async () => { await Source.deleteOne({ _id: logSource._id }); - return { matchedCount: 0 } as any; + return fromAny({ matchedCount: 0 }); }); try { diff --git a/packages/api/src/routers/external-api/__tests__/webhooks.int.test.ts b/packages/api/src/routers/external-api/__tests__/webhooks.int.test.ts index b5370a7b50..2e445e951f 100644 --- a/packages/api/src/routers/external-api/__tests__/webhooks.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/webhooks.int.test.ts @@ -1,4 +1,5 @@ import { WebhookService } from '@hyperdx/common-utils/dist/types'; +import { fromAny } from '@total-typescript/shoehorn'; import { ObjectId } from 'mongodb'; import request, { SuperAgentTest } from 'supertest'; @@ -305,11 +306,13 @@ describe('External API v2 Webhooks', () => { // fails externalWebhookSchema parsing on read. meta.total counts every // stored row (countDocuments) while data drops the unparseable one, so // data.length can be less than meta.total — this documents that skew. - await Webhook.collection.insertOne({ - team: team._id, - name: 'Broken Webhook', - service: 'not-a-real-service', - } as any); + await Webhook.collection.insertOne( + fromAny({ + team: team._id, + name: 'Broken Webhook', + service: 'not-a-real-service', + }), + ); const response = await authRequest('get', WEBHOOKS_BASE_URL).expect(200); @@ -847,14 +850,17 @@ describe('External API v2 Webhooks', () => { team: team._id, }); - const spy = jest.spyOn(Webhook, 'findOne').mockImplementationOnce((() => - (async () => { - await Webhook.updateOne( - { _id: created._id }, - { $set: { url: 'https://example.com/moved-concurrently' } }, - ); - return staleDoc; - })()) as any); + const spy = jest.spyOn(Webhook, 'findOne').mockImplementationOnce( + fromAny(() => + (async () => { + await Webhook.updateOne( + { _id: created._id }, + { $set: { url: 'https://example.com/moved-concurrently' } }, + ); + return staleDoc; + })(), + ), + ); try { const response = await authRequest( @@ -890,11 +896,14 @@ describe('External API v2 Webhooks', () => { team: team._id, }); - const spy = jest.spyOn(Webhook, 'findOne').mockImplementationOnce((() => - (async () => { - await Webhook.deleteOne({ _id: created._id }); - return staleDoc; - })()) as any); + const spy = jest.spyOn(Webhook, 'findOne').mockImplementationOnce( + fromAny(() => + (async () => { + await Webhook.deleteOne({ _id: created._id }); + return staleDoc; + })(), + ), + ); try { await authRequest('put', `${WEBHOOKS_BASE_URL}/${created._id}`) diff --git a/packages/api/src/routers/external-api/v2/utils/__tests__/alertChartConfig.test.ts b/packages/api/src/routers/external-api/v2/utils/__tests__/alertChartConfig.test.ts index 0760ea36b8..1b83ead663 100644 --- a/packages/api/src/routers/external-api/v2/utils/__tests__/alertChartConfig.test.ts +++ b/packages/api/src/routers/external-api/v2/utils/__tests__/alertChartConfig.test.ts @@ -2,7 +2,9 @@ import { AlertChartConfig, AlertChartConfigSchema, DisplayType, + MetricsDataType, } from '@hyperdx/common-utils/dist/types'; +import { fromAny } from '@total-typescript/shoehorn'; import { convertAlertChartConfigToExternal, @@ -142,13 +144,13 @@ describe('convertExternalAlertChartConfigToInternal', () => { where: 'level:error', whereLanguage: 'lucene', alias: 'CPU', - metricType: 'gauge', + metricType: MetricsDataType.Gauge, metricName: 'system.cpu.utilization', periodAggFn: 'delta', }, countItem(), ], - } as ExternalAlertChartConfig); + }); expect(internal).toMatchObject({ displayType: DisplayType.Line, @@ -189,7 +191,7 @@ describe('convertExternalAlertChartConfigToInternal', () => { describe('external <-> internal round-trip', () => { it('round-trips a builder line config, including alert-only and metric fields', () => { - const external = { + const external: ExternalAlertChartConfig = { displayType: DisplayType.Line, sourceId: SOURCE_ID, name: 'Error Rate Query', @@ -207,13 +209,13 @@ describe('external <-> internal round-trip', () => { where: 'level:error', whereLanguage: 'lucene' as const, alias: 'CPU', - metricType: 'gauge' as const, + metricType: MetricsDataType.Gauge, metricName: 'system.cpu.utilization', periodAggFn: 'delta' as const, }, countItem(), ], - } as ExternalAlertChartConfig; + }; const roundTripped = convertAlertChartConfigToExternal( convertExternalAlertChartConfigToInternal(external), @@ -591,11 +593,13 @@ describe('convertAlertChartConfigToExternal', () => { ), ).toBeUndefined(); expect( - convertAlertChartConfigToExternal({ - configType: 'promql', - promqlQuery: 'up', - source: SOURCE_ID, - } as unknown as AlertChartConfig), + convertAlertChartConfigToExternal( + fromAny({ + configType: 'promql', + promqlQuery: 'up', + source: SOURCE_ID, + }), + ), ).toBeUndefined(); }); }); diff --git a/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts b/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts index 200f6f26bb..6f6b59441f 100644 --- a/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts +++ b/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts @@ -10,6 +10,7 @@ import { PromqlSavedChartConfig, SourceKind, } from '@hyperdx/common-utils/dist/types'; +import { fromAny } from '@total-typescript/shoehorn'; import mongoose from 'mongoose'; import { z } from 'zod'; @@ -368,7 +369,7 @@ describe('collectTileContainerRefIssues', () => { // loosely typed so a fixture can model that; the read-path heal is what these // tests are about. function makeDoc(overrides: Record = {}): DashboardDocument { - return { + return fromAny({ _id: new mongoose.Types.ObjectId(), name: 'Test', tiles: [], @@ -378,7 +379,7 @@ function makeDoc(overrides: Record = {}): DashboardDocument { savedQueryLanguage: null, savedFilterValues: [], ...overrides, - } as unknown as DashboardDocument; + }); } function makeTile( diff --git a/packages/api/src/tasks/__tests__/util.test.ts b/packages/api/src/tasks/__tests__/util.test.ts index 9a0d6c3b63..596346a337 100644 --- a/packages/api/src/tasks/__tests__/util.test.ts +++ b/packages/api/src/tasks/__tests__/util.test.ts @@ -1,3 +1,5 @@ +import { fromAny } from '@total-typescript/shoehorn'; + import { calcAlertDateRange, escapeJsonString, @@ -74,10 +76,10 @@ describe('util', () => { }); it('should handle null and undefined values', () => { - expect(unflattenObject({ 'foo.bar': null as any })).toEqual({ + expect(unflattenObject({ 'foo.bar': fromAny(null) })).toEqual({ foo: { bar: null }, }); - expect(unflattenObject({ 'foo.bar': undefined as any })).toEqual({ + expect(unflattenObject({ 'foo.bar': fromAny(undefined) })).toEqual({ foo: { bar: undefined }, }); }); diff --git a/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts index f7b93557a1..c00fba76ba 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts @@ -8,6 +8,7 @@ import { Tile, WebhookService, } from '@hyperdx/common-utils/dist/types'; +import { fromAny, fromPartial } from '@total-typescript/shoehorn'; import mongoose from 'mongoose'; import ms from 'ms'; import { z } from 'zod'; @@ -1113,8 +1114,8 @@ describe('checkAlerts', () => { }> = {}, ): AlertDetails => { const base = { - alert: { groupBy: overrides.alertGroupBy } as any, - source: {} as any, + alert: fromPartial({ groupBy: overrides.alertGroupBy }), + source: fromPartial({}), previousMap: new Map(), }; @@ -1122,10 +1123,10 @@ describe('checkAlerts', () => { return { ...base, taskType: AlertTaskType.TILE, - tile: { + tile: fromPartial({ config: { groupBy: overrides.tileGroupBy ?? '' }, - } as any, - dashboard: {} as any, + }), + dashboard: fromPartial({}), }; } @@ -1143,7 +1144,7 @@ describe('checkAlerts', () => { return { ...base, taskType: AlertTaskType.SAVED_SEARCH, - savedSearch: {} as any, + savedSearch: fromPartial({}), }; }; @@ -1277,15 +1278,15 @@ describe('checkAlerts', () => { defaultTableSelectExpression: 'Timestamp, Body', }, savedSearch: { - _id: 'fake-saved-search-id' as any, - team: 'team-123' as any, + _id: fromAny('fake-saved-search-id'), + team: fromAny('team-123'), id: 'fake-saved-search-id', name: 'My Search', select: 'Body', where: 'Body: "error"', whereLanguage: 'lucene', orderBy: 'timestamp', - source: 'fake-source-id' as any, + source: fromAny('fake-source-id'), tags: ['test'], createdAt: new Date(), updatedAt: new Date(), @@ -1317,7 +1318,7 @@ describe('checkAlerts', () => { id: 'id-123', name: 'My Dashboard', tiles: [testTile], - team: 'team-123' as any, + team: fromAny('team-123'), tags: ['test'], createdAt: new Date(), updatedAt: new Date(), @@ -1362,7 +1363,7 @@ describe('checkAlerts', () => { beforeEach(async () => { jest .spyOn(slack, 'postMessageToWebhook') - .mockResolvedValueOnce(null as any); + .mockResolvedValueOnce(fromAny(null)); }); afterEach(async () => { @@ -2023,7 +2024,7 @@ describe('checkAlerts', () => { jest .spyOn(slack, 'postMessageToWebhook') - .mockResolvedValueOnce(null as any); + .mockResolvedValueOnce(fromAny(null)); jest.spyOn(checkAlert, 'handleSendGenericWebhook'); }); @@ -3072,7 +3073,9 @@ describe('checkAlerts', () => { it('INLINE alert (group by) - notifies per group', async () => { // Two groups fire, so two notifications go out (the shared beforeEach // only mocks a single call). - jest.spyOn(slack, 'postMessageToWebhook').mockResolvedValue(null as any); + jest + .spyOn(slack, 'postMessageToWebhook') + .mockResolvedValue(fromAny(null)); const { team, @@ -3246,7 +3249,7 @@ describe('checkAlerts', () => { webhookSettings: Partial; }> = {}) => { const fixture = await setupSavedSearchAlertTest({ - webhookSettings: webhookSettings as IWebhook, + webhookSettings, }); const dashboard = await new Dashboard({ name: 'Errors Dashboard', @@ -4183,7 +4186,7 @@ describe('checkAlerts', () => { headers: status === 302 ? { Location: redirectTarget } : {}, }); }); - global.fetch = fetchMock as any; + global.fetch = fetchMock; const { team, @@ -4396,7 +4399,7 @@ describe('checkAlerts', () => { status: 500, text: jest.fn().mockResolvedValue('resolve send failed'), }); - global.fetch = fetchMock as any; + global.fetch = fetchMock; const { team, @@ -4571,7 +4574,7 @@ describe('checkAlerts', () => { status: 500, text: jest.fn().mockResolvedValue('group webhook failed'), }); - global.fetch = fetchMock as any; + global.fetch = fetchMock; const { team, @@ -4588,7 +4591,7 @@ describe('checkAlerts', () => { name: 'Generic Webhook', description: 'generic webhook', body: JSON.stringify({ text: '{{title}}' }), - } as IWebhook, + }, }); const now = new Date('2023-11-16T22:12:00.000Z'); @@ -5073,7 +5076,7 @@ describe('checkAlerts', () => { url: 'https://webhook.site/no-body', name: 'Bodyless Generic Webhook', // Intentionally no `body`. - } as IWebhook, + }, }); const now = new Date('2023-11-16T22:12:00.000Z'); @@ -6930,9 +6933,9 @@ describe('checkAlerts', () => { expect(slack.postMessageToWebhook).toHaveBeenCalledTimes(4); // Verify the resolution notification was sent for service-b - const calls = (slack.postMessageToWebhook as jest.Mock).mock.calls; + const calls = jest.mocked(slack.postMessageToWebhook).mock.calls; const resolutionCall = calls.find(call => - call[1].text.includes('My Search'), + call[1].text?.includes('My Search'), ); expect(resolutionCall).toBeDefined(); }); @@ -7615,9 +7618,9 @@ describe('checkAlerts', () => { expect(slack.postMessageToWebhook).toHaveBeenCalledTimes(4); // Verify the resolution notification was sent for service-b - const calls = (slack.postMessageToWebhook as jest.Mock).mock.calls; + const calls = jest.mocked(slack.postMessageToWebhook).mock.calls; const resolutionCall = calls.find(call => - call[1].text.includes('My Search'), + call[1].text?.includes('My Search'), ); expect(resolutionCall).toBeDefined(); }); @@ -8009,7 +8012,7 @@ describe('checkAlerts', () => { expect(slack.postMessageToWebhook).toHaveBeenCalledTimes(2); // Validate webhook messages contain correct group names - const calls = (slack.postMessageToWebhook as jest.Mock).mock.calls; + const calls = jest.mocked(slack.postMessageToWebhook).mock.calls; const messages = calls.map((call: any) => ({ url: call[0], text: call[1].text, @@ -11498,7 +11501,7 @@ describe('checkAlerts', () => { expect((await Alert.findById(details.alert.id))!.state).toBe('OK'); expect(slack.postMessageToWebhook).toHaveBeenCalledTimes(2); - const calls = (slack.postMessageToWebhook as jest.Mock).mock.calls; + const calls = jest.mocked(slack.postMessageToWebhook).mock.calls; expect(JSON.stringify(calls[0][1])).toContain('Alert for'); expect(JSON.stringify(calls[1][1])).toContain( 'The alert has been resolved', @@ -11570,7 +11573,7 @@ describe('checkAlerts', () => { jest .spyOn(slack, 'postMessageToWebhook') - .mockResolvedValue(null as any); + .mockResolvedValue(fromAny(null)); const details = await createAlertDetails( team, @@ -11671,7 +11674,7 @@ describe('checkAlerts', () => { jest .spyOn(slack, 'postMessageToWebhook') - .mockResolvedValue(null as any); + .mockResolvedValue(fromAny(null)); const details = await createAlertDetails( team, @@ -11758,7 +11761,7 @@ describe('checkAlerts', () => { jest .spyOn(slack, 'postMessageToWebhook') - .mockResolvedValue(null as any); + .mockResolvedValue(fromAny(null)); const details = await createAlertDetails( team, diff --git a/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts index 06f00de963..4bee904862 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts @@ -1,4 +1,5 @@ import { ClickhouseClient } from '@hyperdx/common-utils/dist/clickhouse/node'; +import { fromAny, fromPartial } from '@total-typescript/shoehorn'; import mongoose from 'mongoose'; import * as config from '@/config'; @@ -44,7 +45,7 @@ const buildPartitionTask = ( alerts: { id: string; previousMap: Map }[], teamId = new mongoose.Types.ObjectId(), ): AlertTask => - ({ + fromPartial({ alerts: alerts.map(({ id, previousMap }) => ({ alert: { id, @@ -68,7 +69,7 @@ const buildPartitionTask = ( team: teamId, }, now: new Date(), - }) as unknown as AlertTask; + }); describe('partitionPreviousMapsByAlert', () => { it('gives each alert only its own entries from a shared map, keys unchanged', () => { @@ -176,7 +177,7 @@ describe('CheckAlertTask', () => { buildLogSearchLink: jest.fn(), getClickHouseClient: jest .fn() - .mockResolvedValue({} as ClickhouseClient), + .mockResolvedValue(fromPartial({})), }; jest.mocked(loadProvider).mockResolvedValue(mockAlertProvider); @@ -191,7 +192,9 @@ describe('CheckAlertTask', () => { }); it('should throw error for invalid task name', async () => { - const args = { taskName: 'invalid-task' } as any; + const args = fromAny({ + taskName: 'invalid-task', + }); const task = new CheckAlertTask(args); await expect(task.execute()).rejects.toThrow( @@ -237,7 +240,7 @@ describe('CheckAlertTask', () => { const args: CheckAlertsTaskArgs = { taskName: TaskName.CHECK_ALERTS }; const task = new CheckAlertTask(args); - const mockAlert = { + const mockAlert: IAlert = fromPartial({ id: 'alert-123', team: { _id: new mongoose.Types.ObjectId() }, source: AlertSource.SAVED_SEARCH, @@ -245,22 +248,22 @@ describe('CheckAlertTask', () => { thresholdType: AlertThresholdType.ABOVE, interval: '5m', channel: { type: 'webhook', webhookId: 'webhook-123' }, - } as IAlert; + }); - const mockSource = { + const mockSource: ISource = fromPartial({ id: 'source-123', from: { databaseName: 'default', tableName: 'otel_logs' }, timestampValueExpression: 'Timestamp', - } as ISource; + }); const mockAlertTask = { alerts: [ - { + fromPartial({ alert: mockAlert, source: mockSource, taskType: AlertTaskType.SAVED_SEARCH, previousMap: new Map(), - } as AlertDetails, + }), ], conn: { id: 'conn-123', @@ -277,10 +280,10 @@ describe('CheckAlertTask', () => { const teamWebhooksById = new Map([ [ 'webhook-123', - { + fromAny({ _id: 'webhook-123', url: 'http://example.com/webhook', - } as unknown as IWebhook, + }), ], ]); @@ -313,7 +316,7 @@ describe('CheckAlertTask', () => { const team1Id = new mongoose.Types.ObjectId(); const team2Id = new mongoose.Types.ObjectId(); - const mockAlert1 = { + const mockAlert1: IAlert = fromPartial({ id: 'alert-123', team: { _id: team1Id }, source: AlertSource.SAVED_SEARCH, @@ -321,9 +324,9 @@ describe('CheckAlertTask', () => { thresholdType: AlertThresholdType.ABOVE, interval: '5m', channel: { type: 'webhook', webhookId: 'webhook-team1' }, - } as IAlert; + }); - const mockAlert2 = { + const mockAlert2: IAlert = fromPartial({ id: 'alert-456', team: { _id: team2Id }, source: AlertSource.SAVED_SEARCH, @@ -331,22 +334,22 @@ describe('CheckAlertTask', () => { thresholdType: AlertThresholdType.BELOW, interval: '1m', channel: { type: 'webhook', webhookId: 'webhook-team2' }, - } as IAlert; + }); - const mockSource = { + const mockSource: ISource = fromPartial({ id: 'source-123', from: { databaseName: 'default', tableName: 'otel_logs' }, timestampValueExpression: 'Timestamp', - } as ISource; + }); const mockAlertTask1 = { alerts: [ - { + fromPartial({ alert: mockAlert1, source: mockSource, taskType: AlertTaskType.SAVED_SEARCH, previousMap: new Map(), - } as AlertDetails, + }), ], conn: { id: 'conn-123', @@ -362,12 +365,12 @@ describe('CheckAlertTask', () => { const mockAlertTask2 = { alerts: [ - { + fromPartial({ alert: mockAlert2, source: mockSource, taskType: AlertTaskType.SAVED_SEARCH, previousMap: new Map(), - } as AlertDetails, + }), ], conn: { id: 'conn-456', @@ -385,24 +388,24 @@ describe('CheckAlertTask', () => { const team1WebhooksById = new Map([ [ 'webhook-team1', - { + fromAny({ _id: 'webhook-team1', name: 'Team1 Webhook', url: 'http://team1.example.com/webhook', team: team1Id, - } as unknown as IWebhook, + }), ], ]); const team2WebhooksById = new Map([ [ 'webhook-team2', - { + fromAny({ _id: 'webhook-team2', name: 'Team2 Webhook', url: 'http://team2.example.com/webhook', team: team2Id, - } as unknown as IWebhook, + }), ], ]); @@ -522,7 +525,7 @@ describe('CheckAlertTask', () => { alertId: string, teamId: mongoose.Types.ObjectId, ) => - ({ + fromPartial({ alerts: [ { alert: { @@ -553,7 +556,7 @@ describe('CheckAlertTask', () => { team: teamId, }, now: new Date(), - }) as unknown as AlertTask; + }); beforeEach(() => { unhandledRejections = []; diff --git a/packages/api/src/tasks/checkAlerts/__tests__/renderAlertTemplate.int.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/renderAlertTemplate.int.test.ts index c9d6f5ecca..266af03eee 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/renderAlertTemplate.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/renderAlertTemplate.int.test.ts @@ -5,6 +5,7 @@ import { SourceKind, Tile, } from '@hyperdx/common-utils/dist/types'; +import { fromAny } from '@total-typescript/shoehorn'; import mongoose from 'mongoose'; import { @@ -32,7 +33,7 @@ const TEST_TEAM_ID = new mongoose.Types.ObjectId().toString(); // Test fixtures only need a handful of IWebhook fields — a single narrowing // point instead of an `as unknown as IWebhook` suppression-worthy cast at // every call site. -const castWebhook = (over: Record): IWebhook => over as any; +const castWebhook = (over: Record): IWebhook => fromAny(over); // A dispatcher that records jobs instead of delivering them, so these tests // assert on fan-out (who got a job) without exercising real transports. @@ -138,8 +139,8 @@ const makeSearchView = ( defaultTableSelectExpression: 'Timestamp, Body', }, savedSearch: { - _id: 'fake-saved-search-id' as any, - team: 'team-123' as any, + _id: fromAny('fake-saved-search-id'), + team: fromAny('team-123'), id: 'fake-saved-search-id', name: 'My Search', select: 'Body', @@ -147,7 +148,7 @@ const makeSearchView = ( whereLanguage: 'lucene', ...(overrides.filters != null && { filters: overrides.filters }), orderBy: 'timestamp', - source: 'fake-source-id' as any, + source: fromAny('fake-source-id'), tags: ['test'], createdAt: new Date(), updatedAt: new Date(), @@ -179,7 +180,7 @@ const makeTileView = ( id: 'id-123', name: 'My Dashboard', tiles: [overrides.tile ?? testTile], - team: 'team-123' as any, + team: fromAny('team-123'), tags: ['test'], createdAt: new Date(), updatedAt: new Date(), diff --git a/packages/api/src/tasks/checkAlerts/__tests__/singleInvocationAlert.int.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/singleInvocationAlert.int.test.ts index 02d5f2bc34..4e049ad3f3 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/singleInvocationAlert.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/singleInvocationAlert.int.test.ts @@ -1,4 +1,5 @@ import { ClickhouseClient } from '@hyperdx/common-utils/dist/clickhouse/node'; +import { fromAny } from '@total-typescript/shoehorn'; import { createServer } from 'http'; import mongoose from 'mongoose'; import ms from 'ms'; @@ -93,7 +94,7 @@ describe('Single Invocation Alert Test', () => { it('should trigger alert and send webhook notification - happy path', async () => { // Mock slack webhook to avoid external calls - jest.spyOn(slack, 'postMessageToWebhook').mockResolvedValue(null as any); + jest.spyOn(slack, 'postMessageToWebhook').mockResolvedValue(fromAny(null)); // Create team const team = await createTeam({ name: 'Test Team' }); @@ -256,7 +257,7 @@ describe('Single Invocation Alert Test', () => { }); it('should include saved search filters in alert ClickHouse query', async () => { - jest.spyOn(slack, 'postMessageToWebhook').mockResolvedValue(null as any); + jest.spyOn(slack, 'postMessageToWebhook').mockResolvedValue(fromAny(null)); const team = await createTeam({ name: 'Test Team' }); @@ -397,7 +398,7 @@ describe('Single Invocation Alert Test', () => { }); it('should not trigger alert when filters exclude all matching logs', async () => { - jest.spyOn(slack, 'postMessageToWebhook').mockResolvedValue(null as any); + jest.spyOn(slack, 'postMessageToWebhook').mockResolvedValue(fromAny(null)); const team = await createTeam({ name: 'Test Team' }); @@ -519,7 +520,7 @@ describe('Single Invocation Alert Test', () => { }); it('should apply both where clause and filters together in alert query', async () => { - jest.spyOn(slack, 'postMessageToWebhook').mockResolvedValue(null as any); + jest.spyOn(slack, 'postMessageToWebhook').mockResolvedValue(fromAny(null)); const team = await createTeam({ name: 'Test Team' }); @@ -658,7 +659,7 @@ describe('Single Invocation Alert Test', () => { it('should use correct tile name in alert title when alerting tile is not first', async () => { // Mock slack webhook to avoid external calls - jest.spyOn(slack, 'postMessageToWebhook').mockResolvedValue(null as any); + jest.spyOn(slack, 'postMessageToWebhook').mockResolvedValue(fromAny(null)); // Create team const team = await createTeam({ name: 'Test Team' }); @@ -847,7 +848,7 @@ describe('Single Invocation Alert Test', () => { // Get the webhook call to inspect the title expect(slack.postMessageToWebhook).toHaveBeenCalledTimes(1); - const webhookCall = (slack.postMessageToWebhook as jest.Mock).mock.calls[0]; + const webhookCall = jest.mocked(slack.postMessageToWebhook).mock.calls[0]; const messageText = webhookCall[1].text; // This assertion SHOULD pass but WILL FAIL due to the bug @@ -864,7 +865,7 @@ describe('Single Invocation Alert Test', () => { }); it('should trigger alert for raw SQL Number chart tile', async () => { - jest.spyOn(slack, 'postMessageToWebhook').mockResolvedValue(null as any); + jest.spyOn(slack, 'postMessageToWebhook').mockResolvedValue(fromAny(null)); const team = await createTeam({ name: 'Test Team' }); diff --git a/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts b/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts index fcd586b217..81d7a76896 100644 --- a/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts @@ -1,4 +1,5 @@ import { DisplayType } from '@hyperdx/common-utils/dist/types'; +import { fromAny } from '@total-typescript/shoehorn'; import mongoose from 'mongoose'; import { createAlert } from '@/controllers/alerts'; @@ -216,8 +217,8 @@ describe('DefaultAlertProvider', () => { expect(alertSource!.timestampValueExpression).toBe('timestamp'); // Ensure it's a plain object, not a mongoose document - expect((alertSource as any).toObject).toBeUndefined(); // mongoose documents have toObject method - expect((alertSource as any).save).toBeUndefined(); // mongoose documents have save method + expect('toObject' in alertSource!).toBe(false); // mongoose documents have toObject method + expect('save' in alertSource!).toBe(false); // mongoose documents have save method } }); @@ -602,7 +603,7 @@ describe('DefaultAlertProvider', () => { // Create alert with invalid source await Alert.create({ team: team._id, - source: 'UNSUPPORTED_SOURCE' as any, + source: fromAny('UNSUPPORTED_SOURCE'), threshold: 10, thresholdType: AlertThresholdType.ABOVE, interval: '5m', diff --git a/packages/api/src/tasks/checkAlerts/transports/__tests__/registry.test.ts b/packages/api/src/tasks/checkAlerts/transports/__tests__/registry.test.ts index cae1b57f63..0021ea89d6 100644 --- a/packages/api/src/tasks/checkAlerts/transports/__tests__/registry.test.ts +++ b/packages/api/src/tasks/checkAlerts/transports/__tests__/registry.test.ts @@ -1,5 +1,6 @@ -import { WebhookService } from '@hyperdx/common-utils/dist/types'; +import { fromAny } from '@total-typescript/shoehorn'; +import { AlertState } from '@/models/alert'; import { deliverToChannel } from '@/tasks/checkAlerts/transports'; import type { Message } from '@/tasks/checkAlerts/transports/types'; @@ -7,7 +8,7 @@ const message: Message = { hdxLink: 'https://example.test/alert', title: 'title', body: 'body', - state: 'ALERT' as Message['state'], + state: AlertState.ALERT, startTime: 0, endTime: 1, eventId: 'evt-1', @@ -16,17 +17,17 @@ const message: Message = { describe('deliverToChannel', () => { it('throws on an unknown channel type', async () => { await expect( - deliverToChannel({ type: 'carrier-pigeon' } as never, message, {}), + deliverToChannel(fromAny({ type: 'carrier-pigeon' }), message, {}), ).rejects.toThrow('Unsupported channel type: carrier-pigeon'); }); it('throws on an unknown webhook service', async () => { await expect( deliverToChannel( - { + fromAny({ type: 'webhook', - channel: { service: 'fax' as WebhookService } as never, - } as never, + channel: { service: 'fax' }, + }), message, {}, ), diff --git a/packages/api/src/tasks/provisionDashboards/__tests__/provisionDashboards.int.test.ts b/packages/api/src/tasks/provisionDashboards/__tests__/provisionDashboards.int.test.ts index c91e79b5b2..4fba261c05 100644 --- a/packages/api/src/tasks/provisionDashboards/__tests__/provisionDashboards.int.test.ts +++ b/packages/api/src/tasks/provisionDashboards/__tests__/provisionDashboards.int.test.ts @@ -180,14 +180,17 @@ describe('provisionDashboards', () => { it('migrates legacy chart-N tile colors before schema validation', () => { const tile = makeTile(); - (tile.config as any).color = 'chart-1'; fs.writeFileSync( path.join(tmpDir, 'legacy.json'), - JSON.stringify({ name: 'Legacy', tiles: [tile], tags: [] }), + JSON.stringify({ + name: 'Legacy', + tiles: [{ ...tile, config: { ...tile.config, color: 'chart-1' } }], + tags: [], + }), ); const result = readDashboardFiles(tmpDir); expect(result).toHaveLength(1); - expect((result[0].tiles[0].config as any).color).toBe('chart-green'); + expect(result[0].tiles[0].config).toHaveProperty('color', 'chart-green'); }); // Early-return for files whose `tiles` is non-array (or missing). @@ -245,12 +248,12 @@ describe('provisionDashboards', () => { await syncDashboards(team._id.toString(), tmpDir); - const dashboard = (await Dashboard.findOne({ + const dashboard = await Dashboard.findOne({ name: 'Existing', team: team._id, - })) as any; - expect(dashboard.tiles[0].id).toBe(newTile.id); - expect(dashboard.tags).toEqual(['updated']); + }); + expect(dashboard!.tiles[0].id).toBe(newTile.id); + expect(dashboard!.tags).toEqual(['updated']); }); it('does not create duplicates on repeated sync', async () => { @@ -331,14 +334,14 @@ describe('provisionDashboards', () => { await syncDashboards(team._id.toString(), tmpDir); - const userDashboard = (await Dashboard.findOne({ + const userDashboard = await Dashboard.findOne({ name: 'My Dashboard', team: team._id, provisioned: { $ne: true }, - })) as any; + }); expect(userDashboard).toBeTruthy(); - expect(userDashboard.tiles[0].id).toBe(userTile.id); - expect(userDashboard.tags).toEqual(['user-tag']); + expect(userDashboard!.tiles[0].id).toBe(userTile.id); + expect(userDashboard!.tags).toEqual(['user-tag']); const provisionedDashboard = await Dashboard.findOne({ name: 'My Dashboard', diff --git a/packages/api/src/utils/__tests__/externalApi.test.ts b/packages/api/src/utils/__tests__/externalApi.test.ts index abbb40da81..33507f6ebc 100644 --- a/packages/api/src/utils/__tests__/externalApi.test.ts +++ b/packages/api/src/utils/__tests__/externalApi.test.ts @@ -1,3 +1,4 @@ +import { fromAny } from '@total-typescript/shoehorn'; import { Types } from 'mongoose'; import { @@ -19,7 +20,7 @@ const foreignChannel = (value: any): AlertChannel => value; const createAlertDocument = ( overrides: Partial> = {}, ): AlertDocument => - ({ + fromAny({ _id: new Types.ObjectId(), team: new Types.ObjectId(), threshold: 5, @@ -29,7 +30,7 @@ const createAlertDocument = ( state: AlertState.OK, channel: { type: null }, ...overrides, - }) as unknown as AlertDocument; + }); describe('utils/externalApi', () => { describe('translateAlertDocumentToExternalAlert', () => { diff --git a/packages/api/src/utils/__tests__/filterSources.test.ts b/packages/api/src/utils/__tests__/filterSources.test.ts index b89b06d35b..0ccc441ade 100644 --- a/packages/api/src/utils/__tests__/filterSources.test.ts +++ b/packages/api/src/utils/__tests__/filterSources.test.ts @@ -1,4 +1,5 @@ import { DashboardFilter, SourceKind } from '@hyperdx/common-utils/dist/types'; +import { fromPartial } from '@total-typescript/shoehorn'; import { getChangedFilterSourceRefs, @@ -104,7 +105,7 @@ describe('getChangedFilterSourceRefs', () => { const { id: _id, ...withoutId } = adhoc(); expect( getChangedFilterSourceRefs( - [withoutId as DashboardFilter, adhoc({ id: 'new' })], + [fromPartial(withoutId), adhoc({ id: 'new' })], [adhoc()], ), ).toEqual([ diff --git a/packages/api/src/utils/__tests__/iacTileAlerts.int.test.ts b/packages/api/src/utils/__tests__/iacTileAlerts.int.test.ts index fc2f7198ee..320dc3e89e 100644 --- a/packages/api/src/utils/__tests__/iacTileAlerts.int.test.ts +++ b/packages/api/src/utils/__tests__/iacTileAlerts.int.test.ts @@ -1,3 +1,4 @@ +import { fromAny } from '@total-typescript/shoehorn'; import mongoose from 'mongoose'; import { getServer, randomMongoId } from '@/fixtures'; @@ -54,11 +55,13 @@ describe('unaddressableTileAlertIds', () => { // The failure this guards is MaxTimeMSExpired on a read sequenced last on // a shared budget. Reproducing that needs a slow collection, so the read // itself is made to reject instead. - const find = jest.spyOn(Dashboard, 'find').mockReturnValue({ - maxTimeMS: () => ({ - lean: () => Promise.reject(new Error('MaxTimeMSExpired')), + const find = jest.spyOn(Dashboard, 'find').mockReturnValue( + fromAny({ + maxTimeMS: () => ({ + lean: () => Promise.reject(new Error('MaxTimeMSExpired')), + }), }), - } as never); + ); try { const withheld = await unaddressableTileAlertIds({ @@ -115,9 +118,11 @@ describe('unaddressableTileAlertIds', () => { const alerts = [alert(dashboard._id, 'tile-1')]; // Never settles, which is the shape of a wait maxTimeMS cannot see. - const find = jest.spyOn(Dashboard, 'find').mockReturnValue({ - maxTimeMS: () => ({ lean: () => new Promise(() => {}) }), - } as never); + const find = jest.spyOn(Dashboard, 'find').mockReturnValue( + fromAny({ + maxTimeMS: () => ({ lean: () => new Promise(() => {}) }), + }), + ); try { const withheld = await unaddressableTileAlertIds({ @@ -144,14 +149,16 @@ describe('unaddressableTileAlertIds', () => { }); const alerts = [alert(dashboard._id, 'tile-1')]; - const find = jest.spyOn(Dashboard, 'find').mockReturnValue({ - maxTimeMS: () => ({ - lean: () => - new Promise((_, reject) => - setTimeout(() => reject(new Error('MongoNetworkError')), 100), - ), + const find = jest.spyOn(Dashboard, 'find').mockReturnValue( + fromAny({ + maxTimeMS: () => ({ + lean: () => + new Promise((_, reject) => + setTimeout(() => reject(new Error('MongoNetworkError')), 100), + ), + }), }), - } as never); + ); // getCounter memoizes by name, so this is the instrument the module under // test captured at import — no options, or it would warn about a mismatch. const add = jest.spyOn( diff --git a/packages/api/src/utils/__tests__/logParser.test.ts b/packages/api/src/utils/__tests__/logParser.test.ts index 65d22bad3e..2e3c2bf9b7 100644 --- a/packages/api/src/utils/__tests__/logParser.test.ts +++ b/packages/api/src/utils/__tests__/logParser.test.ts @@ -1,3 +1,5 @@ +import { fromAny } from '@total-typescript/shoehorn'; + import { mapObjectToKeyValuePairs, traverseJson } from '@/utils/logParser'; describe('logParser', () => { @@ -54,7 +56,7 @@ describe('logParser', () => { }); it('mapObjectToKeyValuePairs', () => { - expect(mapObjectToKeyValuePairs(null as any)).toEqual({ + expect(mapObjectToKeyValuePairs(fromAny(null))).toEqual({ 'bool.names': [], 'bool.values': [], 'number.names': [], diff --git a/packages/api/src/utils/__tests__/retry.test.ts b/packages/api/src/utils/__tests__/retry.test.ts index d202886843..081ee119c3 100644 --- a/packages/api/src/utils/__tests__/retry.test.ts +++ b/packages/api/src/utils/__tests__/retry.test.ts @@ -31,8 +31,7 @@ describe('withRetry', () => { }); it('should not retry on 4xx client errors except 429', async () => { - const error400 = new Error('bad request') as any; - error400.status = 400; + const error400 = Object.assign(new Error('bad request'), { status: 400 }); const fn400 = jest.fn().mockRejectedValue(error400); @@ -43,8 +42,7 @@ describe('withRetry', () => { }); it('should not retry on 3xx redirect responses', async () => { - const redirectError = new Error('redirect') as any; - redirectError.status = 302; + const redirectError = Object.assign(new Error('redirect'), { status: 302 }); const fn = jest.fn().mockRejectedValue(redirectError); @@ -55,8 +53,7 @@ describe('withRetry', () => { }); it('should retry on 429 Too Many Requests', async () => { - const error429 = new Error('rate limited') as any; - error429.status = 429; + const error429 = Object.assign(new Error('rate limited'), { status: 429 }); const fn429 = jest .fn() @@ -72,8 +69,9 @@ describe('withRetry', () => { }); it('should retry on 5xx server errors', async () => { - const error500 = new Error('internal server error') as any; - error500.status = 500; + const error500 = Object.assign(new Error('internal server error'), { + status: 500, + }); const fn500 = jest .fn() @@ -113,11 +111,11 @@ describe('withRetry', () => { }); it('should strictly obey retryOnlyOnStatus if provided', async () => { - const error500 = new Error('internal server error') as any; - error500.status = 500; + const error500 = Object.assign(new Error('internal server error'), { + status: 500, + }); - const error429 = new Error('rate limited') as any; - error429.status = 429; + const error429 = Object.assign(new Error('rate limited'), { status: 429 }); const fn = jest .fn() diff --git a/packages/api/src/utils/__tests__/validators.test.ts b/packages/api/src/utils/__tests__/validators.test.ts index 8800d7ff48..9b36223b36 100644 --- a/packages/api/src/utils/__tests__/validators.test.ts +++ b/packages/api/src/utils/__tests__/validators.test.ts @@ -1,4 +1,5 @@ import { WebhookService } from '@hyperdx/common-utils/dist/types'; +import { fromAny } from '@total-typescript/shoehorn'; import dns from 'dns'; import { createHandlebarsWithHelpers } from '@/tasks/checkAlerts/transports'; @@ -560,8 +561,8 @@ describe('validators', () => { }); it('should return false if password is invalid', () => { - expect(validators.validatePassword(null as any)).toBe(false); - expect(validators.validatePassword(undefined as any)).toBe(false); + expect(validators.validatePassword(fromAny(null))).toBe(false); + expect(validators.validatePassword(fromAny(undefined))).toBe(false); expect(validators.validatePassword('')).toBe(false); expect(validators.validatePassword('1234567')).toBe(false); expect(validators.validatePassword('abcdefghijk')).toBe(false); // 11 chars diff --git a/yarn.lock b/yarn.lock index 06925e9012..b5d4e3824c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4106,6 +4106,7 @@ __metadata: "@opentelemetry/sdk-trace-base": "npm:^2.8.0" "@slack/webhook": "npm:^7.0.0" "@stoplight/spectral-cli": "npm:^6.15.0" + "@total-typescript/shoehorn": "npm:^0.1.2" "@types/compression": "npm:^1.7.3" "@types/cors": "npm:^2.8.14" "@types/express": "npm:^4.17.13"