Skip to content

refactor: enable no-unnecessary-condition #18798

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

Closed
Show file tree
Hide file tree
Changes from all commits
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
18 changes: 18 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ export default tseslint.config(
'**/*.snap',
],
},
{
linterOptions: {
reportUnusedDisableDirectives: shouldTypeCheck ? 'warn' : 'off',
},
},
eslint.configs.recommended,
...tseslint.configs.recommended,
...tseslint.configs.stylistic,
Expand Down Expand Up @@ -145,6 +150,16 @@ export default tseslint.config(
'@typescript-eslint/consistent-type-definitions': 'off',
'@typescript-eslint/prefer-for-of': 'off',
'@typescript-eslint/prefer-function-type': 'off',
...(shouldTypeCheck
? {
'@typescript-eslint/no-unnecessary-condition': [
'error',
{
allowConstantLoopConditions: true,
},
],
}
: {}),

'import-x/no-nodejs-modules': [
'error',
Expand Down Expand Up @@ -346,5 +361,8 @@ export default tseslint.config(
project: false,
},
},
rules: {
'@typescript-eslint/no-unnecessary-condition': 'off',
},
},
)
19 changes: 10 additions & 9 deletions packages/create-vite/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,9 +289,10 @@ const FRAMEWORKS: Framework[] = [
},
]

const TEMPLATES = FRAMEWORKS.map(
(f) => (f.variants && f.variants.map((v) => v.name)) || [f.name],
).reduce((a, b) => a.concat(b), [])
const TEMPLATES = FRAMEWORKS.map((f) => f.variants.map((v) => v.name)).reduce(
(a, b) => a.concat(b),
[],
)

const renameFiles: Record<string, string | undefined> = {
_gitignore: '.gitignore',
Expand Down Expand Up @@ -394,8 +395,8 @@ async function init() {
}),
},
{
type: (framework: Framework) =>
framework && framework.variants ? 'select' : null,
type: (framework: Framework | /* package name */ string) =>
typeof framework === 'object' ? 'select' : null,
name: 'variant',
message: reset('Select a variant:'),
choices: (framework: Framework) =>
Expand Down Expand Up @@ -478,7 +479,7 @@ async function init() {
const replacedArgs = args.map((arg) =>
arg.replace('TARGET_DIR', () => targetDir),
)
const { status } = spawn.sync(command, replacedArgs, {
const { status } = spawn.sync(command!, replacedArgs, {
stdio: 'inherit',
})
process.exit(status ?? 0)
Expand Down Expand Up @@ -596,11 +597,11 @@ function emptyDir(dir: string) {

function pkgFromUserAgent(userAgent: string | undefined) {
if (!userAgent) return undefined
const pkgSpec = userAgent.split(' ')[0]
const pkgSpec = userAgent.split(' ')[0]!
const pkgSpecArr = pkgSpec.split('/')
return {
name: pkgSpecArr[0],
version: pkgSpecArr[1],
name: pkgSpecArr[0]!,
version: pkgSpecArr[1] ?? '',
}
}

Expand Down
3 changes: 2 additions & 1 deletion packages/create-vite/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"declaration": false,
"sourceMap": false,
"noUnusedLocals": true,
"esModuleInterop": true
"esModuleInterop": true,
"noUncheckedIndexedAccess": true
}
}
8 changes: 4 additions & 4 deletions packages/plugin-legacy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,7 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] {
if (isLegacyBundle(bundle, opts) && genModern) {
// avoid emitting duplicate assets
for (const name in bundle) {
if (bundle[name].type === 'asset' && !/.+\.map$/.test(name)) {
if (bundle[name]!.type === 'asset' && !/.+\.map$/.test(name)) {
delete bundle[name]
}
}
Expand Down Expand Up @@ -831,7 +831,7 @@ async function buildPolyfillChunk(
},
},
})
const _polyfillChunk = Array.isArray(res) ? res[0] : res
const _polyfillChunk = Array.isArray(res) ? res[0]! : res
if (!('output' in _polyfillChunk)) return
const polyfillChunk = _polyfillChunk.output.find(
(chunk) => chunk.type === 'chunk' && chunk.isEntry,
Expand All @@ -840,7 +840,7 @@ async function buildPolyfillChunk(
// associate the polyfill chunk to every entry chunk so that we can retrieve
// the polyfill filename in index html transform
for (const key in bundle) {
const chunk = bundle[key]
const chunk = bundle[key]!
if (chunk.type === 'chunk' && chunk.facadeModuleId) {
facadeToChunkMap.set(chunk.facadeModuleId, polyfillChunk.fileName)
}
Expand Down Expand Up @@ -971,7 +971,7 @@ function wrapIIFEBabelPlugin(): BabelPlugin {
}

const hash =
// eslint-disable-next-line n/no-unsupported-features/node-builtins -- crypto.hash is supported in Node 21.7.0+, 20.12.0+
// eslint-disable-next-line n/no-unsupported-features/node-builtins, @typescript-eslint/no-unnecessary-condition -- crypto.hash is supported in Node 21.7.0+, 20.12.0+
crypto.hash ??
((
algorithm: string,
Expand Down
1 change: 1 addition & 0 deletions packages/plugin-legacy/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"sourceMap": true,
"noUnusedLocals": true,
"esModuleInterop": true,
"noUncheckedIndexedAccess": true,
"paths": {
"vite": ["../vite/src/node/index.js"]
}
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/rollup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ function shimDepsPlugin(deps: Record<string, ShimOptions[]>): Plugin {
transform(code, id) {
for (const file in deps) {
if (id.replace(/\\/g, '/').endsWith(file)) {
for (const { src, replacement, pattern } of deps[file]) {
for (const { src, replacement, pattern } of deps[file]!) {
const magicString = new MagicString(code)

if (src) {
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/rollup.dts.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ function replaceConfusingTypeNames(
continue
}

const betterId = replacements[id]
const betterId = replacements[id]!
const regexEscapedId = escapeRegex(id)
// If the better id accesses a namespace, the existing `Foo as Foo$1`
// named import cannot be replaced with `Foo as Namespace.Foo`, so we
Expand Down
14 changes: 7 additions & 7 deletions packages/vite/rollupLicensePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ export default function licensePlugin(
let dependencyLicenseTexts = ''
for (let i = 0; i < deps.length; i++) {
// Find dependencies with the same license text so it can be shared
const licenseText = deps[i].licenseText
const sameDeps = [deps[i]]
const licenseText = deps[i]!.licenseText
const sameDeps = [deps[i]!]
if (licenseText) {
for (let j = i + 1; j < deps.length; j++) {
if (licenseText === deps[j].licenseText) {
if (licenseText === deps[j]!.licenseText) {
sameDeps.push(...deps.splice(j, 1))
j--
}
Expand All @@ -47,11 +47,11 @@ export default function licensePlugin(
depInfos.length > 1 &&
depInfos.every(
(info) =>
info.license === depInfos[0].license &&
info.names === depInfos[0].names,
info.license === depInfos[0]!.license &&
info.names === depInfos[0]!.names,
)
) {
const { license, names } = depInfos[0]
const { license, names } = depInfos[0]!
const repositoryText = depInfos
.map((info) => info.repository)
.filter(Boolean)
Expand All @@ -64,7 +64,7 @@ export default function licensePlugin(
// Else show each dependency separately
else {
for (let j = 0; j < depInfos.length; j++) {
const { license, names, repository } = depInfos[j]
const { license, names, repository } = depInfos[j]!

if (license) text += `License: ${license}\n`
if (names) text += `By: ${names}\n`
Expand Down
6 changes: 5 additions & 1 deletion packages/vite/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,10 @@ const hmrClient = new HMRClient(
explicitImportRequired,
isWithinCircularImport,
}) {
const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`)
const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`) as [
string,
...string[],
]
const importPromise = import(
/* @vite-ignore */
base +
Expand Down Expand Up @@ -309,6 +312,7 @@ const hasDocument = 'document' in globalThis
function createErrorOverlay(err: ErrorPayload['err']) {
clearErrorOverlay()
const { customElements } = globalThis
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (customElements) {
const ErrorOverlayConstructor = customElements.get(overlayId)!
document.body.appendChild(new ErrorOverlayConstructor(err))
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/client/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Object.keys(defines).forEach((key) => {
const segments = key.split('.')
let target = context
for (let i = 0; i < segments.length; i++) {
const segment = segments[i]
const segment = segments[i]!
if (i === segments.length - 1) {
target[segment] = defines[key]
} else {
Expand Down
36 changes: 19 additions & 17 deletions packages/vite/src/client/overlay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,10 @@ export class ErrorOverlay extends HTMLElement {
}
this.text('.message-body', message.trim())

const [file] = (err.loc?.file || err.id || 'unknown file').split(`?`)
const [file] = (err.loc?.file || err.id || 'unknown file').split(`?`) as [
string,
...string[],
]
if (err.loc) {
this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, links)
} else if (err.id) {
Expand Down Expand Up @@ -264,23 +267,21 @@ export class ErrorOverlay extends HTMLElement {
fileRE.lastIndex = 0
while ((match = fileRE.exec(text))) {
const { 0: file, index } = match
if (index != null) {
const frag = text.slice(curIndex, index)
el.appendChild(document.createTextNode(frag))
const link = document.createElement('a')
link.textContent = file
link.className = 'file-link'
link.onclick = () => {
fetch(
new URL(
`${base}__open-in-editor?file=${encodeURIComponent(file)}`,
import.meta.url,
),
)
}
el.appendChild(link)
curIndex += frag.length + file.length
const frag = text.slice(curIndex, index)
el.appendChild(document.createTextNode(frag))
const link = document.createElement('a')
link.textContent = file
link.className = 'file-link'
link.onclick = () => {
fetch(
new URL(
`${base}__open-in-editor?file=${encodeURIComponent(file)}`,
import.meta.url,
),
)
}
el.appendChild(link)
curIndex += frag.length + file.length
}
}
}
Expand All @@ -292,6 +293,7 @@ export class ErrorOverlay extends HTMLElement {

export const overlayId = 'vite-error-overlay'
const { customElements } = globalThis // Ensure `customElements` is defined before the next line.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (customElements && !customElements.get(overlayId)) {
customElements.define(overlayId, ErrorOverlay)
}
6 changes: 3 additions & 3 deletions packages/vite/src/module-runner/hmrHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,11 +151,11 @@ function getModulesEntrypoints(
if (!module) {
continue
}
if (module.importers && !module.importers.size) {
if (!module.importers.size) {
entrypoints.add(module.url)
continue
}
for (const importer of module.importers || []) {
for (const importer of module.importers) {
getModulesEntrypoints(runner, [importer], visited, entrypoints)
}
}
Expand All @@ -167,7 +167,7 @@ function findAllEntrypoints(
entrypoints = new Set<string>(),
): Set<string> {
for (const mod of runner.evaluatedModules.idToModuleMap.values()) {
if (mod.importers && !mod.importers.size) {
if (!mod.importers.size) {
entrypoints.add(mod.url)
}
}
Expand Down
1 change: 1 addition & 0 deletions packages/vite/src/module-runner/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,7 @@ export class ModuleRunner {

const { code, file } = fetchResult

// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- is this needed?
if (code == null) {
const importer = callstack[callstack.length - 2]
throw new Error(
Expand Down
1 change: 1 addition & 0 deletions packages/vite/src/module-runner/sourcemap/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export function enableSourceMapSupport(runner: ModuleRunner): () => void {
`Cannot use "sourcemapInterceptor: 'node'" because "process.setSourceMapsEnabled" function is not available. Please use Node >= 16.6.0.`,
)
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- process.sourceMapsEnabled is not available in Node < 20.7.0
const isEnabledAlready = process.sourceMapsEnabled ?? false
process.setSourceMapsEnabled(true)
return () => !isEnabledAlready && process.setSourceMapsEnabled(false)
Expand Down
20 changes: 13 additions & 7 deletions packages/vite/src/module-runner/sourcemap/interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { ModuleRunner } from '../runner'
import { posixDirname, posixResolve } from '../utils'
import type { EvaluatedModules } from '../evaluatedModules'
import { slash } from '../../shared/utils'
import type { StrictRegExpExecArrayFromLen } from '../../shared/typeUtils'
import { DecodedMap, getOriginalPosition } from './decoder'

interface RetrieveFileHandler {
Expand Down Expand Up @@ -172,7 +173,8 @@ function retrieveSourceMap(source: string) {

function mapSourcePosition(position: OriginalMapping) {
if (!position.source) return position
let sourceMap = getRunnerSourceMap(position)
let sourceMap: CachedMapEntry | null | undefined =
getRunnerSourceMap(position)
if (!sourceMap) sourceMap = sourceMapCache[position.source]
if (!sourceMap) {
// Call the (overrideable) retrieveSourceMap function to get the source map.
Expand Down Expand Up @@ -210,7 +212,7 @@ function mapSourcePosition(position: OriginalMapping) {
}

// Resolve the source URL relative to the URL of the source map
if (sourceMap && sourceMap.map && sourceMap.url) {
if (sourceMap.map && sourceMap.url) {
const originalPosition = getOriginalPosition(sourceMap.map, position)

// Only return the original position if a matching line was found. If no
Expand Down Expand Up @@ -238,7 +240,9 @@ function mapSourcePosition(position: OriginalMapping) {
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
function mapEvalOrigin(origin: string): string {
// Most eval() calls are in this format
let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin)
const match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(
origin,
) as StrictRegExpExecArrayFromLen<4> | null
if (match) {
const position = mapSourcePosition({
name: null,
Expand All @@ -250,8 +254,10 @@ function mapEvalOrigin(origin: string): string {
}

// Parse nested eval() calls using recursion
match = /^eval at ([^(]+) \((.+)\)$/.exec(origin)
if (match) return `eval at ${match[1]} (${mapEvalOrigin(match[2])})`
const match2 = /^eval at ([^(]+) \((.+)\)$/.exec(
origin,
) as StrictRegExpExecArrayFromLen<2> | null
if (match2) return `eval at ${match2[1]} (${mapEvalOrigin(match2[2])})`

// Make sure we still return useful information if we didn't find anything
return origin
Expand Down Expand Up @@ -345,7 +351,7 @@ function cloneCallSite(frame: CallSite) {
}

function wrapCallSite(frame: CallSite, state: State) {
// provides interface backward compatibility
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- provides interface backward compatibility
if (state === undefined) state = { nextPosition: null, curPosition: null }

if (frame.isNative()) {
Expand Down Expand Up @@ -425,7 +431,7 @@ function prepareStackTrace(error: Error, stack: CallSite[]) {
const state = { nextPosition: null, curPosition: null }
const processedStack = []
for (let i = stack.length - 1; i >= 0; i--) {
processedStack.push(`\n at ${wrapCallSite(stack[i], state)}`)
processedStack.push(`\n at ${wrapCallSite(stack[i]!, state)}`)
state.nextPosition = state.curPosition
}
state.curPosition = state.nextPosition = null
Expand Down
Loading