File size: 4,958 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#!/usr/bin/env node

import { existsSync } from 'fs'
import { isAbsolute, join } from 'path'

import loadConfig from '../server/config'
import { printAndExit } from '../server/lib/utils'
import { Telemetry } from '../telemetry/storage'
import { green } from '../lib/picocolors'
import { ESLINT_DEFAULT_DIRS } from '../lib/constants'
import { runLintCheck } from '../lib/eslint/runLintCheck'
import { CompileError } from '../lib/compile-error'
import { PHASE_PRODUCTION_BUILD } from '../shared/lib/constants'
import { eventLintCheckCompleted } from '../telemetry/events'
import { getProjectDir } from '../lib/get-project-dir'
import { findPagesDir } from '../lib/find-pages-dir'
import { verifyTypeScriptSetup } from '../lib/verify-typescript-setup'

export type NextLintOptions = {
  cache: boolean
  cacheLocation?: string
  cacheStrategy: string
  config?: string
  dir?: string[]
  errorOnUnmatchedPattern?: boolean
  file?: string[]
  fix?: boolean
  fixType?: string
  format?: string
  ignore: boolean
  outputFile?: string
  quiet?: boolean
  strict?: boolean
  // TODO(jiwon): ESLint v9 unsupported options
  // we currently delete them at `runLintCheck` when used in v9
  ext: string[]
  ignorePath?: string
  reportUnusedDisableDirectivesSeverity: 'error' | 'off' | 'warn'
  resolvePluginsRelativeTo?: string
  rulesdir?: string
  inlineConfig: boolean
  maxWarnings: number
}

const eslintOptions = (
  options: NextLintOptions,
  defaultCacheLocation: string
) => ({
  overrideConfigFile: options.config || null,
  extensions: options.ext ?? [],
  resolvePluginsRelativeTo: options.resolvePluginsRelativeTo || null,
  rulePaths: options.rulesdir ?? [],
  fix: options.fix ?? false,
  fixTypes: options.fixType ?? null,
  ignorePath: options.ignorePath || null,
  ignore: options.ignore,
  allowInlineConfig: options.inlineConfig,
  reportUnusedDisableDirectives:
    options.reportUnusedDisableDirectivesSeverity || null,
  cache: options.cache,
  cacheLocation: options.cacheLocation || defaultCacheLocation,
  cacheStrategy: options.cacheStrategy,
  errorOnUnmatchedPattern: options.errorOnUnmatchedPattern ?? false,
})

const nextLint = async (options: NextLintOptions, directory?: string) => {
  const baseDir = getProjectDir(directory)

  // Check if the provided directory exists
  if (!existsSync(baseDir)) {
    printAndExit(`> No such directory exists as the project root: ${baseDir}`)
  }

  const nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, baseDir)

  const files = options.file ?? []
  const dirs = options.dir ?? nextConfig.eslint?.dirs
  const filesToLint = [...(dirs ?? []), ...files]

  const pathsToLint = (
    filesToLint.length ? filesToLint : ESLINT_DEFAULT_DIRS
  ).reduce((res: string[], d: string) => {
    const currDir = isAbsolute(d) ? d : join(baseDir, d)

    if (!existsSync(currDir)) {
      return res
    }

    res.push(currDir)
    return res
  }, [])

  const reportErrorsOnly = Boolean(options.quiet)
  const maxWarnings = options.maxWarnings
  const formatter = options.format || null
  const strict = Boolean(options.strict)
  const outputFile = options.outputFile || null

  const distDir = join(baseDir, nextConfig.distDir)
  const defaultCacheLocation = join(distDir, 'cache', 'eslint/')
  const { pagesDir, appDir } = findPagesDir(baseDir)

  await verifyTypeScriptSetup({
    dir: baseDir,
    distDir: nextConfig.distDir,
    intentDirs: [pagesDir, appDir].filter(Boolean) as string[],
    typeCheckPreflight: false,
    tsconfigPath: nextConfig.typescript.tsconfigPath,
    disableStaticImages: nextConfig.images.disableStaticImages,
    hasAppDir: !!appDir,
    hasPagesDir: !!pagesDir,
  })

  runLintCheck(baseDir, pathsToLint, {
    lintDuringBuild: false,
    eslintOptions: eslintOptions(options, defaultCacheLocation),
    reportErrorsOnly,
    maxWarnings,
    formatter,
    outputFile,
    strict,
  })
    .then(async (lintResults) => {
      const lintOutput =
        typeof lintResults === 'string' ? lintResults : lintResults?.output

      if (typeof lintResults !== 'string' && lintResults?.eventInfo) {
        const telemetry = new Telemetry({
          distDir,
        })
        telemetry.record(
          eventLintCheckCompleted({
            ...lintResults.eventInfo,
            buildLint: false,
          })
        )
        await telemetry.flush()
      }

      if (
        typeof lintResults !== 'string' &&
        lintResults?.isError &&
        lintOutput
      ) {
        throw new CompileError(lintOutput)
      }

      if (lintOutput) {
        printAndExit(lintOutput, 0)
      } else if (lintResults && !lintOutput) {
        printAndExit(green('✔ No ESLint warnings or errors'), 0)
      } else {
        // this makes sure we exit 1 after the error from line 116
        // in packages/next/src/lib/eslint/runLintCheck
        process.exit(1)
      }
    })
    .catch((err) => {
      printAndExit(err.message)
    })
}

export { nextLint }