Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
chore(shared): enhance ESLint plugins and add type safety (#6654)
白熱73d893b88775
diff --git a/common/shared/esbuild/index.ts b/common/shared/esbuild/index.tsindex 9df3d13d9b..6ab289daad 100644--- a/common/shared/esbuild/index.ts+++ b/common/shared/esbuild/index.ts@@ -16,11 +16,36 @@import fs from 'fs-extra';-export function ignoreGlobalCssPlugin() {+interface IResolveArgs {+ importer: string;+ path: string;+}++interface ILoadArgs {+ path: string;+}++interface IPluginBuild {+ onResolve(+ options: { filter: RegExp; namespace?: string },+ callback: (args: IResolveArgs) => unknown+ ): void;+ onLoad(+ options: { filter: RegExp; namespace?: string },+ callback: (args: ILoadArgs) => unknown+ ): void;+}++interface IEsbuildPlugin {+ name: string;+ setup: (build: IPluginBuild) => void;+}++export function ignoreGlobalCssPlugin(): IEsbuildPlugin {return {name: 'ignore-global-css',- setup(build) {- build.onResolve({ filter: /\/global\.css$/ }, (args) => {+ setup(build: IPluginBuild) {+ build.onResolve({ filter: /\/global\.css$/ }, (args: IResolveArgs) => {if (args.importer.includes('packages')) {return {path: args.path,@@ -39,17 +64,17 @@ export function ignoreGlobalCssPlugin() {};}-export function removeClassnameNewlinesPlugin() {+export function removeClassnameNewlinesPlugin(): IEsbuildPlugin {return {name: 'remove-classname-newlines',- setup(build) {- build.onLoad({ filter: /\.(tsx)$/ }, (args) => {+ setup(build: IPluginBuild) {+ build.onLoad({ filter: /\.(tsx)$/ }, (args: ILoadArgs) => {const source = fs.readFileSync(args.path, 'utf8');const transformedSource = source.replace(/className\s*=\s*{([^}]*?)}/gs,- (match, classNameValue) => {- const cleanedValue = classNameValue.replace(/`([^`]*?)`/gs, (templateMatch, templateContent) => {+ (_match: string, classNameValue: string) => {+ const cleanedValue = classNameValue.replace(/`([^`]*?)`/gs, (_templateMatch: string, templateContent: string) => {return `\`${templateContent.replace(/\s*\n\s*/g, ' ').trim()}\``;});diff --git a/common/shared/eslint/plugins/no-external-imports-in-facade.ts b/common/shared/eslint/plugins/no-external-imports-in-facade.tsindex 4cb49b34bd..f2c8603010 100644--- a/common/shared/eslint/plugins/no-external-imports-in-facade.ts+++ b/common/shared/eslint/plugins/no-external-imports-in-facade.ts@@ -1,7 +1,21 @@/* eslint-disable header/header */+import type { Rule } from 'eslint';import path from 'node:path';-export default {+function getImportSourceValue(node: Rule.Node): string | null {+ if (!('source' in node)) {+ return null;+ }++ const source = (node as { source?: { value?: unknown } }).source;+ if (!source || typeof source.value !== 'string') {+ return null;+ }++ return source.value;+}++const rule: Rule.RuleModule = {meta: {type: 'problem',docs: {@@ -24,10 +38,10 @@ export default {const currentDir = path.dirname(filename);return {- ImportDeclaration(node) {- const importPath = node.source.value;+ ImportDeclaration(node: Rule.Node) {+ const importPath = getImportSourceValue(node);- if (importPath[0] !== '.') {+ if (!importPath || !importPath.startsWith('.')) {return;}@@ -44,3 +58,5 @@ export default {};},};++export default rule;diff --git a/common/shared/eslint/plugins/no-facade-imports-outside-facade.ts b/common/shared/eslint/plugins/no-facade-imports-outside-facade.tsindex 05d9f9810c..8f6dc49112 100644--- a/common/shared/eslint/plugins/no-facade-imports-outside-facade.ts+++ b/common/shared/eslint/plugins/no-facade-imports-outside-facade.ts@@ -1,12 +1,28 @@/* eslint-disable header/header */+import type { Rule } from 'eslint';import path from 'node:path';-function normalizePath(filePath) {+interface IRuleOptions { ignore?: unknown[] }++function getImportSourceValue(node: Rule.Node): string | null {+ if (!('source' in node)) {+ return null;+ }++ const source = (node as { source?: { value?: unknown } }).source;+ if (!source || typeof source.value !== 'string') {+ return null;+ }++ return source.value;+}++function normalizePath(filePath: string): string {return filePath.split(path.sep).join('/');}-function shouldIgnoreFile(normalizedFilePath, ignorePaths) {- return ignorePaths.some((ignorePath) => {+function shouldIgnoreFile(normalizedFilePath: string, ignorePaths: readonly unknown[]): boolean {+ return ignorePaths.some((ignorePath: unknown) => {if (typeof ignorePath !== 'string') {return false;}@@ -23,7 +39,7 @@ function shouldIgnoreFile(normalizedFilePath, ignorePaths) {});}-export default {+const rule: Rule.RuleModule = {meta: {type: 'problem',docs: {@@ -51,7 +67,7 @@ export default {create(context) {const filename = context.getFilename();const normalizedPath = normalizePath(filename);- const [ruleOptions = {}] = context.options;+ const [ruleOptions = {} as IRuleOptions] = context.options as [IRuleOptions?];const ignorePaths = Array.isArray(ruleOptions.ignore) ? ruleOptions.ignore : [];if (shouldIgnoreFile(normalizedPath, ignorePaths)) {@@ -71,23 +87,12 @@ export default {return {};}- const parentDir = parentDirMatch[1];- const packagePrefix = parentDir === 'univer'- ? '@univerjs/'- : parentDir === 'univer-pro'- ? '@univerjs-pro/'- : null;-- if (!packagePrefix) {- return {};- }-return {- ImportDeclaration(node) {- const importPath = node.source.value;+ ImportDeclaration(node: Rule.Node) {+ const importPath = getImportSourceValue(node);// Check if the import path contains 'facade'- if (importPath.includes('facade')) {+ if (importPath?.includes('facade')) {context.report({node,messageId: 'noFacadeImports',@@ -95,21 +100,19 @@ export default {});}},- ExportNamedDeclaration(node) {- if (node.source) {- const exportPath = node.source.value;- if (exportPath.includes('facade')) {- context.report({- node,- messageId: 'noFacadeImports',- data: { importPath: exportPath },- });- }+ ExportNamedDeclaration(node: Rule.Node) {+ const exportPath = getImportSourceValue(node);+ if (exportPath?.includes('facade')) {+ context.report({+ node,+ messageId: 'noFacadeImports',+ data: { importPath: exportPath },+ });}},- ExportAllDeclaration(node) {- const exportPath = node.source.value;- if (exportPath.includes('facade')) {+ ExportAllDeclaration(node: Rule.Node) {+ const exportPath = getImportSourceValue(node);+ if (exportPath?.includes('facade')) {context.report({node,messageId: 'noFacadeImports',@@ -120,3 +123,5 @@ export default {};},};++export default rule;diff --git a/common/shared/eslint/plugins/no-self-package-imports.ts b/common/shared/eslint/plugins/no-self-package-imports.tsindex 0d39394767..196a14dbb2 100644--- a/common/shared/eslint/plugins/no-self-package-imports.ts+++ b/common/shared/eslint/plugins/no-self-package-imports.ts@@ -1,7 +1,21 @@/* eslint-disable header/header */+import type { Rule } from 'eslint';import path from 'node:path';-export default {+function getImportSourceValue(node: Rule.Node): string | null {+ if (!('source' in node)) {+ return null;+ }++ const source = (node as { source?: { value?: unknown } }).source;+ if (!source || typeof source.value !== 'string') {+ return null;+ }++ return source.value;+}++const rule: Rule.RuleModule = {meta: {type: 'problem',docs: {@@ -50,10 +64,10 @@ export default {const possiblePackageName = `${packagePrefix}${packageName}`;return {- ImportDeclaration(node) {- const importPath = node.source.value;+ ImportDeclaration(node: Rule.Node) {+ const importPath = getImportSourceValue(node);- if (importPath === possiblePackageName) {+ if (importPath && importPath === possiblePackageName) {context.report({node,messageId: 'noSelfImport',@@ -67,3 +81,5 @@ export default {};},};++export default rule;diff --git a/common/shared/eslint/third-party.d.ts b/common/shared/eslint/third-party.d.tsnew file mode 100644index 0000000000..5977981d52--- /dev/null+++ b/common/shared/eslint/third-party.d.ts@@ -0,0 +1,3 @@+declare module 'eslint-plugin-header';+declare module 'eslint-plugin-no-barrel-import';+declare module 'eslint-plugin-no-penetrating-import';diff --git a/common/shared/package.json b/common/shared/package.jsonindex 20edaec47c..30ca1a1df0 100644--- a/common/shared/package.json+++ b/common/shared/package.json@@ -24,6 +24,9 @@"bin": {"univer-cli": "bin/index.ts"},+ "scripts": {+ "typecheck": "tsc --noEmit"+ },"dependencies": {"@typescript-eslint/parser": "^8.56.1","@vitejs/plugin-react": "^5.1.4",@@ -51,6 +54,7 @@"@types/fs-extra": "^11.0.4","@univerjs/icons": "^1.1.1","@univerjs/icons-svg": "^1.1.1",- "@univerjs/protocol": "0.1.48"+ "@univerjs/protocol": "0.1.48",+ "typescript": "^5.9.3"}}diff --git a/common/shared/tsconfig.json b/common/shared/tsconfig.jsonnew file mode 100644index 0000000000..7f88116494--- /dev/null+++ b/common/shared/tsconfig.json@@ -0,0 +1,19 @@+{+ "extends": "./tsconfigs/base.json",+ "compilerOptions": {+ "rootDir": ".",+ "skipLibCheck": true+ },+ "include": [+ "bin/**/*.ts",+ "esbuild/**/*.ts",+ "eslint/**/*.ts",+ "eslint/**/*.d.ts",+ "tailwind/**/*.ts",+ "vite/**/*.ts",+ "vitest/**/*.ts"+ ],+ "exclude": [+ "node_modules"+ ]+}diff --git a/common/shared/vite/auto-detected-external-plugin.ts b/common/shared/vite/auto-detected-external-plugin.tsindex 66f116e598..86813c5def 100644--- a/common/shared/vite/auto-detected-external-plugin.ts+++ b/common/shared/vite/auto-detected-external-plugin.ts@@ -19,7 +19,7 @@ import { peerDepsMap } from './data';import { convertLibNameFromPackageName } from './utils';export function autoDetectedExternalPlugin(): Plugin {- const globals = {};+ const globals: Record<string, string> = {};let hasCss = false;return {@@ -33,8 +33,9 @@ export function autoDetectedExternalPlugin(): Plugin {return null;}- if (source in peerDepsMap) {- globals[source] = peerDepsMap[source].global;+ if (Object.prototype.hasOwnProperty.call(peerDepsMap, source)) {+ const dep = peerDepsMap[source as keyof typeof peerDepsMap];+ globals[source] = dep.global;return { id: source, external: true };} else if (source.startsWith('@univerjs')) {diff --git a/common/shared/vite/index.ts b/common/shared/vite/index.tsindex 53e7efdba0..47c6058e40 100644--- a/common/shared/vite/index.ts+++ b/common/shared/vite/index.ts@@ -219,8 +219,8 @@ export async function build(options?: IBuildOptions) {},plugins: [trimClassNamePlugin(),- react(),- vue(),+ react({}),+ vue({}),autoDetectedExternalPlugin(),vitePluginExternal({nodeBuiltins: true,diff --git a/common/shared/vite/plugin-trim-classname-plugin.ts b/common/shared/vite/plugin-trim-classname-plugin.tsindex 07b81ad87c..70e672bd2e 100644--- a/common/shared/vite/plugin-trim-classname-plugin.ts+++ b/common/shared/vite/plugin-trim-classname-plugin.ts@@ -14,14 +14,16 @@* limitations under the License.*/-export function trimClassNamePlugin() {+import type { Plugin } from 'vite';++export function trimClassNamePlugin(): Plugin {return {name: 'vite-plugin-trim-classname',- transform(code, id) {+ transform(code: string, id: string) {if (id.endsWith('.tsx')) {const transformedCode = code.replace(/className: `([^`}]+)`/g,- (match, classNameValue) => {+ (_match: string, classNameValue: string) => {const cleanedClassName = classNameValue.replace(/\n/g, ' ').replace(/\s{2,}/g, ' ')@@ -30,7 +32,7 @@ export function trimClassNamePlugin() {}).replace(/clsx\(`([^`}]+)`/g,- (match, classNameValue) => {+ (_match: string, classNameValue: string) => {const cleanedClassName = classNameValue.replace(/\n/g, ' ').replace(/\s{2,}/g, ' ')diff --git a/packages/core/src/shared/compare.ts b/packages/core/src/shared/compare.tsindex 240bf993d8..ba4fa026f2 100644--- a/packages/core/src/shared/compare.ts+++ b/packages/core/src/shared/compare.ts@@ -16,11 +16,11 @@import type { ITextRun } from '../types/interfaces/i-document-data';-interface AnyObject {- [key: number | string]: AnyObject | AnyObject[] | Array<[number | string]> | any;+interface IAnyObject {+ [key: number | string]: IAnyObject | IAnyObject[] | Array<[number | string]> | any;}-export function deepCompare(arg1: AnyObject, arg2: AnyObject): boolean {+export function deepCompare(arg1: IAnyObject, arg2: IAnyObject): boolean {if (Object.prototype.toString.call(arg1) === Object.prototype.toString.call(arg2)) {if (Object.prototype.toString.call(arg1) === '[object Object]' ||@@ -29,7 +29,7 @@ export function deepCompare(arg1: AnyObject, arg2: AnyObject): boolean {if (Object.keys(arg1).length !== Object.keys(arg2).length) {return false;}- return Object.keys(arg1).every((key) => deepCompare(arg1[key] as AnyObject, arg2[key] as AnyObject));+ return Object.keys(arg1).every((key) => deepCompare(arg1[key] as IAnyObject, arg2[key] as IAnyObject));}return arg1 === arg2;}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex cc456bb063..095cfad75f 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -395,6 +395,9 @@ importers:'@univerjs/protocol':specifier: 0.1.48version: 0.1.48+ typescript:+ specifier: ^5.9.3+ version: 5.9.3common/storybook:dependencies: