From 0b7be6660315926d1f49c8301fecf2b87d7a2b98 Mon Sep 17 00:00:00 2001 From: Rui Wu Date: Wed, 11 Sep 2024 18:41:50 +0800 Subject: [PATCH] chore: biome fix --- packages/core/build.config.ts | 14 ++-- packages/core/src/constants.ts | 17 +++-- packages/core/src/index.ts | 84 ++++++++++++--------- packages/core/src/types.ts | 8 +- packages/core/src/utils.ts | 130 ++++++++++++++++++--------------- packages/core/src/worker.ts | 25 ++++--- 6 files changed, 156 insertions(+), 122 deletions(-) diff --git a/packages/core/build.config.ts b/packages/core/build.config.ts index a2d3b14..25f9139 100644 --- a/packages/core/build.config.ts +++ b/packages/core/build.config.ts @@ -1,21 +1,21 @@ -import { unlinkSync } from 'node:fs'; -import { resolve } from 'node:path'; -import { defineBuildConfig } from 'unbuild'; +import { unlinkSync } from "node:fs"; +import { resolve } from "node:path"; +import { defineBuildConfig } from "unbuild"; export default defineBuildConfig({ - entries: ['src/index', 'src/worker'], + entries: ["src/index", "src/worker"], clean: true, declaration: true, rollup: { emitCJS: true, inlineDependencies: true, esbuild: { - target: 'node14.18', + target: "node18", }, }, hooks: { - 'build:done': (ctx) => { - unlinkSync(resolve(ctx.options.outDir, 'worker.d.ts')); + "build:done": (ctx) => { + unlinkSync(resolve(ctx.options.outDir, "worker.d.ts")); }, }, }); diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts index 330e694..be298cd 100644 --- a/packages/core/src/constants.ts +++ b/packages/core/src/constants.ts @@ -1,5 +1,5 @@ -import type { Colors } from 'picocolors/types'; -import type { TextType } from './types'; +import type { Colors } from "picocolors/types"; +import type { TextType } from "./types"; export const ESLINT_SEVERITY = { ERROR: 2, @@ -8,10 +8,13 @@ export const ESLINT_SEVERITY = { export const CWD = process.cwd(); -export const PLUGIN_NAME = 'vite:eslint2'; +export const PLUGIN_NAME = "vite:eslint2"; -export const COLOR_MAPPING: Record> = { - error: 'red', - warning: 'yellow', - plugin: 'magenta', +export const COLOR_MAPPING: Record< + TextType, + keyof Omit +> = { + error: "red", + warning: "yellow", + plugin: "magenta", }; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 4a46fe6..c48b415 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,32 +1,34 @@ -import { Worker } from 'node:worker_threads'; -import { dirname, extname, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import type * as Vite from 'vite'; -import type { FSWatcher } from 'chokidar'; -import chokidar from 'chokidar'; -import debugWrap from 'debug'; +import { dirname, extname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { Worker } from "node:worker_threads"; +import type { FSWatcher } from "chokidar"; +import chokidar from "chokidar"; +import debugWrap from "debug"; +import type * as Vite from "vite"; +import { CWD, PLUGIN_NAME } from "./constants"; +import type { + ESLintFormatter, + ESLintInstance, + ESLintOutputFixes, + ESLintPluginUserOptions, +} from "./types"; import { - getOptions, + getFilePath, getFilter, - shouldIgnoreModule, + getOptions, initializeESLint, lintFiles, - getFilePath, -} from './utils'; -import type { - ESLintPluginUserOptions, - ESLintInstance, - ESLintFormatter, - ESLintOutputFixes, -} from './types'; -import { PLUGIN_NAME, CWD } from './constants'; + shouldIgnoreModule, +} from "./utils"; const debug = debugWrap(PLUGIN_NAME); const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const ext = extname(__filename); -export default function ESLintPlugin(userOptions: ESLintPluginUserOptions = {}): Vite.Plugin { +export default function ESLintPlugin( + userOptions: ESLintPluginUserOptions = {}, +): Vite.Plugin { const options = getOptions(userOptions); let worker: Worker; @@ -40,31 +42,34 @@ export default function ESLintPlugin(userOptions: ESLintPluginUserOptions = {}): return { name: PLUGIN_NAME, apply(config, { command }) { - debug(`==== apply hook ====`); - if (config.mode === 'test' || process.env.VITEST) return options.test; + debug("==== apply hook ===="); + if (config.mode === "test" || process.env.VITEST) return options.test; const shouldApply = - (command === 'serve' && options.dev) || (command === 'build' && options.build); + (command === "serve" && options.dev) || + (command === "build" && options.build); debug(`should apply this plugin: ${shouldApply}`); return shouldApply; }, async buildStart() { - debug(`==== buildStart hook ====`); + debug("==== buildStart hook ===="); // initialize worker if (options.lintInWorker) { if (worker) return; - debug(`Initialize worker`); - worker = new Worker(resolve(__dirname, `worker${ext}`), { workerData: { options } }); + debug("Initialize worker"); + worker = new Worker(resolve(__dirname, `worker${ext}`), { + workerData: { options }, + }); return; } // initialize ESLint - debug(`Initial ESLint`); + debug("Initial ESLint"); const result = await initializeESLint(options); eslintInstance = result.eslintInstance; formatter = result.formatter; outputFixes = result.outputFixes; // lint on start if needed if (options.lintOnStart) { - debug(`Lint on start`); + debug("Lint on start"); await lintFiles( { files: options.include, @@ -78,20 +83,24 @@ export default function ESLintPlugin(userOptions: ESLintPluginUserOptions = {}): } }, async transform(_, id) { - debug('==== transform hook ===='); + debug("==== transform hook ===="); // initialize watcher if (options.chokidar) { if (watcher) return; - debug(`Initialize watcher`); + debug("Initialize watcher"); watcher = chokidar .watch(options.include, { ignored: options.exclude }) - .on('change', async (path) => { - debug(`==== change event ====`); + .on("change", async (path) => { + debug("==== change event ===="); const fullPath = resolve(CWD, path); // worker + watcher if (worker) return worker.postMessage(fullPath); // watcher only - const shouldIgnore = await shouldIgnoreModule(fullPath, filter, eslintInstance); + const shouldIgnore = await shouldIgnoreModule( + fullPath, + filter, + eslintInstance, + ); debug(`should ignore: ${shouldIgnore}`); if (shouldIgnore) return; return await lintFiles( @@ -108,9 +117,9 @@ export default function ESLintPlugin(userOptions: ESLintPluginUserOptions = {}): return; } // no watcher - debug('id: ', id); + debug(`id: ${id}`); const filePath = getFilePath(id); - debug(`filePath`, filePath); + debug(`filePath: ${filePath}`); // worker if (worker) return worker.postMessage(filePath); // no worker @@ -129,10 +138,13 @@ export default function ESLintPlugin(userOptions: ESLintPluginUserOptions = {}): ); }, async buildEnd() { - debug('==== buildEnd ===='); + debug("==== buildEnd ===="); if (watcher?.close) await watcher.close(); }, }; } -export { type ESLintPluginOptions, type ESLintPluginUserOptions } from './types'; +export { + type ESLintPluginOptions, + type ESLintPluginUserOptions, +} from "./types"; diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index d95d3d9..4ad3090 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -1,6 +1,6 @@ -import type * as ESLint from 'eslint'; -import type * as Rollup from 'rollup'; -import type { CreateFilter } from '@rollup/pluginutils'; +import type { CreateFilter } from "@rollup/pluginutils"; +import type * as ESLint from "eslint"; +import type * as Rollup from "rollup"; export type FilterPattern = string | string[]; export type Filter = ReturnType; @@ -256,4 +256,4 @@ export type LintFiles = ( context?: Rollup.PluginContext, ) => Promise; -export type TextType = 'error' | 'warning' | 'plugin'; +export type TextType = "error" | "warning" | "plugin"; diff --git a/packages/core/src/utils.ts b/packages/core/src/utils.ts index 11d93ea..b50e331 100644 --- a/packages/core/src/utils.ts +++ b/packages/core/src/utils.ts @@ -1,6 +1,7 @@ -import pico from 'picocolors'; -import { createFilter, normalizePath } from '@rollup/pluginutils'; -import type * as Rollup from 'rollup'; +import { createFilter, normalizePath } from "@rollup/pluginutils"; +import pico from "picocolors"; +import type * as Rollup from "rollup"; +import { COLOR_MAPPING, ESLINT_SEVERITY, PLUGIN_NAME } from "./constants"; import type { ESLintConstructorOptions, ESLintInstance, @@ -11,8 +12,7 @@ import type { Filter, LintFiles, TextType, -} from './types'; -import { COLOR_MAPPING, ESLINT_SEVERITY, PLUGIN_NAME } from './constants'; +} from "./types"; export function interopDefault(m: any) { return m.default || m; @@ -42,11 +42,11 @@ export const getOptions = ({ dev: dev ?? true, build: build ?? false, cache: cache ?? true, - cacheLocation: cacheLocation ?? '.eslintcache', - include: include ?? ['src/**/*.{js,jsx,ts,tsx,vue,svelte}'], - exclude: exclude ?? ['node_modules', 'virtual:'], - eslintPath: eslintPath ?? 'eslint', - formatter: formatter ?? 'stylish', + cacheLocation: cacheLocation ?? ".eslintcache", + include: include ?? ["src/**/*.{js,jsx,ts,tsx,vue,svelte}"], + exclude: exclude ?? ["node_modules", "virtual:"], + eslintPath: eslintPath ?? "eslint", + formatter: formatter ?? "stylish", lintInWorker: lintInWorker ?? false, lintOnStart: lintOnStart ?? false, lintDirtyOnly: lintDirtyOnly ?? true, @@ -68,21 +68,21 @@ export const getESLintConstructorOptions = ( Object.entries(options).filter( ([key]) => ![ - 'test', - 'dev', - 'build', - 'include', - 'exclude', - 'eslintPath', - 'formatter', - 'lintInWorker', - 'lintOnStart', - 'lintDirtyOnly', - 'chokidar', - 'emitError', - 'emitErrorAsWarning', - 'emitWarning', - 'emitWarningAsError', + "test", + "dev", + "build", + "include", + "exclude", + "eslintPath", + "formatter", + "lintInWorker", + "lintOnStart", + "lintDirtyOnly", + "chokidar", + "emitError", + "emitErrorAsWarning", + "emitWarning", + "emitWarningAsError", ].includes(key), ), ), @@ -97,9 +97,13 @@ export const initializeESLint = async (options: ESLintPluginOptions) => { const ESLintClass = module.loadESLint ? await module.loadESLint() : module.ESLint || module.FlatESLint || module.LegacyESLint; - const eslintInstance = new ESLintClass(getESLintConstructorOptions(options)) as ESLintInstance; + const eslintInstance = new ESLintClass( + getESLintConstructorOptions(options), + ) as ESLintInstance; const loadedFormatter = await eslintInstance.loadFormatter(formatter); - const outputFixes = ESLintClass.outputFixes.bind(ESLintClass) as ESLintOutputFixes; + const outputFixes = ESLintClass.outputFixes.bind( + ESLintClass, + ) as ESLintOutputFixes; return { eslintInstance, formatter: loadedFormatter, @@ -115,9 +119,9 @@ export const initializeESLint = async (options: ESLintPluginOptions) => { // https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/importMetaGlob.ts // https://vitejs.dev/guide/api-plugin.html#virtual-modules-convention export const isVirtualModule = (id: string) => - id.startsWith('virtual:') || id[0] === '\0' || !id.includes('/'); + id.startsWith("virtual:") || id[0] === "\0" || !id.includes("/"); -export const getFilePath = (id: string) => normalizePath(id).split('?')[0]; +export const getFilePath = (id: string) => normalizePath(id).split("?")[0]; export const shouldIgnoreModule = async ( id: string, @@ -131,9 +135,9 @@ export const shouldIgnoreModule = async ( // xxx.vue?type=style or yyy.svelte?type=style style modules const filePath = getFilePath(id); if ( - ['.vue', '.svelte'].some((extname) => filePath.endsWith(extname)) && - id.includes('?') && - id.includes('type=style') + [".vue", ".svelte"].some((extname) => filePath.endsWith(extname)) && + id.includes("?") && + id.includes("type=style") ) { return true; } @@ -180,15 +184,23 @@ export const removeESLintWarningResults = (results: ESLintLintResults) => export const filterESLintLintResults = (results: ESLintLintResults) => results.filter((result) => result.errorCount > 0 || result.warningCount > 0); -export const colorize = (text: string, textType: TextType) => pico[COLOR_MAPPING[textType]](text); +export const colorize = (text: string, textType: TextType) => + pico[COLOR_MAPPING[textType]](text); -export const log = (text: string, textType: TextType, context?: Rollup.PluginContext) => { - console.log(''); +export const log = ( + text: string, + textType: TextType, + context?: Rollup.PluginContext, +) => { + console.log(""); if (context) { - if (textType === 'error') context.error(text); - else if (textType === 'warning') context.warn(text); + if (textType === "error") context.error(text); + else if (textType === "warning") context.warn(text); } else { - const t = colorize(`${text} Plugin: ${colorize(PLUGIN_NAME, 'plugin')}\r\n`, textType); + const t = colorize( + `${text} Plugin: ${colorize(PLUGIN_NAME, "plugin")}\r\n`, + textType, + ); console.log(t); } }; @@ -197,24 +209,26 @@ export const lintFiles: LintFiles = async ( { files, eslintInstance, formatter, outputFixes, options }, context, ) => - await eslintInstance.lintFiles(files).then(async (lintResults: ESLintLintResults | void) => { - // do nothing if there are no results - if (!lintResults || lintResults.length === 0) return; - // output fixes - if (options.fix) outputFixes(lintResults); - // filter results - let results = [...lintResults]; - if (!options.emitError) results = removeESLintErrorResults(results); - if (!options.emitWarning) results = removeESLintWarningResults(results); - results = filterESLintLintResults(results); - if (results.length === 0) return; + await eslintInstance + .lintFiles(files) + .then(async (lintResults: ESLintLintResults) => { + // do nothing if there are no results + if (!lintResults || lintResults.length === 0) return; + // output fixes + if (options.fix) outputFixes(lintResults); + // filter results + let results = [...lintResults]; + if (!options.emitError) results = removeESLintErrorResults(results); + if (!options.emitWarning) results = removeESLintWarningResults(results); + results = filterESLintLintResults(results); + if (results.length === 0) return; - const formattedText = await formatter.format(results); - let formattedTextType: TextType; - if (results.some((result) => result.errorCount > 0)) { - formattedTextType = options.emitErrorAsWarning ? 'warning' : 'error'; - } else { - formattedTextType = options.emitWarningAsError ? 'error' : 'warning'; - } - return log(formattedText, formattedTextType, context); - }); + const formattedText = await formatter.format(results); + let formattedTextType: TextType; + if (results.some((result) => result.errorCount > 0)) { + formattedTextType = options.emitErrorAsWarning ? "warning" : "error"; + } else { + formattedTextType = options.emitWarningAsError ? "error" : "warning"; + } + return log(formattedText, formattedTextType, context); + }); diff --git a/packages/core/src/worker.ts b/packages/core/src/worker.ts index 0155fea..94c8289 100644 --- a/packages/core/src/worker.ts +++ b/packages/core/src/worker.ts @@ -1,13 +1,18 @@ -import { workerData, parentPort } from 'node:worker_threads'; -import debugWrap from 'debug'; +import { parentPort, workerData } from "node:worker_threads"; +import debugWrap from "debug"; +import { PLUGIN_NAME } from "./constants"; import type { - ESLintInstance, ESLintFormatter, + ESLintInstance, ESLintOutputFixes, ESLintPluginOptions, -} from './types'; -import { getFilter, initializeESLint, lintFiles, shouldIgnoreModule } from './utils'; -import { PLUGIN_NAME } from './constants'; +} from "./types"; +import { + getFilter, + initializeESLint, + lintFiles, + shouldIgnoreModule, +} from "./utils"; const debug = debugWrap(`${PLUGIN_NAME}:worker`); @@ -20,13 +25,13 @@ let outputFixes: ESLintOutputFixes; // this file needs to be compiled into cjs, which doesn't support top-level await // so we use iife here (async () => { - debug(`Initialize ESLint`); + debug("Initialize ESLint"); const result = await initializeESLint(options); eslintInstance = result.eslintInstance; formatter = result.formatter; outputFixes = result.outputFixes; if (options.lintOnStart) { - debug(`Lint on start`); + debug("Lint on start"); lintFiles({ files: options.include, eslintInstance, @@ -37,8 +42,8 @@ let outputFixes: ESLintOutputFixes; } })(); -parentPort?.on('message', async (files) => { - debug(`==== message event ====`); +parentPort?.on("message", async (files) => { + debug("==== message event ===="); debug(`message: ${files}`); const shouldIgnore = await shouldIgnoreModule(files, filter, eslintInstance); debug(`should ignore: ${shouldIgnore}`);