Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Stricter ESLint config #383

Merged
merged 2 commits into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module.exports = {
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-type-checked',
'plugin:import/recommended',
'plugin:import/electron',
'plugin:import/typescript',
Expand All @@ -18,7 +18,11 @@ module.exports = {
'prettier',
],
parser: '@typescript-eslint/parser',
ignorePatterns: ['resources/group_snippet.js', 'install-k6.js'],
ignorePatterns: [
'resources/group_snippet.js',
'install-k6.js',
'.eslintrc.cjs',
],
plugins: [
'import',
'unused-imports',
Expand All @@ -43,11 +47,8 @@ module.exports = {
argsIgnorePattern: '^_',
},
],
// TODO: remove warnings when plugin:@typescript-eslint/recommended-type-checked is enabled
'@typescript-eslint/no-unsafe-assignment': 'warn',
'@typescript-eslint/no-unsafe-return': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
'@typescript-eslint/no-unsafe-member-access': 'warn',
'@typescript-eslint/no-floating-promises': 'off',
'@typescript-eslint/no-misused-promises': 'off',
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest turning those on later. It highlighted some cases where we pass async functions as e.g. click handlers

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add them as warnings?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Initially, I was reluctant to do this, as the number of warning seemed to be too high with quite a few of them not being useful. I then discussed possible solutions with @e-fisher and we found a way to enable these rules with a few tweaks.

},

parserOptions: {
Expand Down
2 changes: 2 additions & 0 deletions src/codegen/codegen.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export function stringify(value: unknown): string {
return `{${properties}}`
}

// TODO: https://github.com/grafana/k6-studio/issues/277
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Marked ignore comments with a link to the issue (I'll update the issue description once this PR is merged).
While it does look annoying, the pros of enabling stricter rules for everything else outweigh the cons

// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
return `${value}`
}

Expand Down
2 changes: 2 additions & 0 deletions src/components/Form/FileUploadInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export const FileUploadInput = ({
disabled={disabled}
onChange={field.onChange}
name={field.name}
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
value={field.value}
/>
</FieldGroup>
Expand Down
2 changes: 2 additions & 0 deletions src/components/WebLogView/RequestDetails/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export function parseParams(data: ProxyData) {
}

return stringify(
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
JSON.parse(jsonrepair(parsePythonByteString(contentDecoded)))
)
} catch (e) {
Expand Down
2 changes: 2 additions & 0 deletions src/components/WebLogView/ResponseDetails/Preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export function Preview({ content, contentType, format }: PreviewProps) {
return (
<ReactJson
shouldCollapse={(field) => field.name !== 'root'}
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
src={JSON.parse(content)}
theme={theme === 'dark' ? 'monokai' : 'rjv-default'}
style={theme === 'dark' ? reactJsonDarkStyles : reactJsonLightStyles}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,12 @@ export function parseContent(format: string | undefined, data: ProxyData) {
try {
switch (format) {
case 'json':
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
return stringify(JSON.parse(safeAtob(content)))
case 'json-raw':
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
return stringify(JSON.parse(safeAtob(content)), 0)
case 'css':
case 'html':
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useRunChecks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ describe('useRunChecks', () => {
createK6Check({ id: '1', name: 'Check 1' }),
createK6Check({ id: '2', name: 'Check 2' }),
]
onScriptCheck.mockImplementation((callback) => {
onScriptCheck.mockImplementation((callback: (data: K6Check[]) => void) => {
callback(mockChecks)
return () => {}
})
Expand Down
3 changes: 2 additions & 1 deletion src/hooks/useRunLogs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useRunLogs } from './useRunLogs'
import { renderHook } from '@testing-library/react'
import { act } from 'react'
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { K6Log } from '@/types'

const onScriptLog = vi.fn()

Expand Down Expand Up @@ -37,7 +38,7 @@ describe('useRunLogs', () => {

it('should update logs when onScriptLog is called', () => {
const mockLog = createK6Log()
onScriptLog.mockImplementation((callback) => {
onScriptLog.mockImplementation((callback: (log: K6Log) => void) => {
callback(mockLog)
return () => {}
})
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useScriptPreview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
} from '@/test/factories/generator'

vi.mock('lodash-es', () => ({
debounce: vi.fn((fn) => fn),
debounce: vi.fn((fn: () => void) => fn),
}))
vi.mock('@/store/generator', () => ({
useGeneratorStore: {
Expand Down
22 changes: 15 additions & 7 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ const createSplashWindow = async () => {
splashscreenWindow.webContents.openDevTools({ mode: 'detach' })
}

splashscreenWindow.loadFile(splashscreenFile)
await splashscreenWindow.loadFile(splashscreenFile)

// wait for the window to be ready before showing it. It prevents showing a white page on longer load times.
splashscreenWindow.once('ready-to-show', () => {
Expand Down Expand Up @@ -231,7 +231,7 @@ app.on('before-quit', async () => {
stopProxyProcess()
})

ipcMain.handle('app:change-route', async (_, route: string) => {
ipcMain.handle('app:change-route', (_, route: string) => {
currentClientRoute = route
})

Expand All @@ -255,9 +255,9 @@ ipcMain.handle('proxy:start', async (event) => {
currentProxyProcess = await launchProxyAndAttachEmitter(browserWindow)
})

ipcMain.on('proxy:stop', async () => {
ipcMain.on('proxy:stop', () => {
console.info('proxy:stop event received')
stopProxyProcess()
return stopProxyProcess()
})

const waitForProxy = async (): Promise<void> => {
Expand Down Expand Up @@ -286,7 +286,7 @@ ipcMain.handle('browser:start', async (event, url?: string) => {
ipcMain.on('browser:stop', async () => {
console.info('browser:stop event received')
if (currentBrowserProcess) {
currentBrowserProcess.close()
await currentBrowserProcess.close()
currentBrowserProcess = null
}
})
Expand Down Expand Up @@ -415,8 +415,12 @@ ipcMain.handle('har:open', async (_, fileName: string): Promise<HarFile> => {
try {
fileHandle = await open(path.join(RECORDINGS_PATH, fileName), 'r')
const data = await fileHandle?.readFile({ encoding: 'utf-8' })
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const har = await JSON.parse(data)

// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
return { name: fileName, content: har }
} finally {
await fileHandle?.close()
Expand Down Expand Up @@ -470,8 +474,12 @@ ipcMain.handle(
fileHandle = await open(path.join(GENERATORS_PATH, fileName), 'r')

const data = await fileHandle?.readFile({ encoding: 'utf-8' })
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const generator = await JSON.parse(data)

// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
return { name: fileName, content: generator }
} finally {
await fileHandle?.close()
Expand All @@ -490,7 +498,7 @@ ipcMain.handle('ui:delete-file', async (_, fileName: string) => {
return unlink(getFilePathFromName(fileName))
})

ipcMain.on('ui:open-folder', async (_, fileName: string) => {
ipcMain.on('ui:open-folder', (_, fileName: string) => {
console.info('ui:open-folder event received')
shell.showItemInFolder(getFilePathFromName(fileName))
})
Expand Down Expand Up @@ -610,7 +618,7 @@ ipcMain.handle('settings:select-upstream-certificate', async () => {
return selectUpstreamCertificate()
})

ipcMain.handle('proxy:status:get', async () => {
ipcMain.handle('proxy:status:get', () => {
console.info('proxy:status:get event received')
return proxyStatus
})
Expand Down
4 changes: 3 additions & 1 deletion src/preload.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// TODO: https://github.com/grafana/k6-studio/issues/277
/* eslint-disable @typescript-eslint/no-unsafe-return */
import { ipcRenderer, contextBridge, IpcRendererEvent } from 'electron'
import { ProxyData, K6Log, K6Check, ProxyStatus } from './types'
import { HarFile } from './types/har'
Expand Down Expand Up @@ -34,7 +36,7 @@ const proxy = {
onProxyData: (callback: (data: ProxyData) => void) => {
return createListener('proxy:data', callback)
},
getProxyStatus: () => {
getProxyStatus: (): Promise<ProxyStatus> => {
return ipcRenderer.invoke('proxy:status:get')
},
onProxyStatusChange: (callback: (status: ProxyStatus) => void) => {
Expand Down
2 changes: 1 addition & 1 deletion src/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export const launchProxy = (
})

proxy.stderr.on('data', (data: Buffer) => {
console.error(`stderr: ${data}`)
console.error(`stderr: ${data.toString()}`)
log.error(data.toString())
})

Expand Down
17 changes: 14 additions & 3 deletions src/rules/correlation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ function applyRule({
requestSnippetSchema: RequestSnippetSchema
state: CorrelationState
rule: CorrelationRule
idGenerator: Generator<number>
idGenerator: IdGenerator
setState: (newState: Partial<CorrelationState>) => void
}) {
// this is the modified schema that we return to the accumulator
Expand Down Expand Up @@ -108,6 +108,8 @@ function applyRule({
}

// try to extract the value
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { extractedValue, generatedUniqueId, correlationExtractionSnippet } =
tryCorrelationExtraction(
rule,
Expand All @@ -126,7 +128,9 @@ function applyRule({
}

setState({
extractedValue: extractedValue,
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
extractedValue,
generatedUniqueId: generatedUniqueId,
responsesExtracted: [
...state.responsesExtracted,
Expand Down Expand Up @@ -542,9 +546,14 @@ const extractCorrelationJsonBody = (
return noCorrelationResult
}

// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const extractedValue = getJsonObjectFromPath(response.content, selector.path)

if (!extractedValue || extractedValue.length === 0) {
if (
!extractedValue ||
(Array.isArray(extractedValue) && extractedValue.length === 0)
) {
return noCorrelationResult
}

Expand All @@ -558,6 +567,8 @@ const extractCorrelationJsonBody = (
const correlationExtractionSnippet = `
correlation_vars['correlation_${generatedUniqueId}'] = resp.json()${json_path}`
return {
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
extractedValue,
correlationExtractionSnippet,
generatedUniqueId,
Expand Down
2 changes: 1 addition & 1 deletion src/rules/parameterization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { matchFilter } from './utils'

export function createParameterizationRuleInstance(
rule: ParameterizationRule,
idGenerator: Generator<number>
idGenerator: Generator<number, number, number>
): ParameterizationRuleInstance {
const state: ParameterizationState = {
requestsReplaced: [],
Expand Down
7 changes: 5 additions & 2 deletions src/rules/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import { ProxyData, RequestSnippetSchema } from '@/types'
import { generateSequentialInt } from './utils'

function createSequentialIdPool() {
const currentId: Record<TestRule['type'], Generator<number>> = {
const currentId: Record<
TestRule['type'],
Generator<number, number, number>
> = {
correlation: generateSequentialInt(),
parameterization: generateSequentialInt(),
verification: generateSequentialInt(),
Expand Down Expand Up @@ -37,7 +40,7 @@ export function applyRules(recording: ProxyData[], rules: TestRule[]) {

function createRuleInstance<T extends TestRule>(
rule: T,
idGenerator: Generator<number>
idGenerator: Generator<number, number, number>
) {
switch (rule.type) {
case 'correlation':
Expand Down
4 changes: 4 additions & 0 deletions src/rules/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ export const matchRegex = (value: string, regexString: string) => {
}

export const getJsonObjectFromPath = (json: string, path: string) => {
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return get(safeJsonParse(json), path)
}

Expand Down Expand Up @@ -272,6 +274,8 @@ export const replaceJsonBody = (

// since we are using lodash and its `set` function creates missing paths we will first check that the path really
// exists before setting it
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const valueToReplace = getJsonObjectFromPath(request.content, selector.path)
if (!valueToReplace) return

Expand Down
4 changes: 4 additions & 0 deletions src/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,15 @@ export const runScript = async (
stdoutReader.on('line', (data) => {
console.log(`stdout: ${data}`)

// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const checkData: K6Check[] = JSON.parse(data)
browserWindow.webContents.send('script:check', checkData)
})

stderrReader.on('line', (data) => {
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const logData: K6Log = JSON.parse(data)
browserWindow.webContents.send('script:log', logData)
})
Expand Down
4 changes: 4 additions & 0 deletions src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,11 @@ export async function getSettings() {
const fileHandle = await open(filePath, 'r')
try {
const settings = await fileHandle?.readFile({ encoding: 'utf-8' })
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const currentSettings = JSON.parse(settings)
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const allSettings = {
...defaultSettings,
...currentSettings,
Expand Down
4 changes: 4 additions & 0 deletions src/utils/format.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
export function queryStringToJSON(str: string) {
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return JSON.parse(
'{"' + str.replace(/&/g, '","').replace(/=/g, '":"') + '"}',
function (key, value) {
// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument
return key === '' ? value : decodeURIComponent(value)
}
)
Expand Down
4 changes: 3 additions & 1 deletion src/utils/harToProxyData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ function parseRequest(request: Entry['request']): Request {
// TODO: add actual values
// @ts-expect-error incomplete type
timestampStart: request.startedDateTime
? // @ts-expect-error incomplete type
? // TODO: https://github.com/grafana/k6-studio/issues/277
// @ts-expect-error incomplete type
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
isoToUnixTimestamp(request.startedDateTime)
: 0,
timestampEnd: 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export function OverwriteFileWarning() {
setValue('overwriteFile', false)
}

// TODO: https://github.com/grafana/k6-studio/issues/277
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const scriptName = getScriptNameWithExtension(getValues('scriptName'))

return (
Expand Down
2 changes: 2 additions & 0 deletions src/views/Generator/Generator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ export function Generator() {

const blocker = useBlocker(({ historyAction }) => {
// Don't block navigation when redirecting home from invalid generator
// TODO(router): Action enum is not exported from react-router-dom
// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
return isDirty && historyAction !== 'REPLACE'
})

Expand Down
Loading
Loading