1 import getMonorepoRoot from "../../utils/get-monorepo-root.js"
2 import { ESLint, Linter } from "eslint"
3 import path from "path"
4 import dirname from "../../utils/dirname.js"
5 import { minimatch } from "minimatch"
6 import { existsSync } from "fs"
7 import getRelativePaths from "../../utils/get-relative-paths.js"
8 import { formatWithPrettier } from "utils"
9
10 /**
11 * A class used to apply formatting to files using ESLint and other formatting options.
12 */
13 class Formatter {
14 protected cwd: string
15 protected eslintConfig?: Linter.Config
16 protected generalESLintConfig?: Linter.ConfigOverride<Linter.RulesRecord>
17 protected configForFile: Map<
18 string,
19 Linter.ConfigOverride<Linter.RulesRecord>
20 >
21
22 constructor() {
23 this.cwd = getMonorepoRoot()
24 this.configForFile = new Map()
25 }
26
27 /**
28 * Adds new lines before and after a comment if it's preceeded/followed immediately by a word (not by an empty line).
29 *
30 * @param {string} content - The content to format.
31 * @returns {string} The returned formatted content.
32 */
33 normalizeCommentNewLine(content: string): string {
34 return content
35 .replaceAll(/(.)\n(\s*)\/\*\*/g, "$1\n\n$2/**")
36 .replaceAll(/\*\/\s*(.)/g, "*/\n$1")
37 }
38
39 /**
40 * Normalizes an ESLint overrides configuration object. If a file name is specified, the configuration are normalized to
41 * include the `tsconfig` related to the file. If a file name isn't specified, the tsconfig file path names
42 * in the `parserConfig.project` array are normalized to have a full relative path (as that is required by ESLint).
43 *
44 * @param {Linter.ConfigOverride<Linter.RulesRecord>} config - The original configuration object.
45 * @param {string} fileName - The file name that
46 * @returns {Linter.ConfigOverride<Linter.RulesRecord>} The normalized and cloned configuration object.
47 */
48 normalizeOverridesConfigObject(
49 config: Linter.ConfigOverride<Linter.RulesRecord>,
50 fileName?: string
51 ): Linter.ConfigOverride<Linter.RulesRecord> {
52 // clone config
53 const newConfig = structuredClone(config)
54 if (!newConfig.parserOptions) {
55 return newConfig
56 }
57
58 if (fileName) {
59 const packagePattern = /^(?<packagePath>.*\/packages\/[^/]*).*$/
60 // try to manually set the project of the parser options
61 const matchFilePackage = packagePattern.exec(fileName)
62
63 if (matchFilePackage?.groups?.packagePath) {
64 const tsConfigPath = path.join(
65 matchFilePackage.groups.packagePath,
66 "tsconfig.json"
67 )
68 const tsConfigSpecPath = path.join(
69 matchFilePackage.groups.packagePath,
70 "tsconfig.spec.json"
71 )
72
73 newConfig.parserOptions.project = [
74 existsSync(tsConfigPath)
75 ? tsConfigPath
76 : existsSync(tsConfigSpecPath)
77 ? tsConfigSpecPath
78 : [
79 ...getRelativePaths(
80 newConfig.parserOptions.project || [],
81 this.cwd
82 ),
83 ],
84 ]
85 }
86 } else if (newConfig.parserOptions.project?.length) {
87 // fix parser projects paths to be relative to this script
88 newConfig.parserOptions.project = getRelativePaths(
89 newConfig.parserOptions.project as string[],
90 this.cwd
91 )
92 }
93
94 return newConfig
95 }
96
97 /**
98 * Retrieves the general ESLint configuration and sets it to the `eslintConfig` class property, if it's not already set.
99 * It also tries to set the `generalESLintConfig` class property to the override configuration in the `eslintConfig`
100 * whose `files` array includes `*.ts`.
101 */
102 async getESLintConfig() {
103 if (this.eslintConfig) {
104 return
105 }
106
107 this.eslintConfig = (
108 await import(
109 path.relative(
110 dirname(import.meta.url),
111 path.join(this.cwd, ".eslintrc.js")
112 )
113 )
114 ).default as Linter.Config
115
116 this.generalESLintConfig = this.eslintConfig!.overrides?.find((item) =>
117 item.files.includes("*.ts")
118 )
119
120 if (this.generalESLintConfig) {
121 this.generalESLintConfig = this.normalizeOverridesConfigObject(
122 this.generalESLintConfig
123 )
124 }
125 }
126
127 /**
128 * Retrieves the normalized ESLint overrides configuration for a specific file.
129 *
130 * @param {string} filePath - The file's path.
131 * @returns {Promise<Linter.ConfigOverride<Linter.RulesRecord> | undefined>} The normalized configuration object or `undefined` if not found.
132 */
133 async getESLintOverridesConfigForFile(
134 filePath: string
135 ): Promise<Linter.ConfigOverride<Linter.RulesRecord> | undefined> {
136 await this.getESLintConfig()
137
138 if (this.configForFile.has(filePath)) {
139 return this.configForFile.get(filePath)!
140 }
141
142 let relevantConfig = this.eslintConfig!.overrides?.find((item) => {
143 if (typeof item.files === "string") {
144 return minimatch(filePath, item.files)
145 }
146
147 return item.files.some((file) => minimatch(filePath, file))
148 })
149
150 if (!relevantConfig && !this.generalESLintConfig) {
151 return undefined
152 }
153
154 relevantConfig = this.normalizeOverridesConfigObject(
155 structuredClone(relevantConfig || this.generalESLintConfig!),
156 filePath
157 )
158
159 relevantConfig!.files = [path.relative(this.cwd, filePath)]
160
161 this.configForFile.set(filePath, relevantConfig)
162
163 return relevantConfig
164 }
165
166 /**
167 * Formats a string with ESLint.
168 *
169 * @param {string} content - The content to format.
170 * @param {string} fileName - The path to the file that the content belongs to.
171 * @returns {Promise<string>} The formatted content.
172 */
173 async formatStrWithEslint(
174 content: string,
175 fileName: string
176 ): Promise<string> {
177 const prettifiedContent = await formatWithPrettier(content, fileName)
178 const relevantConfig = await this.getESLintOverridesConfigForFile(fileName)
179
180 const eslint = new ESLint({
181 overrideConfig: {
182 ...this.eslintConfig,
183 overrides: relevantConfig ? [relevantConfig] : undefined,
184 },
185 cwd: this.cwd,
186 resolvePluginsRelativeTo: this.cwd,
187 fix: true,
188 ignore: false,
189 })
190
191 let newContent = prettifiedContent
192 const result = await eslint.lintText(prettifiedContent, {
193 filePath: fileName,
194 })
195
196 if (result.length) {
197 newContent = result[0].output || newContent
198 }
199
200 return newContent
201 }
202
203 /**
204 * Applies all formatting types to a string.
205 *
206 * @param {string} content - The content to format.
207 * @param {string} fileName - The path to the file that holds the content.
208 * @returns {Promise<string>} The formatted content.
209 */
210 async formatStr(content: string, fileName: string): Promise<string> {
211 const newContent = await this.formatStrWithEslint(content, fileName)
212
213 let normalizedContent = this.normalizeCommentNewLine(newContent)
214
215 if (normalizedContent !== newContent) {
216 /**
217 * Since adding the new lines after comments as done in {@link normalizeCommentNewLine} method may lead to linting errors,
218 * we have to rerun the {@link formatStrWithEslint}. It's not possible to run {@link normalizeCommentNewLine} the first time
219 * and provide the expected result.
220 */
221 normalizedContent = await this.formatStrWithEslint(
222 normalizedContent,
223 fileName
224 )
225 }
226
227 return normalizedContent
228 }
229
230 /**
231 * Adds comments of a source file to the top of the file's content. It should have additional extra line after the comment.
232 * If the comment's length is 0, the `content` is returned as is.
233 *
234 * @param {string} comment - The comments of the source file.
235 * @param {string} content - The source file's comments.
236 * @returns {string} The full content with the comments.
237 */
238 addCommentsToSourceFile(comment: string, content: string): string {
239 return comment.length ? `/**\n ${comment}*/\n\n${content}` : content
240 }
241 }
242
243 export default Formatter