Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(tooling): migrate remaining sources to TypeScript (#44410)

Stephen Zhoub735f8473357
diff --git a/package.json b/package.json
index a17d95c57ee..3f3e4ee2f1c 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,7 @@
"dev": "concurrently -k -n vinext,proxy \"vp run dify-web#dev\" \"vp run dify-web#dev:proxy\"",
"knip": "knip --workspace web",
"knip:production": "knip --workspace web --production --include files",
- "knip:production-unused-check": "node ./packages/tooling/scripts/check-web-production-unused-after-knip-fix.mjs",
+ "knip:production-unused-check": "node ./packages/tooling/scripts/check-web-production-unused-after-knip-fix.ts",
"prepare": "vp config",
"lint:oxlint": "vp lint",
"lint:oxlint:fix": "vp lint --fix",
diff --git a/packages/tooling/README.md b/packages/tooling/README.md
index 00526cfcf25..85686e7aa8f 100644
--- a/packages/tooling/README.md
+++ b/packages/tooling/README.md
@@ -6,7 +6,7 @@ Vite+ provides the primary static check through `vp check`, which combines Oxfmt
custom rules, and dead-code tooling. Edit the implementations here:
- `repository.config.ts`: repository Vite+ lint, format, staged checks, and cached check task.
-- `lint.config.ts`, `eslint.mjs`, and `tsslint.config.ts`: rule configurations.
+- `lint.config.ts`, `eslint.ts`, and `tsslint.config.ts`: rule configurations.
- `plugins/`: custom rules, their fixtures, and tests.
- `knip.config.ts`, `a11y.config.ts`, `oxlint.unused.config.json`, and `scripts/`: targeted checks.
- `package.json`: plugin dependencies and the tooling package's test and type-check scripts.
@@ -85,13 +85,13 @@ vp run -w lint:eslint package.json pnpm-workspace.yaml web/docs
vp run -w lint:eslint:fix package.json pnpm-workspace.yaml web/docs
```
-Oxlint and Vite+ type-check scope is defined by `packages/tooling/lint.config.ts` `ignorePatterns`, and ESLint's scope is defined by `packages/tooling/eslint.mjs` global ignores.
+Oxlint and Vite+ type-check scope is defined by `packages/tooling/lint.config.ts` `ignorePatterns`, and ESLint's scope is defined by `packages/tooling/eslint.ts` global ignores.
The primary rule baseline lives in `packages/tooling/lint.config.ts` and is connected through the root `vite.config.ts` `lint` block. Oxlint-native rules are preferred, and compatible ESLint rules can run through Oxlint's `jsPlugins` support. The rules are explicit snapshots of the ESLint configurations that were active at migration time. Do not import an upstream preset wholesale: enable a new rule intentionally and review its existing violations first.
Tailwind canonical class cleanup is optional because loading the JavaScript plugin adds noticeable lint startup time. The default `vp run -w check` command does not load it. Run `vp run -w lint:tailwind` to inspect `web/` and `packages/dify-ui/`, or `vp run -w lint:tailwind:fix` to apply safe replacements. Both commands run the complete lint configuration with the additional `better-tailwindcss/enforce-canonical-classes` rule, using `web/app/styles/globals.css` and a 16px root font size.
-The non-code baseline and its repository-wide file scope live in `packages/tooling/eslint.mjs`. ESLint checks JSON, JSONC, JSON5, YAML, and Markdown only. The configuration globally ignores JavaScript, JSX, TypeScript, TSX, and declaration files; a comment-only inventory records the removed code checks as a migration tradeoff. It does not import or depend on the Antfu ESLint config.
+The non-code baseline and its repository-wide file scope live in `packages/tooling/eslint.ts`. ESLint checks JSON, JSONC, JSON5, YAML, and Markdown only. The configuration globally ignores JavaScript, JSX, TypeScript, TSX, and declaration files; a comment-only inventory records the removed code checks as a migration tradeoff. It does not import or depend on the Antfu ESLint config.
### Type-aware Linting
@@ -134,7 +134,7 @@ ESLint is intentionally limited to non-code files. The remaining limitations and
| Markdown code blocks | ESLint validates the Markdown document, but fenced JavaScript and TypeScript blocks are not passed through the former overlapping preset. This remains deferred rather than duplicating the Oxlint rule set. |
| Override-scoped settings | The three Dify UI Tailwind rules are disabled with the rest of ESLint's code path. Oxlint still applies the web `react-x.additionalStateHooks` setting globally because it cannot scope settings to an override. |
-Suppression comments belong to exactly one linter. Use `oxlint-disable` for code rules from `packages/tooling/lint.config.ts`, and use `eslint-disable` only for non-code rules from `packages/tooling/eslint.mjs`. Oxlint deliberately sets `respectEslintDisableDirectives` to `false`, so an ESLint comment cannot hide an Oxlint finding.
+Suppression comments belong to exactly one linter. Use `oxlint-disable` for code rules from `packages/tooling/lint.config.ts`, and use `eslint-disable` only for non-code rules from `packages/tooling/eslint.ts`. Oxlint deliberately sets `respectEslintDisableDirectives` to `false`, so an ESLint comment cannot hide an Oxlint finding.
### Inline Disable Comments
diff --git a/packages/tooling/eslint.mjs b/packages/tooling/eslint.ts
similarity index 98%
rename from packages/tooling/eslint.mjs
rename to packages/tooling/eslint.ts
index 93bfcd04389..891230985cb 100644
--- a/packages/tooling/eslint.mjs
+++ b/packages/tooling/eslint.ts
@@ -1,6 +1,4 @@
-// @ts-check
-/// <reference types="node" />
-
+import type { ESLint } from 'eslint'
import markdown from '@eslint/markdown'
import gitignore from 'eslint-config-flat-gitignore'
import md from 'eslint-markdown'
@@ -10,10 +8,10 @@ import pnpm from 'eslint-plugin-pnpm'
import yml from 'eslint-plugin-yml'
import { defineConfig, globalIgnores } from 'eslint/config'
import { repositoryRoot } from './paths.ts'
-import dify from './plugins/eslint/index.js'
+import dify from './plugins/eslint/index.ts'
const codeFiles = '**/*.{js,cjs,mjs,jsx,ts,cts,mts,tsx}'
-const mdPlugin = /** @type {import('eslint').ESLint.Plugin} */ (/** @type {unknown} */ (md))
+const mdPlugin = md as unknown as ESLint.Plugin
/**
* Migration tradeoff: ESLint is intentionally restricted to non-code files.
diff --git a/packages/tooling/lint.config.ts b/packages/tooling/lint.config.ts
index a43be5ebc55..f52c14a5bca 100644
--- a/packages/tooling/lint.config.ts
+++ b/packages/tooling/lint.config.ts
@@ -257,7 +257,7 @@ export const lintConfig = {
...(enableTailwindCanonicalClasses ? ['eslint-plugin-better-tailwindcss'] : []),
{
name: 'dify',
- specifier: './plugins/eslint/index.js',
+ specifier: './plugins/eslint/index.ts',
},
{
name: 'eslint-react',
diff --git a/packages/tooling/package.json b/packages/tooling/package.json
index 46c3b2eae13..eecd0798798 100644
--- a/packages/tooling/package.json
+++ b/packages/tooling/package.json
@@ -4,12 +4,12 @@
"private": true,
"type": "module",
"exports": {
- "./eslint": "./eslint.mjs",
+ "./eslint": "./eslint.ts",
"./oxlint": "./lint.config.ts",
"./tsslint": "./tsslint.config.ts",
"./knip": "./knip.config.ts",
"./repository": "./repository.config.ts",
- "./eslint-plugin": "./plugins/eslint/index.js",
+ "./eslint-plugin": "./plugins/eslint/index.ts",
"./i18n-plurals": "./i18n-plurals.ts"
},
"scripts": {
@@ -44,6 +44,8 @@
"devDependencies": {
"@dify/tsconfig": "workspace:*",
"@types/node": "catalog:",
+ "@typescript-eslint/utils": "catalog:",
+ "jsonc-eslint-parser": "catalog:",
"vite": "catalog:"
},
"peerDependencies": {
diff --git a/packages/tooling/plugins/eslint/index.js b/packages/tooling/plugins/eslint/index.ts
similarity index 70%
rename from packages/tooling/plugins/eslint/index.js
rename to packages/tooling/plugins/eslint/index.ts
index 6ede72704e2..9e4e4f3ca62 100644
--- a/packages/tooling/plugins/eslint/index.js
+++ b/packages/tooling/plugins/eslint/index.ts
@@ -1,15 +1,15 @@
-import consistentPlaceholders from './rules/consistent-placeholders.js'
-import i18nFlatKey from './rules/i18n-flat-key.js'
-import noExtraKeys from './rules/no-extra-keys.js'
-import noFileWideDisable from './rules/no-file-wide-disable.js'
-import preferTailwindIcons from './rules/prefer-tailwind-icons.js'
-import requireDisableDirectiveDescription from './rules/require-disable-directive-description.js'
-import requireI18nNamespace from './rules/require-i18n-namespace.js'
-import requireTFunctionNamespace from './rules/require-t-function-namespace.js'
-import requireTitleForTruncatedText from './rules/require-title-for-truncated-text.js'
+import type { ESLint } from 'eslint'
+import consistentPlaceholders from './rules/consistent-placeholders.ts'
+import i18nFlatKey from './rules/i18n-flat-key.ts'
+import noExtraKeys from './rules/no-extra-keys.ts'
+import noFileWideDisable from './rules/no-file-wide-disable.ts'
+import preferTailwindIcons from './rules/prefer-tailwind-icons.ts'
+import requireDisableDirectiveDescription from './rules/require-disable-directive-description.ts'
+import requireI18nNamespace from './rules/require-i18n-namespace.ts'
+import requireTFunctionNamespace from './rules/require-t-function-namespace.ts'
+import requireTitleForTruncatedText from './rules/require-title-for-truncated-text.ts'
-/** @type {import('eslint').ESLint.Plugin} */
-const plugin = {
+const plugin: ESLint.Plugin = {
meta: {
name: 'dify',
version: '1.0.0',
diff --git a/packages/tooling/plugins/eslint/rules/consistent-placeholders.js b/packages/tooling/plugins/eslint/rules/consistent-placeholders.ts
similarity index 75%
rename from packages/tooling/plugins/eslint/rules/consistent-placeholders.js
rename to packages/tooling/plugins/eslint/rules/consistent-placeholders.ts
index 0c08eae5a15..2733db4adb2 100644
--- a/packages/tooling/plugins/eslint/rules/consistent-placeholders.js
+++ b/packages/tooling/plugins/eslint/rules/consistent-placeholders.ts
@@ -1,14 +1,17 @@
+import type { Rule } from 'eslint'
+import type { AST } from 'jsonc-eslint-parser'
+import type { JsonRuleModule } from '../utils.ts'
import fs from 'node:fs'
import path, { normalize, sep } from 'node:path'
import { getTranslationSourceKey } from '../../../i18n-plurals.ts'
-import { cleanJsonText } from '../utils.js'
+import { cleanJsonText } from '../utils.ts'
-function extractPlaceholders(str) {
+function extractPlaceholders(str: string) {
const matches = str.match(/\{\{\w+\}\}/g) || []
return matches.map((m) => m.slice(2, -2)).sort()
}
-function extractTagMarkers(str) {
+function extractTagMarkers(str: string) {
const matches = Array.from(str.matchAll(/<\/?([A-Z][\w-]*)\b[^>]*>/gi))
const markers = matches.map((match) => {
const fullMatch = match[0]
@@ -24,27 +27,31 @@ function extractTagMarkers(str) {
return markers.sort()
}
-function formatTagMarker(marker) {
+function formatTagMarker(marker: string) {
if (marker.startsWith('close:')) return marker.slice('close:'.length)
if (marker.startsWith('self:')) return marker.slice('self:'.length)
return marker.slice('open:'.length)
}
-function arraysEqual(arr1, arr2) {
+function arraysEqual(arr1: string[], arr2: string[]) {
if (arr1.length !== arr2.length) return false
return arr1.every((val, i) => val === arr2[i])
}
-function uniqueSorted(items) {
+function uniqueSorted(items: string[]) {
return Array.from(new Set(items)).sort()
}
-function getJsonLiteralValue(node) {
+function getJsonLiteralValue(node: AST.JSONNode | undefined) {
if (!node) return undefined
return node.type === 'JSONLiteral' ? node.value : undefined
}
-function buildPlaceholderMessage(key, englishPlaceholders, currentPlaceholders) {
+function buildPlaceholderMessage(
+ key: string,
+ englishPlaceholders: string[],
+ currentPlaceholders: string[],
+) {
const missing = englishPlaceholders.filter((p) => !currentPlaceholders.includes(p))
const extra = currentPlaceholders.filter((p) => !englishPlaceholders.includes(p))
@@ -58,7 +65,7 @@ function buildPlaceholderMessage(key, englishPlaceholders, currentPlaceholders)
)
}
-function buildTagMessage(key, englishTagMarkers, currentTagMarkers) {
+function buildTagMessage(key: string, englishTagMarkers: string[], currentTagMarkers: string[]) {
const missing = englishTagMarkers.filter((p) => !currentTagMarkers.includes(p))
const extra = currentTagMarkers.filter((p) => !englishTagMarkers.includes(p))
@@ -73,7 +80,7 @@ function buildTagMessage(key, englishTagMarkers, currentTagMarkers) {
)
}
-export default {
+const rule: JsonRuleModule = {
meta: {
type: 'problem',
docs: {
@@ -81,22 +88,25 @@ export default {
},
},
create(context) {
- const state = {
+ const state: {
+ enabled: boolean
+ englishJson: Record<string, unknown> | null
+ englishKeys: Set<string>
+ language: string
+ } = {
enabled: false,
englishJson: null,
englishKeys: new Set(),
language: 'en-US',
}
- function isTopLevelProperty(node) {
+ function isTopLevelProperty(node: AST.JSONProperty) {
const objectNode = node.parent
if (!objectNode || objectNode.type !== 'JSONObjectExpression') return false
const expressionNode = objectNode.parent
return (
!!expressionNode &&
- (expressionNode.type === 'JSONExpressionStatement' ||
- expressionNode.type === 'Program' ||
- expressionNode.type === 'JSONProgram')
+ ['JSONExpressionStatement', 'Program', 'JSONProgram'].includes(expressionNode.type)
)
}
@@ -118,23 +128,23 @@ export default {
try {
const englishFilePath = path.join(path.dirname(filename), '..', 'en-US', jsonFile ?? '')
const englishText = fs.readFileSync(englishFilePath, 'utf8')
- state.englishJson = JSON.parse(cleanJsonText(englishText))
+ state.englishJson = JSON.parse(cleanJsonText(englishText)) as Record<string, unknown>
state.englishKeys = new Set(Object.keys(state.englishJson))
} catch (error) {
state.enabled = false
context.report({
- node,
+ node: node as unknown as Rule.Node,
message: `Error parsing JSON: ${error instanceof Error ? error.message : String(error)}`,
})
}
},
- JSONProperty(node) {
+ JSONProperty(node: AST.JSONProperty) {
if (!state.enabled) return
if (!state.englishJson || !isTopLevelProperty(node)) return
- const key = node.key.value ?? node.key.name
- if (!key) return
+ const key = node.key.type === 'JSONIdentifier' ? node.key.name : node.key.value
+ if (typeof key !== 'string' || !key) return
const sourceKey = getTranslationSourceKey(state.englishKeys, key, state.language)
if (!sourceKey) return
@@ -152,14 +162,14 @@ export default {
if (!arraysEqual(currentPlaceholders, englishPlaceholders)) {
context.report({
- node: currentNode,
+ node: currentNode as unknown as Rule.Node,
message: buildPlaceholderMessage(key, englishPlaceholders, currentPlaceholders),
})
}
if (!arraysEqual(currentTagMarkers, englishTagMarkers)) {
context.report({
- node: currentNode,
+ node: currentNode as unknown as Rule.Node,
message: buildTagMessage(key, englishTagMarkers, currentTagMarkers),
})
}
@@ -167,3 +177,6 @@ export default {
}
},
}
+
+// JSON listeners receive jsonc-eslint-parser nodes rather than ESTree nodes.
+export default rule as unknown as Rule.RuleModule
diff --git a/packages/tooling/plugins/eslint/rules/i18n-flat-key.js b/packages/tooling/plugins/eslint/rules/i18n-flat-key.ts
similarity index 79%
rename from packages/tooling/plugins/eslint/rules/i18n-flat-key.js
rename to packages/tooling/plugins/eslint/rules/i18n-flat-key.ts
index a59c2624c4e..5cfe055d812 100644
--- a/packages/tooling/plugins/eslint/rules/i18n-flat-key.js
+++ b/packages/tooling/plugins/eslint/rules/i18n-flat-key.ts
@@ -1,16 +1,18 @@
-function getPropertyKey(property) {
+import type { Rule, SourceCode } from 'eslint'
+import type { AST } from 'jsonc-eslint-parser'
+import type { JsonRuleModule } from '../utils.ts'
+function getPropertyKey(property: AST.JSONProperty) {
if (property.key.type === 'JSONIdentifier') return property.key.name
if (property.key.type === 'JSONLiteral' && typeof property.key.value === 'string')
return property.key.value
return null
}
-function getReportNode(sourceCode, targetNode) {
+function getReportNode(sourceCode: SourceCode, targetNode: AST.JSONNode) {
return sourceCode.getNodeByRangeIndex(targetNode.range[0]) ?? sourceCode.ast
}
-/** @type {import('eslint').Rule.RuleModule} */
-export default {
+const rule: JsonRuleModule = {
meta: {
type: 'problem',
docs: {
@@ -26,7 +28,7 @@ export default {
},
create(context) {
return {
- JSONObjectExpression(node) {
+ JSONObjectExpression(node: AST.JSONObjectExpression) {
if (node.parent.type !== 'JSONExpressionStatement') {
const targetNode = node.parent.type === 'JSONProperty' ? node.parent.key : node
context.report({
@@ -36,7 +38,7 @@ export default {
return
}
- const keyEntries = new Map()
+ const keyEntries = new Map<string, { key: string; keyNode: AST.JSONProperty['key'] }>()
for (const property of node.properties) {
const key = getPropertyKey(property)
if (key === null || keyEntries.has(key)) continue
@@ -47,7 +49,7 @@ export default {
}
const keys = [...keyEntries.keys()]
- const keyPrefixes = new Set()
+ const keyPrefixes = new Set<string>()
for (const key of keys) {
if (!key.includes('.')) continue
const parts = key.split('.')
@@ -81,3 +83,6 @@ export default {
}
},
}
+
+// JSON listeners receive jsonc-eslint-parser nodes rather than ESTree nodes.
+export default rule as unknown as Rule.RuleModule
diff --git a/packages/tooling/plugins/eslint/rules/no-extra-keys.test.js b/packages/tooling/plugins/eslint/rules/no-extra-keys.test.ts
similarity index 81%
rename from packages/tooling/plugins/eslint/rules/no-extra-keys.test.js
rename to packages/tooling/plugins/eslint/rules/no-extra-keys.test.ts
index 0685d00a01e..44ad1dcdc48 100644
--- a/packages/tooling/plugins/eslint/rules/no-extra-keys.test.js
+++ b/packages/tooling/plugins/eslint/rules/no-extra-keys.test.ts
@@ -6,10 +6,12 @@ import path from 'node:path'
import { Linter } from 'eslint'
import jsonc from 'eslint-plugin-jsonc'
import { expect, it } from 'vite-plus/test'
-import consistentPlaceholders from './consistent-placeholders.js'
-import noExtraKeys from './no-extra-keys.js'
+import consistentPlaceholders from './consistent-placeholders.ts'
+import noExtraKeys from './no-extra-keys.ts'
-function lintTranslation(translation, fix = false) {
+function lintTranslation(translation: Record<string, string>, fix: true): Linter.FixReport
+function lintTranslation(translation: Record<string, string>, fix?: false): Linter.LintMessage[]
+function lintTranslation(translation: Record<string, string>, fix = false) {
const directory = mkdtempSync(path.join(tmpdir(), 'dify-i18n-lint-'))
try {
mkdirSync(path.join(directory, 'en-US'))
@@ -22,7 +24,7 @@ function lintTranslation(translation, fix = false) {
}),
)
const linter = new Linter({ cwd: directory })
- const config = [
+ const config: Linter.Config[] = [
...jsonc.configs['flat/base'],
{
files: ['**/*.json'],
@@ -68,6 +70,6 @@ it('checks interpolation and tags in locale-specific variants', () => {
'dify/consistent-placeholders',
'dify/consistent-placeholders',
])
- expect(messages[0].message).toContain('missing {{count}}')
- expect(messages[1].message).toContain('Trans tag mismatch')
+ expect(messages[0]!.message).toContain('missing {{count}}')
+ expect(messages[1]!.message).toContain('Trans tag mismatch')
})
diff --git a/packages/tooling/plugins/eslint/rules/no-extra-keys.js b/packages/tooling/plugins/eslint/rules/no-extra-keys.ts
similarity index 96%
rename from packages/tooling/plugins/eslint/rules/no-extra-keys.js
rename to packages/tooling/plugins/eslint/rules/no-extra-keys.ts
index 439bbda6394..f571cf835fe 100644
--- a/packages/tooling/plugins/eslint/rules/no-extra-keys.js
+++ b/packages/tooling/plugins/eslint/rules/no-extra-keys.ts
@@ -1,9 +1,9 @@
+import type { Rule } from 'eslint'
import fs from 'node:fs'
import path, { normalize, sep } from 'node:path'
import { getTranslationSourceKey } from '../../../i18n-plurals.ts'
-/** @type {import('eslint').Rule.RuleModule} */
-export default {
+const rule: Rule.RuleModule = {
meta: {
type: 'problem',
docs: {
@@ -67,3 +67,5 @@ export default {
}
},
}
+
+export default rule
diff --git a/packages/tooling/plugins/eslint/rules/no-file-wide-disable.js b/packages/tooling/plugins/eslint/rules/no-file-wide-disable.ts
similarity index 81%
rename from packages/tooling/plugins/eslint/rules/no-file-wide-disable.js
rename to packages/tooling/plugins/eslint/rules/no-file-wide-disable.ts
index 28dd670d809..1bcbb80d8a1 100644
--- a/packages/tooling/plugins/eslint/rules/no-file-wide-disable.js
+++ b/packages/tooling/plugins/eslint/rules/no-file-wide-disable.ts
@@ -1,4 +1,6 @@
-export default {
+import type { Rule } from 'eslint'
+import { getDisableDirectives } from '../utils.ts'
+const rule: Rule.RuleModule = {
meta: {
type: 'problem',
docs: { description: 'Require block disables to end with a matching enable.' },
@@ -11,8 +13,11 @@ export default {
create(context) {
return {
Program() {
- const pending = new Map()
- for (const directive of context.sourceCode.getDisableDirectives().directives) {
+ const pending = new Map<
+ ReturnType<typeof getDisableDirectives>[number],
+ Set<string> | null
+ >()
+ for (const directive of getDisableDirectives(context.sourceCode)) {
const rules = directive.value
.split(',')
.map((rule) => rule.trim())
@@ -43,3 +48,5 @@ export default {
}
},
}
+
+export default rule
diff --git a/packages/tooling/plugins/eslint/rules/prefer-tailwind-icons.js b/packages/tooling/plugins/eslint/rules/prefer-tailwind-icons.ts
similarity index 83%
rename from packages/tooling/plugins/eslint/rules/prefer-tailwind-icons.js
rename to packages/tooling/plugins/eslint/rules/prefer-tailwind-icons.ts
index 136294a76f5..784a842fb61 100644
--- a/packages/tooling/plugins/eslint/rules/prefer-tailwind-icons.js
+++ b/packages/tooling/plugins/eslint/rules/prefer-tailwind-icons.ts
@@ -1,3 +1,21 @@
+import type { TSESLint, TSESTree } from '@typescript-eslint/utils'
+import type { Rule } from 'eslint'
+type LibraryConfig = { source: string; name?: string; prefix?: string }
+type ResolvedLibraryConfig = { sourceRegex: RegExp; nameRegex: RegExp; prefix?: string }
+type Options = {
+ libraries?: LibraryConfig[]
+ prefix?: string
+ propMappings?: Record<string, string>
+}
+type IconImport = {
+ node: TSESTree.ImportSpecifier
+ importedName: string
+ localName: string
+ config: ResolvedLibraryConfig
+ source: string
+ used: boolean
+}
+
const CAMEL_TO_KEBAB_UPPERCASE_REGEX = /([A-Z]+)([A-Z][a-z])/gu
const CAMEL_TO_KEBAB_LETTER_DIGIT_REGEX = /([a-z])(\d)/giu
const CAMEL_TO_KEBAB_DIGIT_LETTER_REGEX = /(\d)([a-z])/giu
@@ -9,13 +27,13 @@ const REGEX_FLAGS_PATTERN = /^[a-z]*$/iu
const NORMALIZE_SEGMENT_SPACES_REGEX = /\s+/gu
const warned = new Set()
-function warnOnce(message) {
+function warnOnce(message: string) {
if (warned.has(message)) return
warned.add(message)
console.warn(message)
}
-function camelToKebab(value) {
+function camelToKebab(value: string) {
return value
.replace(CAMEL_TO_KEBAB_UPPERCASE_REGEX, '$1-$2')
.replace(CAMEL_TO_KEBAB_LETTER_DIGIT_REGEX, '$1-$2')
@@ -27,12 +45,12 @@ function camelToKebab(value) {
.toLowerCase()
}
-function pixelToClass(pixels, classPrefix) {
+function pixelToClass(pixels: number, classPrefix: string) {
if (pixels % 4 === 0) return `${classPrefix}-${pixels / 4}`
return `${classPrefix}-[${pixels}px]`
}
-function parseRegexPattern(pattern) {
+function parseRegexPattern(pattern: string) {
if (!pattern.startsWith('/')) return null
let closingSlashIndex = -1
for (let i = pattern.length - 1; i > 0; i--) {
@@ -55,7 +73,7 @@ function parseRegexPattern(pattern) {
}
}
-function createRegex(pattern, optionName) {
+function createRegex(pattern: string, optionName: string) {
if (pattern.startsWith('/') && pattern.lastIndexOf('/') > 0) {
const literalRegex = parseRegexPattern(pattern)
if (literalRegex) return literalRegex
@@ -70,12 +88,12 @@ function createRegex(pattern, optionName) {
}
}
-function hasRegexMatch(value, regex) {
+function hasRegexMatch(value: string, regex: RegExp) {
regex.lastIndex = 0
return regex.test(value)
}
-function normalizeSegment(value) {
+function normalizeSegment(value: string) {
return value
.replaceAll('/', '-')
.replaceAll('_', '-')
@@ -85,13 +103,18 @@ function normalizeSegment(value) {
.toLowerCase()
}
-function getIconClass(importName, source, config, globalPrefix) {
+function getIconClass(
+ importName: string,
+ source: string,
+ config: ResolvedLibraryConfig,
+ globalPrefix: string,
+) {
const prefix = config.prefix ?? globalPrefix
config.sourceRegex.lastIndex = 0
config.nameRegex.lastIndex = 0
const sourceMatch = source.match(config.sourceRegex)
const nameMatch = importName.match(config.nameRegex)
- const getGroup = (...keys) => {
+ const getGroup = (...keys: string[]) => {
for (const key of keys) {
const fromName = nameMatch?.groups?.[key]
if (fromName) return fromName
@@ -110,7 +133,7 @@ function getIconClass(importName, source, config, globalPrefix) {
.replace(REPEATED_DASH_REGEX, '-')
}
-function normalizeLibraryConfig(config) {
+function normalizeLibraryConfig(config: LibraryConfig) {
const sourceRegex = createRegex(config.source, 'libraries[].source')
if (!sourceRegex) return null
const nameRegex = createRegex(config.name ?? '.*', 'libraries[].name')
@@ -122,7 +145,7 @@ function normalizeLibraryConfig(config) {
}
}
-function normalizeLibraryConfigs(configs) {
+function normalizeLibraryConfigs(configs: LibraryConfig[]) {
const resolved = []
for (const config of configs) {
const normalized = normalizeLibraryConfig(config)
@@ -131,7 +154,9 @@ function normalizeLibraryConfigs(configs) {
return resolved
}
-function isNamedImportSpecifier(specifier) {
+function isNamedImportSpecifier(
+ specifier: TSESTree.ImportClause,
+): specifier is TSESTree.ImportSpecifier & { imported: TSESTree.Identifier } {
return (
specifier.type === 'ImportSpecifier' &&
specifier.imported.type === 'Identifier' &&
@@ -139,7 +164,10 @@ function isNamedImportSpecifier(specifier) {
)
}
-function isJsxAttributeNamed(attribute, name) {
+function isJsxAttributeNamed(
+ attribute: TSESTree.JSXAttribute | TSESTree.JSXSpreadAttribute,
+ name: string,
+): attribute is TSESTree.JSXAttribute {
return (
attribute.type === 'JSXAttribute' &&
attribute.name.type === 'JSXIdentifier' &&
@@ -147,7 +175,7 @@ function isJsxAttributeNamed(attribute, name) {
)
}
-function getNumericJsxAttributeValue(attribute) {
+function getNumericJsxAttributeValue(attribute: TSESTree.JSXAttribute) {
if (!attribute.value) return null
if (attribute.value.type === 'Literal' && typeof attribute.value.value === 'number')
return attribute.value.value
@@ -161,7 +189,11 @@ function getNumericJsxAttributeValue(attribute) {
return null
}
-function getClassNameValueText(classNames, classNameAttribute, sourceCode) {
+function getClassNameValueText(
+ classNames: string,
+ classNameAttribute: TSESTree.JSXAttribute | undefined,
+ sourceCode: TSESLint.SourceCode,
+) {
if (!classNameAttribute?.value) return `{${JSON.stringify(classNames)}}`
if (
classNameAttribute.value.type === 'Literal' &&
@@ -192,7 +224,7 @@ function getClassNameValueText(classNames, classNameAttribute, sourceCode) {
return null
}
-function hasRuntimeReference(sourceCode, specifier) {
+function hasRuntimeReference(sourceCode: TSESLint.SourceCode, specifier: TSESTree.ImportClause) {
try {
const variable = sourceCode.getDeclaredVariables(specifier)[0]
if (!variable) return false
@@ -207,8 +239,7 @@ function hasRuntimeReference(sourceCode, specifier) {
}
}
-/** @type {import('eslint').Rule.RuleModule} */
-export default {
+const rule: TSESLint.RuleModule<string, [Options?]> = {
meta: {
type: 'suggestion',
hasSuggestions: true,
@@ -252,6 +283,7 @@ export default {
'Icon "{{importedName}}" from "{{source}}" can be replaced with Tailwind CSS class "{{iconClass}}"',
},
},
+ defaultOptions: [],
create(context) {
const [options = {}] = context.options
const resolvedConfigs = normalizeLibraryConfigs(options.libraries ?? [])
@@ -259,7 +291,7 @@ export default {
const globalPrefix = options.prefix ?? ''
const propMappings = options.propMappings ?? {}
- const iconImports = new Map()
+ const iconImports = new Map<string, IconImport>()
const sourceCode = context.sourceCode
return {
@@ -302,7 +334,7 @@ export default {
isJsxAttributeNamed(attribute, 'className'),
)
const mappedClasses = []
- const consumedMappedAttributes = new Set()
+ const consumedMappedAttributes = new Set<TSESTree.JSXAttribute>()
for (const [propName, classPrefix] of Object.entries(propMappings)) {
const mappedAttribute = node.attributes.find((attribute) =>
isJsxAttributeNamed(attribute, propName),
@@ -316,7 +348,8 @@ export default {
const classesToAdd = [iconClass, ...mappedClasses].filter(Boolean).join(' ')
const classValue = getClassNameValueText(classesToAdd, classNameAttribute, sourceCode)
- if (node.parent.type !== 'JSXElement') return
+ const element = node.parent
+ if (element.type !== 'JSXElement') return
context.report({
node,
@@ -349,10 +382,10 @@ export default {
? `className=${classValue} ${otherAttributes}`
: `className=${classValue}`
if (node.selfClosing)
- return fixer.replaceText(node.parent, `<span ${attrsText} />`)
+ return fixer.replaceText(element, `<span ${attrsText} />`)
const fixes = [fixer.replaceText(node, `<span ${attrsText}>`)]
- if (node.parent.closingElement)
- fixes.push(fixer.replaceText(node.parent.closingElement, '</span>'))
+ if (element.closingElement)
+ fixes.push(fixer.replaceText(element.closingElement, '</span>'))
return fixes
},
},
@@ -384,3 +417,6 @@ export default {
}
},
}
+
+// ESLint and Oxlint supply the parser-specific AST used by these typed listeners.
+export default rule as unknown as Rule.RuleModule
diff --git a/packages/tooling/plugins/eslint/rules/require-disable-directive-description.test.js b/packages/tooling/plugins/eslint/rules/require-disable-directive-description.test.ts
similarity index 94%
rename from packages/tooling/plugins/eslint/rules/require-disable-directive-description.test.js
rename to packages/tooling/plugins/eslint/rules/require-disable-directive-description.test.ts
index 144d80af3c6..af6906b3b5c 100644
--- a/packages/tooling/plugins/eslint/rules/require-disable-directive-description.test.js
+++ b/packages/tooling/plugins/eslint/rules/require-disable-directive-description.test.ts
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { expect, it } from 'vite-plus/test'
-function lintFixture(source, rules) {
+function lintFixture(source: string, rules: Record<string, string>) {
const require = createRequire(import.meta.url)
const viteRequire = createRequire(require.resolve('vite-plus/package.json'))
const oxlintBin = join(dirname(dirname(viteRequire.resolve('oxlint'))), 'bin', 'oxlint')
@@ -13,7 +13,7 @@ function lintFixture(source, rules) {
try {
writeFileSync(
join(directory, 'plugin.mjs'),
- `export { default } from ${JSON.stringify(require.resolve('../index.js'))};`,
+ `export { default } from ${JSON.stringify(require.resolve('../index.ts'))};`,
)
writeFileSync(
join(directory, '.oxlintrc.json'),
@@ -35,7 +35,11 @@ function lintFixture(source, rules) {
)
expect(result.error).toBeUndefined()
expect([0, 1], result.stderr + result.stdout).toContain(result.status)
- return JSON.parse(result.stdout).diagnostics
+ return JSON.parse(result.stdout).diagnostics as Array<{
+ code: string
+ severity: string
+ labels: { span: { line: number } }[]
+ }>
} finally {
rmSync(directory, { recursive: true, force: true })
}
@@ -64,7 +68,7 @@ it('checks actual Oxlint directives, including JSX and both prefixes, without re
].join('\n'),
{ 'dify/require-disable-directive-description': 'error' },
)
- expect(diagnostics.map(({ code, labels }) => ({ code, line: labels[0].span.line }))).toEqual([
+ expect(diagnostics.map(({ code, labels }) => ({ code, line: labels[0]!.span.line }))).toEqual([
{ code: 'dify(require-disable-directive-description)', line: 1 },
{ code: 'dify(require-disable-directive-description)', line: 3 },
{ code: 'dify(require-disable-directive-description)', line: 4 },
diff --git a/packages/tooling/plugins/eslint/rules/require-disable-directive-description.js b/packages/tooling/plugins/eslint/rules/require-disable-directive-description.ts
similarity index 71%
rename from packages/tooling/plugins/eslint/rules/require-disable-directive-description.js
rename to packages/tooling/plugins/eslint/rules/require-disable-directive-description.ts
index 39130cd1910..bb33bd069ba 100644
--- a/packages/tooling/plugins/eslint/rules/require-disable-directive-description.js
+++ b/packages/tooling/plugins/eslint/rules/require-disable-directive-description.ts
@@ -1,4 +1,6 @@
-export default {
+import type { Rule } from 'eslint'
+import { getDisableDirectives } from '../utils.ts'
+const rule: Rule.RuleModule = {
meta: {
type: 'suggestion',
docs: {
@@ -12,7 +14,7 @@ export default {
create(context) {
return {
Program() {
- for (const directive of context.sourceCode.getDisableDirectives().directives) {
+ for (const directive of getDisableDirectives(context.sourceCode)) {
if (directive.type !== 'enable' && !directive.justification.trim()) {
context.report({
node: directive.node,
@@ -24,3 +26,5 @@ export default {
}
},
}
+
+export default rule
diff --git a/packages/tooling/plugins/eslint/rules/require-i18n-namespace.test.js b/packages/tooling/plugins/eslint/rules/require-i18n-namespace.test.ts
similarity index 92%
rename from packages/tooling/plugins/eslint/rules/require-i18n-namespace.test.js
rename to packages/tooling/plugins/eslint/rules/require-i18n-namespace.test.ts
index 8ce8f425f32..f5afb95a4c5 100644
--- a/packages/tooling/plugins/eslint/rules/require-i18n-namespace.test.js
+++ b/packages/tooling/plugins/eslint/rules/require-i18n-namespace.test.ts
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { expect, it } from 'vite-plus/test'
-function lintFixture(source, rules) {
+function lintFixture(source: string, rules: Record<string, string>) {
const require = createRequire(import.meta.url)
const viteRequire = createRequire(require.resolve('vite-plus/package.json'))
const oxlintBin = join(dirname(dirname(viteRequire.resolve('oxlint'))), 'bin', 'oxlint')
@@ -13,7 +13,7 @@ function lintFixture(source, rules) {
try {
writeFileSync(
join(directory, 'plugin.mjs'),
- `export { default } from ${JSON.stringify(require.resolve('../index.js'))};`,
+ `export { default } from ${JSON.stringify(require.resolve('../index.ts'))};`,
)
writeFileSync(
join(directory, '.oxlintrc.json'),
@@ -35,7 +35,11 @@ function lintFixture(source, rules) {
)
expect(result.error).toBeUndefined()
expect([0, 1], result.stderr + result.stdout).toContain(result.status)
- return JSON.parse(result.stdout).diagnostics
+ return JSON.parse(result.stdout).diagnostics as Array<{
+ code: string
+ severity: string
+ labels: { span: { line: number } }[]
+ }>
} finally {
rmSync(directory, { recursive: true, force: true })
}
@@ -62,7 +66,7 @@ it('rejects missing, empty, string, and dynamic namespaces through named and nam
'translate(getNamespaces())',
].join('\n')
const diagnostics = lintFixture(source, { 'dify/require-i18n-namespace': 'error' })
- expect(diagnostics.map(({ code, labels }) => ({ code, line: labels[0].span.line }))).toEqual(
+ expect(diagnostics.map(({ code, labels }) => ({ code, line: labels[0]!.span.line }))).toEqual(
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17].map((line) => ({
code: 'dify(require-i18n-namespace)',
line,
@@ -105,5 +109,5 @@ it('allows reading only i18n but still requires namespaces when t or the rest is
'const { t: i18nAlias } = useTranslation()',
].join('\n')
const diagnostics = lintFixture(source, { 'dify/require-i18n-namespace': 'error' })
- expect(diagnostics.map(({ labels }) => labels[0].span.line)).toEqual([9, 10, 11, 12, 13])
+ expect(diagnostics.map(({ labels }) => labels[0]!.span.line)).toEqual([9, 10, 11, 12, 13])
})
diff --git a/packages/tooling/plugins/eslint/rules/require-i18n-namespace.js b/packages/tooling/plugins/eslint/rules/require-i18n-namespace.ts
similarity index 58%
rename from packages/tooling/plugins/eslint/rules/require-i18n-namespace.js
rename to packages/tooling/plugins/eslint/rules/require-i18n-namespace.ts
index 19565947f33..b9dd539b830 100644
--- a/packages/tooling/plugins/eslint/rules/require-i18n-namespace.js
+++ b/packages/tooling/plugins/eslint/rules/require-i18n-namespace.ts
@@ -1,6 +1,8 @@
+import type { TSESLint, TSESTree } from '@typescript-eslint/utils'
+import type { Rule } from 'eslint'
const translationModules = new Set(['react-i18next', '#i18n'])
-function unwrap(node) {
+function unwrap(node: TSESTree.Node | undefined) {
while (
node &&
[
@@ -10,14 +12,16 @@ function unwrap(node) {
'TSTypeAssertion',
'ParenthesizedExpression',
'ChainExpression',
- ].includes(node.type)
+ ].includes(node.type) &&
+ 'expression' in node &&
+ typeof node.expression !== 'boolean'
)
node = node.expression
return node
}
-function getVariable(sourceCode, node) {
- let scope = sourceCode.getScope(node)
+function getVariable(sourceCode: TSESLint.SourceCode, node: TSESTree.Identifier) {
+ let scope: TSESLint.Scope.Scope | null = sourceCode.getScope(node)
while (scope) {
const variable = scope.set.get(node.name)
if (variable) return variable
@@ -25,40 +29,51 @@ function getVariable(sourceCode, node) {
}
}
-function isTranslationHook(sourceCode, callee) {
- callee = unwrap(callee)
+function isTranslationHook(sourceCode: TSESLint.SourceCode, callee: TSESTree.Node) {
+ callee = unwrap(callee)!
let identifier = callee
let namespaceImport = false
if (callee.type === 'MemberExpression') {
- const property = callee.computed ? callee.property.value : callee.property.name
+ const property =
+ callee.property.type === 'Literal'
+ ? callee.property.value
+ : callee.property.type === 'Identifier' && !callee.computed
+ ? callee.property.name
+ : undefined
if (property !== 'useTranslation') return false
- identifier = unwrap(callee.object)
+ identifier = unwrap(callee.object)!
namespaceImport = true
}
if (identifier.type !== 'Identifier') return false
const definition = getVariable(sourceCode, identifier)?.defs[0]
if (
definition?.type !== 'ImportBinding' ||
+ definition.parent.type !== 'ImportDeclaration' ||
!translationModules.has(definition.parent.source.value)
)
return false
if (namespaceImport) return definition.node.type === 'ImportNamespaceSpecifier'
return (
definition.node.type === 'ImportSpecifier' &&
- (definition.node.imported.name ?? definition.node.imported.value) === 'useTranslation'
+ (definition.node.imported.type === 'Identifier'
+ ? definition.node.imported.name
+ : definition.node.imported.value) === 'useTranslation'
)
}
-function isNamespaceArray(node) {
+function isNamespaceArray(node: TSESTree.Node | undefined) {
node = unwrap(node)
return node?.type === 'ArrayExpression' && node.elements.length > 0
}
-function onlyReadsI18n(node) {
+function onlyReadsI18n(node: TSESTree.Node) {
while (node.parent && unwrap(node.parent) === unwrap(node)) node = node.parent
const parent = node.parent
- const isI18nProperty = (property, computed) =>
- property.type === 'Literal' ? property.value === 'i18n' : !computed && property.name === 'i18n'
+ if (!parent) return false
+ const isI18nProperty = (property: TSESTree.Node, computed: boolean) =>
+ property.type === 'Literal'
+ ? property.value === 'i18n'
+ : !computed && property.type === 'Identifier' && property.name === 'i18n'
if (parent.type === 'MemberExpression' && parent.object === node)
return isI18nProperty(parent.property, parent.computed)
const pattern =
@@ -68,12 +83,11 @@ function onlyReadsI18n(node) {
? parent.left
: undefined
if (pattern?.type !== 'ObjectPattern' || pattern.properties.length !== 1) return false
- const property = pattern.properties[0]
+ const property = pattern.properties[0]!
return property.type === 'Property' && isI18nProperty(property.key, property.computed)
}
-/** @type {import('eslint').Rule.RuleModule} */
-export default {
+const rule: TSESLint.RuleModule<string, []> = {
meta: {
type: 'problem',
docs: {
@@ -84,20 +98,22 @@ export default {
emptyNamespace: 'Declare the namespaces used by useTranslation as a non-empty inline array.',
},
},
+ defaultOptions: [],
create(context) {
const importedNames = new Set(
context.sourceCode.ast.body
.filter(
- (node) => node.type === 'ImportDeclaration' && translationModules.has(node.source.value),
+ (node): node is TSESTree.ImportDeclaration =>
+ node.type === 'ImportDeclaration' && translationModules.has(node.source.value),
)
.flatMap((node) => node.specifiers.map((specifier) => specifier.local.name)),
)
if (!importedNames.size) return {}
return {
CallExpression(node) {
- const callee = unwrap(node.callee)
+ const callee = unwrap(node.callee)!
const identifier = callee.type === 'MemberExpression' ? unwrap(callee.object) : callee
- if (!importedNames.has(identifier.name)) return
+ if (identifier?.type !== 'Identifier' || !importedNames.has(identifier.name)) return
if (
isTranslationHook(context.sourceCode, node.callee) &&
!isNamespaceArray(node.arguments[0]) &&
@@ -108,3 +124,6 @@ export default {
}
},
}
+
+// ESLint and Oxlint supply the parser-specific AST used by these typed listeners.
+export default rule as unknown as Rule.RuleModule
diff --git a/packages/tooling/plugins/eslint/rules/require-t-function-namespace.test.js b/packages/tooling/plugins/eslint/rules/require-t-function-namespace.test.ts
similarity index 92%
rename from packages/tooling/plugins/eslint/rules/require-t-function-namespace.test.js
rename to packages/tooling/plugins/eslint/rules/require-t-function-namespace.test.ts
index 55b7ad6e319..dbe8f3a8854 100644
--- a/packages/tooling/plugins/eslint/rules/require-t-function-namespace.test.js
+++ b/packages/tooling/plugins/eslint/rules/require-t-function-namespace.test.ts
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { expect, it } from 'vite-plus/test'
-function lintFixture(source, rules) {
+function lintFixture(source: string, rules: Record<string, string>) {
const require = createRequire(import.meta.url)
const viteRequire = createRequire(require.resolve('vite-plus/package.json'))
const oxlintBin = join(dirname(dirname(viteRequire.resolve('oxlint'))), 'bin', 'oxlint')
@@ -13,7 +13,7 @@ function lintFixture(source, rules) {
try {
writeFileSync(
join(directory, 'plugin.mjs'),
- `export { default } from ${JSON.stringify(require.resolve('../index.js'))};`,
+ `export { default } from ${JSON.stringify(require.resolve('../index.ts'))};`,
)
writeFileSync(
join(directory, '.oxlintrc.json'),
@@ -35,7 +35,11 @@ function lintFixture(source, rules) {
)
expect(result.error).toBeUndefined()
expect([0, 1], result.stderr + result.stdout).toContain(result.status)
- return JSON.parse(result.stdout).diagnostics
+ return JSON.parse(result.stdout).diagnostics as Array<{
+ code: string
+ severity: string
+ labels: { span: { line: number } }[]
+ }>
} finally {
rmSync(directory, { recursive: true, force: true })
}
@@ -60,7 +64,7 @@ it('rejects missing, broad, and non-tuple namespaces through imported TFunction
"type Union = TFunction<['common' | 'workflow']>",
].join('\n')
const diagnostics = lintFixture(source, { 'dify/require-t-function-namespace': 'error' })
- expect(diagnostics.map(({ code, labels }) => ({ code, line: labels[0].span.line }))).toEqual(
+ expect(diagnostics.map(({ code, labels }) => ({ code, line: labels[0]!.span.line }))).toEqual(
Array.from({ length: 13 }, (_, index) => ({
code: 'dify(require-t-function-namespace)',
line: index + 3,
diff --git a/packages/tooling/plugins/eslint/rules/require-t-function-namespace.js b/packages/tooling/plugins/eslint/rules/require-t-function-namespace.ts
similarity index 59%
rename from packages/tooling/plugins/eslint/rules/require-t-function-namespace.js
rename to packages/tooling/plugins/eslint/rules/require-t-function-namespace.ts
index b6f675c42cd..fa546186519 100644
--- a/packages/tooling/plugins/eslint/rules/require-t-function-namespace.js
+++ b/packages/tooling/plugins/eslint/rules/require-t-function-namespace.ts
@@ -1,5 +1,7 @@
-function getVariable(sourceCode, node) {
- let scope = sourceCode.getScope(node)
+import type { TSESLint, TSESTree } from '@typescript-eslint/utils'
+import type { Rule } from 'eslint'
+function getVariable(sourceCode: TSESLint.SourceCode, node: TSESTree.Identifier) {
+ let scope: TSESLint.Scope.Scope | null = sourceCode.getScope(node)
while (scope) {
const variable = scope.set.get(node.name)
if (variable) return variable
@@ -7,22 +9,28 @@ function getVariable(sourceCode, node) {
}
}
-function isTFunction(sourceCode, name) {
+function isTFunction(sourceCode: TSESLint.SourceCode, name: TSESTree.EntityName) {
const qualified = name.type === 'TSQualifiedName'
if (qualified && name.right.name !== 'TFunction') return false
const identifier = qualified ? name.left : name
if (identifier.type !== 'Identifier') return false
const definition = getVariable(sourceCode, identifier)?.defs[0]
- if (definition?.type !== 'ImportBinding' || definition.parent.source.value !== 'i18next')
+ if (
+ definition?.type !== 'ImportBinding' ||
+ definition.parent.type !== 'ImportDeclaration' ||
+ definition.parent.source.value !== 'i18next'
+ )
return false
if (qualified) return definition.node.type === 'ImportNamespaceSpecifier'
return (
definition.node.type === 'ImportSpecifier' &&
- (definition.node.imported.name ?? definition.node.imported.value) === 'TFunction'
+ (definition.node.imported.type === 'Identifier'
+ ? definition.node.imported.name
+ : definition.node.imported.value) === 'TFunction'
)
}
-function isNamespaceTuple(node) {
+function isNamespaceTuple(node: TSESTree.TypeNode | undefined) {
if (node?.type === 'TSTypeOperator' && node.operator === 'readonly') node = node.typeAnnotation
return (
node?.type === 'TSTupleType' &&
@@ -30,14 +38,14 @@ function isNamespaceTuple(node) {
node.elementTypes.every(
(element) =>
element.type === 'TSLiteralType' &&
+ element.literal.type === 'Literal' &&
typeof element.literal.value === 'string' &&
element.literal.value.length > 0,
)
)
}
-/** @type {import('eslint').Rule.RuleModule} */
-export default {
+const rule: TSESLint.RuleModule<string, []> = {
meta: {
type: 'problem',
docs: { description: 'Require explicit namespace tuples for i18next TFunction types.' },
@@ -47,13 +55,17 @@ export default {
"Declare TFunction namespaces as a non-empty tuple of string literals, e.g. TFunction<['common', 'workflow']>.",
},
},
+ defaultOptions: [],
create(context) {
const importedNames = new Set(
context.sourceCode.ast.body
- .filter((node) => node.type === 'ImportDeclaration' && node.source.value === 'i18next')
+ .filter(
+ (node): node is TSESTree.ImportDeclaration =>
+ node.type === 'ImportDeclaration' && node.source.value === 'i18next',
+ )
.flatMap((node) => node.specifiers.map((specifier) => specifier.local.name)),
)
- const check = (node) => {
+ const check = (node: TSESTree.TSTypeReference | TSESTree.TSImportType) => {
if (!isNamespaceTuple(node.typeArguments?.params[0]))
context.report({ node, messageId: 'namespaceTuple' })
}
@@ -61,7 +73,11 @@ export default {
TSTypeReference(node) {
const identifier =
node.typeName.type === 'TSQualifiedName' ? node.typeName.left : node.typeName
- if (importedNames.has(identifier.name) && isTFunction(context.sourceCode, node.typeName))
+ if (
+ identifier.type === 'Identifier' &&
+ importedNames.has(identifier.name) &&
+ isTFunction(context.sourceCode, node.typeName)
+ )
check(node)
},
TSImportType(node) {
@@ -75,3 +91,6 @@ export default {
}
},
}
+
+// ESLint and Oxlint supply the parser-specific AST used by these typed listeners.
+export default rule as unknown as Rule.RuleModule
diff --git a/packages/tooling/plugins/eslint/rules/require-title-for-truncated-text.test.js b/packages/tooling/plugins/eslint/rules/require-title-for-truncated-text.test.ts
similarity index 96%
rename from packages/tooling/plugins/eslint/rules/require-title-for-truncated-text.test.js
rename to packages/tooling/plugins/eslint/rules/require-title-for-truncated-text.test.ts
index e62b2c5fb2e..dc233b4f963 100644
--- a/packages/tooling/plugins/eslint/rules/require-title-for-truncated-text.test.js
+++ b/packages/tooling/plugins/eslint/rules/require-title-for-truncated-text.test.ts
@@ -4,7 +4,7 @@ import tsParser from '@typescript-eslint/parser'
import { Linter } from 'eslint'
import { it } from 'vite-plus/test'
import { repositoryRoot } from '../../../paths.ts'
-import rule from './require-title-for-truncated-text.js'
+import rule from './require-title-for-truncated-text.ts'
import './fixtures/truncation.module.css'
const plugin = {
@@ -13,7 +13,7 @@ const plugin = {
},
}
-function verifyAndFix(code, filename = 'test.tsx') {
+function verifyAndFix(code: string, filename = 'test.tsx') {
const linter = new Linter({ cwd: repositoryRoot })
return linter.verifyAndFix(
code,
@@ -121,8 +121,8 @@ it('reports an empty title without replacing it', () => {
assert.equal(result.fixed, false)
assert.equal(result.messages.length, 1)
- assert.equal(result.messages[0].severity, 1)
- assert.equal(result.messages[0].messageId, 'emptyTitle')
+ assert.equal(result.messages[0]!.severity, 1)
+ assert.equal(result.messages[0]!.messageId, 'emptyTitle')
assert.equal(result.output, code)
})
@@ -136,7 +136,7 @@ it('reports custom components without fixing them', () => {
assert.equal(result.fixed, false)
assert.equal(result.messages.length, 1)
- assert.equal(result.messages[0].severity, 1)
+ assert.equal(result.messages[0]!.severity, 1)
assert.equal(result.output, code)
})
@@ -190,7 +190,7 @@ it('checks Dify UI single text but ignores multiple text children', () => {
assert.equal(result.fixed, false)
assert.equal(result.messages.length, 1)
- assert.equal(result.messages[0].severity, 1)
+ assert.equal(result.messages[0]!.severity, 1)
})
it('does not count non-text conditional children as additional text', () => {
@@ -205,7 +205,7 @@ it('does not count non-text conditional children as additional text', () => {
assert.equal(result.fixed, false)
assert.equal(result.messages.length, 1)
- assert.equal(result.messages[0].messageId, 'missingTitle')
+ assert.equal(result.messages[0]!.messageId, 'missingTitle')
})
it('resolves truncation classes imported from CSS modules', () => {
diff --git a/packages/tooling/plugins/eslint/rules/require-title-for-truncated-text.js b/packages/tooling/plugins/eslint/rules/require-title-for-truncated-text.ts
similarity index 82%
rename from packages/tooling/plugins/eslint/rules/require-title-for-truncated-text.js
rename to packages/tooling/plugins/eslint/rules/require-title-for-truncated-text.ts
index d0c77ba52d9..5c98f1b06a1 100644
--- a/packages/tooling/plugins/eslint/rules/require-title-for-truncated-text.js
+++ b/packages/tooling/plugins/eslint/rules/require-title-for-truncated-text.ts
@@ -1,8 +1,12 @@
+import type { TSESLint, TSESTree } from '@typescript-eslint/utils'
+import type { Rule } from 'eslint'
import { readFileSync, statSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
const DEFAULT_TRUNCATION_CLASSES = new Set(['text-ellipsis', 'truncate'])
-const cssModuleClassCache = new Map()
+type CssModuleBindings = Map<TSESLint.Scope.Variable, Set<string>>
+
+const cssModuleClassCache = new Map<string, { classNames: Set<string>; modifiedTime: number }>()
const UNSAFE_TITLE_EXPRESSION = Symbol('unsafe-title-expression')
const STYLE_WRAPPER_TYPES = new Set([
'ChainExpression',
@@ -13,7 +17,7 @@ const STYLE_WRAPPER_TYPES = new Set([
'TSTypeAssertion',
])
-function getJsxName(node) {
+function getJsxName(node: TSESTree.Node | undefined): string | null {
if (!node) return null
if (node.type === 'JSXIdentifier') return node.name
if (node.type === 'JSXMemberExpression') {
@@ -29,22 +33,28 @@ function getJsxName(node) {
return null
}
-function getAttribute(openingElement, attributeName) {
+function getAttribute(openingElement: TSESTree.JSXOpeningElement, attributeName: string) {
return openingElement.attributes.find(
- (attribute) =>
+ (attribute): attribute is TSESTree.JSXAttribute =>
attribute.type === 'JSXAttribute' &&
attribute.name.type === 'JSXIdentifier' &&
attribute.name.name === attributeName,
)
}
-function unwrapExpression(node) {
+function unwrapExpression(node: TSESTree.Node | undefined) {
let current = node
- while (current && STYLE_WRAPPER_TYPES.has(current.type)) current = current.expression
+ while (
+ current &&
+ STYLE_WRAPPER_TYPES.has(current.type) &&
+ 'expression' in current &&
+ typeof current.expression !== 'boolean'
+ )
+ current = current.expression
return current
}
-function getStaticString(node) {
+function getStaticString(node: TSESTree.Node | undefined) {
const current = unwrapExpression(node)
if (!current) return null
if (current.type === 'Literal' && typeof current.value === 'string') return current.value
@@ -53,7 +63,7 @@ function getStaticString(node) {
return null
}
-function getUnprefixedClassName(token) {
+function getUnprefixedClassName(token: string) {
let bracketDepth = 0
let lastVariantSeparator = -1
@@ -70,7 +80,7 @@ function getUnprefixedClassName(token) {
.replace(/!$/u, '')
}
-function isTruncationClassToken(token) {
+function isTruncationClassToken(token: string) {
const className = getUnprefixedClassName(token)
if (DEFAULT_TRUNCATION_CLASSES.has(className)) return true
if (className.startsWith('line-clamp-') && className !== 'line-clamp-none') return true
@@ -82,11 +92,11 @@ function isTruncationClassToken(token) {
)
}
-function stringContainsTruncationClass(value) {
+function stringContainsTruncationClass(value: string) {
return value.split(/\s+/u).some((token) => token && isTruncationClassToken(token))
}
-function hasActiveLineClampDeclaration(cssText) {
+function hasActiveLineClampDeclaration(cssText: string) {
const lineClampPattern = /(?:-webkit-)?line-clamp\s*:\s*([^;}]+)/giu
return [...cssText.matchAll(lineClampPattern)].some((match) => {
const value = (match[1] ?? '').trim()
@@ -94,12 +104,12 @@ function hasActiveLineClampDeclaration(cssText) {
})
}
-function getTruncatingCssModuleClassNames(cssText) {
- const classNames = new Set()
+function getTruncatingCssModuleClassNames(cssText: string) {
+ const classNames = new Set<string>()
const classBlockPattern = /\.([A-Z_a-z][\w-]*)\s*\{([^{}]*)\}/gu
for (const match of cssText.matchAll(classBlockPattern)) {
- const [, className, body = ''] = match
+ const [, className = '', body = ''] = match
const hasTextEllipsis = /text-overflow\s*:\s*ellipsis\b/iu.test(body)
const hasLineClamp = hasActiveLineClampDeclaration(body)
const hasTruncationApply = [...body.matchAll(/@apply\s+([^;}]+)/gu)].some((applyMatch) =>
@@ -112,7 +122,7 @@ function getTruncatingCssModuleClassNames(cssText) {
return classNames
}
-function getCssModuleClassNames(cssModulePath) {
+function getCssModuleClassNames(cssModulePath: string) {
try {
const modifiedTime = statSync(cssModulePath).mtimeMs
const cached = cssModuleClassCache.get(cssModulePath)
@@ -122,11 +132,11 @@ function getCssModuleClassNames(cssModulePath) {
cssModuleClassCache.set(cssModulePath, { classNames, modifiedTime })
return classNames
} catch {
- return new Set()
+ return new Set<string>()
}
}
-function getPropertyName(property) {
+function getPropertyName(property: TSESTree.Node | undefined) {
if (!property || property.type !== 'Property') return null
if (!property.computed && property.key.type === 'Identifier') return property.key.name
if (property.key.type === 'Literal' && typeof property.key.value === 'string')
@@ -134,7 +144,7 @@ function getPropertyName(property) {
return null
}
-function getVariableByName(scope, name) {
+function getVariableByName(scope: TSESLint.Scope.Scope | null, name: string) {
let currentScope = scope
while (currentScope) {
const variable = currentScope.set.get(name)
@@ -144,12 +154,13 @@ function getVariableByName(scope, name) {
return null
}
-function getVariableInitializer(identifier, sourceCode) {
+function getVariableInitializer(identifier: TSESTree.Identifier, sourceCode: TSESLint.SourceCode) {
const variable = getVariableByName(sourceCode.getScope(identifier), identifier.name)
if (!variable || variable.defs.length !== 1) return null
const [definition] = variable.defs
if (
+ !definition ||
definition.type !== 'Variable' ||
definition.node.type !== 'VariableDeclarator' ||
definition.node.id.type !== 'Identifier' ||
@@ -161,11 +172,11 @@ function getVariableInitializer(identifier, sourceCode) {
}
function expressionContainsTruncationClass(
- node,
- sourceCode,
- cssModuleBindings,
- seenVariables = new Set(),
-) {
+ node: TSESTree.Node | undefined,
+ sourceCode: TSESLint.SourceCode,
+ cssModuleBindings: CssModuleBindings,
+ seenVariables = new Set<TSESLint.Scope.Variable>(),
+): boolean {
const current = unwrapExpression(node)
if (!current) return false
@@ -194,7 +205,11 @@ function expressionContainsTruncationClass(
? current.property.name
: null
const variable = getVariableByName(sourceCode.getScope(object), object.name)
- return propertyName !== null && cssModuleBindings.get(variable)?.has(propertyName)
+ return (
+ propertyName !== null &&
+ variable !== null &&
+ (cssModuleBindings.get(variable)?.has(propertyName) ?? false)
+ )
}
case 'TemplateLiteral':
return (
@@ -321,7 +336,7 @@ function expressionContainsTruncationClass(
}
}
-function isActiveLineClampValue(node) {
+function isActiveLineClampValue(node: TSESTree.Node | undefined) {
const current = unwrapExpression(node)
if (!current) return false
if (current.type === 'Literal') {
@@ -333,7 +348,11 @@ function isActiveLineClampValue(node) {
return current.type !== 'Identifier' || current.name !== 'undefined'
}
-function expressionContainsTruncationStyle(node, sourceCode, seenVariables = new Set()) {
+function expressionContainsTruncationStyle(
+ node: TSESTree.Node | undefined,
+ sourceCode: TSESLint.SourceCode,
+ seenVariables = new Set<TSESLint.Scope.Variable>(),
+): boolean {
const current = unwrapExpression(node)
if (!current) return false
@@ -386,7 +405,7 @@ function expressionContainsTruncationStyle(node, sourceCode, seenVariables = new
return getStaticString(property.value)?.trim().toLowerCase() === 'ellipsis'
if (
['WebkitLineClamp', 'webkitLineClamp', 'lineClamp', '-webkit-line-clamp'].includes(
- propertyName,
+ propertyName ?? '',
)
)
return isActiveLineClampValue(property.value)
@@ -394,7 +413,11 @@ function expressionContainsTruncationStyle(node, sourceCode, seenVariables = new
})
}
-function hasTruncation(openingElement, sourceCode, cssModuleBindings) {
+function hasTruncation(
+ openingElement: TSESTree.JSXOpeningElement,
+ sourceCode: TSESLint.SourceCode,
+ cssModuleBindings: CssModuleBindings,
+) {
const classAttribute =
getAttribute(openingElement, 'className') ?? getAttribute(openingElement, 'class')
if (classAttribute?.value) {
@@ -422,7 +445,7 @@ function hasTruncation(openingElement, sourceCode, cssModuleBindings) {
)
}
-function isEmptyTitleAttribute(attribute) {
+function isEmptyTitleAttribute(attribute: TSESTree.JSXAttribute | undefined) {
if (!attribute || !attribute.value) return true
if (attribute.value.type === 'Literal')
return typeof attribute.value.value !== 'string' || attribute.value.value.trim() === ''
@@ -437,7 +460,7 @@ function isEmptyTitleAttribute(attribute) {
return expression.type === 'Identifier' && expression.name === 'undefined'
}
-function isRenderableTitleExpression(node) {
+function isRenderableTitleExpression(node: TSESTree.Node | undefined) {
const current = unwrapExpression(node)
if (!current) return false
return ![
@@ -451,7 +474,7 @@ function isRenderableTitleExpression(node) {
].includes(current.type)
}
-function isSafeToDuplicateTitleExpression(node) {
+function isSafeToDuplicateTitleExpression(node: TSESTree.Node | undefined) {
const current = unwrapExpression(node)
if (!current) return false
@@ -465,7 +488,7 @@ function isSafeToDuplicateTitleExpression(node) {
return false
}
-function getMeaningfulChildren(element) {
+function getMeaningfulChildren(element: TSESTree.JSXElement | TSESTree.JSXFragment) {
return element.children.filter((child) => {
if (child.type === 'JSXText') return child.value.trim() !== ''
if (child.type === 'JSXExpressionContainer')
@@ -474,16 +497,18 @@ function getMeaningfulChildren(element) {
})
}
-function getSingleTextChild(element) {
+function getSingleTextChild(
+ element: TSESTree.JSXElement | TSESTree.JSXFragment,
+): TSESTree.JSXChild | null {
const meaningfulChildren = getMeaningfulChildren(element)
if (meaningfulChildren.length !== 1) return null
- const child = meaningfulChildren[0]
+ const child = meaningfulChildren[0]!
if (child.type === 'JSXElement') return getSingleTextChild(child)
return child
}
-function getExpressionTextChildCount(node) {
+function getExpressionTextChildCount(node: TSESTree.Node | undefined): number {
const current = unwrapExpression(node)
if (!current) return 0
@@ -522,7 +547,7 @@ function getExpressionTextChildCount(node) {
return isRenderableTitleExpression(current) ? 1 : 0
}
-function getTextChildCount(element) {
+function getTextChildCount(element: TSESTree.JSXElement | TSESTree.JSXFragment): number {
let count = 0
for (const child of getMeaningfulChildren(element)) {
@@ -538,12 +563,15 @@ function getTextChildCount(element) {
return count
}
-function hasMultipleTextChildren(openingElement) {
+function hasMultipleTextChildren(openingElement: TSESTree.JSXOpeningElement) {
const element = openingElement.parent
return element?.type === 'JSXElement' && getTextChildCount(element) > 1
}
-function getTitleFixTextFromAttribute(attribute, sourceCode) {
+function getTitleFixTextFromAttribute(
+ attribute: TSESTree.JSXAttribute | undefined,
+ sourceCode: TSESLint.SourceCode,
+) {
if (!attribute?.value) return null
if (attribute.value.type === 'Literal') {
if (typeof attribute.value.value !== 'string' || attribute.value.value.trim() === '')
@@ -555,7 +583,10 @@ function getTitleFixTextFromAttribute(attribute, sourceCode) {
return `title={${sourceCode.getText(attribute.value.expression)}}`
}
-function getTitleFixText(openingElement, sourceCode) {
+function getTitleFixText(
+ openingElement: TSESTree.JSXOpeningElement,
+ sourceCode: TSESLint.SourceCode,
+) {
const element = openingElement.parent
if (!element || element.type !== 'JSXElement') return null
@@ -586,22 +617,28 @@ function getTitleFixText(openingElement, sourceCode) {
return hasUnsafeTitleExpression ? UNSAFE_TITLE_EXPRESSION : null
}
-function hasTitledSingleChild(openingElement) {
+function hasTitledSingleChild(openingElement: TSESTree.JSXOpeningElement) {
const element = openingElement.parent
if (!element || element.type !== 'JSXElement') return false
const meaningfulChildren = getMeaningfulChildren(element)
- if (meaningfulChildren.length !== 1 || meaningfulChildren[0].type !== 'JSXElement') return null
- const titleAttribute = getAttribute(meaningfulChildren[0].openingElement, 'title')
+ if (meaningfulChildren.length !== 1 || meaningfulChildren[0]!.type !== 'JSXElement') return null
+ const titleAttribute = getAttribute(meaningfulChildren[0]!.openingElement, 'title')
return !!titleAttribute && !isEmptyTitleAttribute(titleAttribute)
}
-function isTooltipTriggerOpening(openingElement, tooltipTriggerNames) {
+function isTooltipTriggerOpening(
+ openingElement: TSESTree.JSXOpeningElement,
+ tooltipTriggerNames: Set<string>,
+) {
const name = getJsxName(openingElement.name)
return name !== null && tooltipTriggerNames.has(name)
}
-function isInsideTooltipTrigger(openingElement, tooltipTriggerNames) {
- let current = openingElement.parent
+function isInsideTooltipTrigger(
+ openingElement: TSESTree.JSXOpeningElement,
+ tooltipTriggerNames: Set<string>,
+) {
+ let current: TSESTree.Node | undefined = openingElement.parent
while (current) {
if (
current.type === 'JSXElement' &&
@@ -621,8 +658,8 @@ function isInsideTooltipTrigger(openingElement, tooltipTriggerNames) {
return false
}
-function getOwningVariableName(openingElement) {
- let current = openingElement.parent
+function getOwningVariableName(openingElement: TSESTree.JSXOpeningElement) {
+ let current: TSESTree.Node | undefined = openingElement.parent
while (current) {
if (current.type === 'VariableDeclarator')
return current.id.type === 'Identifier' ? current.id.name : null
@@ -637,7 +674,7 @@ function getOwningVariableName(openingElement) {
return null
}
-function collectReferencedIdentifiers(node, names) {
+function collectReferencedIdentifiers(node: TSESTree.Node | undefined, names: Set<string>) {
const current = unwrapExpression(node)
if (!current) return
if (current.type === 'Identifier') {
@@ -653,8 +690,7 @@ function collectReferencedIdentifiers(node, names) {
}
}
-/** @type {import('eslint').Rule.RuleModule} */
-export default {
+const rule: TSESLint.RuleModule<string, []> = {
meta: {
type: 'suggestion',
docs: {
@@ -668,13 +704,14 @@ export default {
},
schema: [],
},
+ defaultOptions: [],
create(context) {
- const candidates = []
- const renderIdentifiers = new Set()
- const tooltipTriggerNames = new Set()
- const cssModuleBindings = new Map()
+ const candidates: TSESTree.JSXOpeningElement[] = []
+ const renderIdentifiers = new Set<string>()
+ const tooltipTriggerNames = new Set<string>()
+ const cssModuleBindings: CssModuleBindings = new Map()
- function recordCssModuleImport(node) {
+ function recordCssModuleImport(node: TSESTree.ImportDeclaration) {
if (typeof node.source.value !== 'string' || !node.source.value.endsWith('.module.css'))
return
const defaultSpecifier = node.specifiers.find(
@@ -696,7 +733,9 @@ export default {
for (const specifier of node.specifiers) {
if (
specifier.type === 'ImportSpecifier' &&
- (specifier.imported.name ?? specifier.imported.value) === 'TooltipTrigger'
+ (specifier.imported.type === 'Identifier'
+ ? specifier.imported.name
+ : specifier.imported.value) === 'TooltipTrigger'
)
tooltipTriggerNames.add(specifier.local.name)
}
@@ -741,3 +780,6 @@ export default {
}
},
}
+
+// ESLint and Oxlint supply the parser-specific AST used by these typed listeners.
+export default rule as unknown as Rule.RuleModule
diff --git a/packages/tooling/plugins/eslint/utils.js b/packages/tooling/plugins/eslint/utils.js
deleted file mode 100644
index e0a20c8c580..00000000000
--- a/packages/tooling/plugins/eslint/utils.js
+++ /dev/null
@@ -1,9 +0,0 @@
-export const cleanJsonText = (text) => {
- const cleaned = text.replaceAll(/,\s*\}/g, '}')
- try {
- JSON.parse(cleaned)
- return cleaned
- } catch {
- return text
- }
-}
diff --git a/packages/tooling/plugins/eslint/utils.ts b/packages/tooling/plugins/eslint/utils.ts
new file mode 100644
index 00000000000..64d32cec4e8
--- /dev/null
+++ b/packages/tooling/plugins/eslint/utils.ts
@@ -0,0 +1,31 @@
+import type { AST, Rule, SourceCode } from 'eslint'
+import type { AST as JsonAST } from 'jsonc-eslint-parser'
+
+export type JsonRuleModule = Omit<Rule.RuleModule, 'create'> & {
+ create: (context: Rule.RuleContext) => {
+ [Type in JsonAST.JSONNode['type']]?: (node: Extract<JsonAST.JSONNode, { type: Type }>) => void
+ }
+}
+
+type DisableDirective = {
+ type: 'disable' | 'enable' | 'disable-next-line' | 'disable-line'
+ value: string
+ justification: string
+ node: AST.Token
+}
+
+export function getDisableDirectives(sourceCode: SourceCode) {
+ return (
+ sourceCode as SourceCode & { getDisableDirectives: () => { directives: DisableDirective[] } }
+ ).getDisableDirectives().directives
+}
+
+export const cleanJsonText = (text: string) => {
+ const cleaned = text.replaceAll(/,\s*\}/g, '}')
+ try {
+ JSON.parse(cleaned)
+ return cleaned
+ } catch {
+ return text
+ }
+}
diff --git a/packages/tooling/scripts/check-web-production-unused-after-knip-fix.mjs b/packages/tooling/scripts/check-web-production-unused-after-knip-fix.ts
similarity index 85%
rename from packages/tooling/scripts/check-web-production-unused-after-knip-fix.mjs
rename to packages/tooling/scripts/check-web-production-unused-after-knip-fix.ts
index ec53f523ccc..f1b0ace66bc 100644
--- a/packages/tooling/scripts/check-web-production-unused-after-knip-fix.mjs
+++ b/packages/tooling/scripts/check-web-production-unused-after-knip-fix.ts
@@ -5,6 +5,13 @@ import path from 'node:path'
import { fileURLToPath } from 'node:url'
import unusedConfig from '../oxlint.unused.config.json' with { type: 'json' }
+type OxlintDiagnostic = {
+ labels?: { file?: string; span?: { line: number; column: number } }[]
+ filename?: string
+ code?: string
+ message?: string
+}
+
const scriptDir = path.dirname(fileURLToPath(import.meta.url))
const repoRoot = path.resolve(scriptDir, '../../..')
const webDir = path.join(repoRoot, 'web')
@@ -20,31 +27,33 @@ const oxlintBin =
if (!oxlintBin) throw new Error('Unable to resolve the bundled Oxlint executable.')
const oxlint = path.resolve(path.dirname(oxlintPackagePath), oxlintBin)
-function run(command, args, options = {}) {
- return new Promise((resolve, reject) => {
- const child = spawn(command, args, {
- cwd: options.cwd,
- env: process.env,
- shell: false,
- })
-
- let stdout = ''
- let stderr = ''
- child.stdout.on('data', (data) => (stdout += data))
- child.stderr.on('data', (data) => (stderr += data))
- child.on('error', reject)
- child.on('close', (status) => resolve({ status, stdout, stderr }))
- })
+function run(command: string, args: string[], options: { cwd?: string } = {}) {
+ return new Promise<{ status: number | null; stdout: string; stderr: string }>(
+ (resolve, reject) => {
+ const child = spawn(command, args, {
+ cwd: options.cwd,
+ env: process.env,
+ shell: false,
+ })
+
+ let stdout = ''
+ let stderr = ''
+ child.stdout.on('data', (data) => (stdout += data))
+ child.stderr.on('data', (data) => (stderr += data))
+ child.on('error', reject)
+ child.on('close', (status) => resolve({ status, stdout, stderr }))
+ },
+ )
}
-function parseOxlintJson(stdout) {
+function parseOxlintJson(stdout: string): { diagnostics?: OxlintDiagnostic[] } {
const jsonStart = stdout.indexOf('{')
if (jsonStart === -1) throw new Error('Oxlint produced no JSON output.')
return JSON.parse(stdout.slice(jsonStart))
}
-function relativeDiagnostic(diagnostic) {
+function relativeDiagnostic(diagnostic: OxlintDiagnostic) {
const label = diagnostic.labels?.[0]
const diagnosticFile = label?.file ?? diagnostic.filename
const filePath = diagnosticFile
diff --git a/packages/tooling/scripts/lint-a11y.mjs b/packages/tooling/scripts/lint-a11y.ts
similarity index 92%
rename from packages/tooling/scripts/lint-a11y.mjs
rename to packages/tooling/scripts/lint-a11y.ts
index 43ee48bf762..e7078f3536d 100644
--- a/packages/tooling/scripts/lint-a11y.mjs
+++ b/packages/tooling/scripts/lint-a11y.ts
@@ -55,12 +55,12 @@ const ignoredDirectories = new Set([
'storybook-static',
])
-function isWithinWebRoot(filePath) {
+function isWithinWebRoot(filePath: string) {
const relativePath = path.relative(webRoot, filePath)
return relativePath !== '' && !relativePath.startsWith('..') && !path.isAbsolute(relativePath)
}
-function isTraversableSourceFile(filePath) {
+function isTraversableSourceFile(filePath: string) {
if (!isWithinWebRoot(filePath) || !sourceExtensions.has(path.extname(filePath))) return false
if (/\.d\.[cm]?ts$/u.test(filePath)) return false
@@ -70,9 +70,9 @@ function isTraversableSourceFile(filePath) {
.some((segment) => ignoredDirectories.has(segment))
}
-function formatTypeScriptDiagnostics(diagnostics) {
+function formatTypeScriptDiagnostics(diagnostics: readonly ts.Diagnostic[]) {
return ts.formatDiagnostics(diagnostics, {
- getCanonicalFileName: (fileName) => fileName,
+ getCanonicalFileName: (fileName: string) => fileName,
getCurrentDirectory: () => webRoot,
getNewLine: () => ts.sys.newLine,
})
@@ -103,7 +103,7 @@ function readCompilerOptions() {
return parsedConfig.options
}
-function collectLocalDependencies(entryFiles) {
+function collectLocalDependencies(entryFiles: string[]) {
for (const entryFile of entryFiles) {
let stats
@@ -122,18 +122,18 @@ function collectLocalDependencies(entryFiles) {
const compilerOptions = readCompilerOptions()
const canonicalFileName = ts.sys.useCaseSensitiveFileNames
- ? (fileName) => fileName
- : (fileName) => fileName.toLowerCase()
+ ? (fileName: string) => fileName
+ : (fileName: string) => fileName.toLowerCase()
const resolutionCache = ts.createModuleResolutionCache(
webRoot,
canonicalFileName,
compilerOptions,
)
- const visitedFiles = new Map()
+ const visitedFiles = new Map<string, string>()
const pending = [...entryFiles]
while (pending.length > 0) {
- const currentFile = path.resolve(pending.pop())
+ const currentFile = path.resolve(pending.pop()!)
const canonicalCurrentFile = canonicalFileName(currentFile)
if (visitedFiles.has(canonicalCurrentFile)) continue
diff --git a/packages/tooling/tsconfig.json b/packages/tooling/tsconfig.json
index 2b8337e5ff9..2ac29bca1a4 100644
--- a/packages/tooling/tsconfig.json
+++ b/packages/tooling/tsconfig.json
@@ -1,7 +1,9 @@
{
"extends": "@dify/tsconfig/node.json",
"compilerOptions": {
- "allowImportingTsExtensions": true
+ "types": ["node", "vite/client"],
+ "allowImportingTsExtensions": true,
+ "allowJs": false
},
- "include": ["**/*.ts", "**/*.js", "**/*.mjs"]
+ "include": ["**/*.ts"]
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d226e57078f..f6dbd575861 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -386,6 +386,9 @@ catalogs:
'@typescript-eslint/parser':
specifier: 8.71.2
version: 8.71.2
+ '@typescript-eslint/utils':
+ specifier: 8.71.2
+ version: 8.71.2
'@typescript/native':
specifier: npm:[email protected]
version: 7.0.2
@@ -575,6 +578,9 @@ catalogs:
js-yaml:
specifier: 5.5.0
version: 5.5.0
+ jsonc-eslint-parser:
+ specifier: 3.3.0
+ version: 3.3.0
jsonschema:
specifier: 1.5.0
version: 1.5.0
@@ -1355,6 +1361,12 @@ importers:
'@types/node':
specifier: 'catalog:'
version: 25.9.9
+ '@typescript-eslint/utils':
+ specifier: 'catalog:'
+ jsonc-eslint-parser:
+ specifier: 'catalog:'
+ version: 3.3.0
vite:
specifier: 'catalog:'
@@ -17051,6 +17063,7 @@ time:
'@types/[email protected]': '2026-09-09T18:08:49.750Z'
'@types/[email protected]': '2025-10-24T04:31:45.132Z'
'@typescript-eslint/[email protected]': '2026-10-12T17:11:57.903Z'
+ '@typescript-eslint/[email protected]': '2026-10-12T17:09:24.822Z'
'@typescript/[email protected]': '2026-07-06T18:06:47.459Z'
'@vitejs/[email protected]': '2026-10-05T10:08:27.143Z'
'@vitejs/[email protected]': '2026-10-15T02:02:18.001Z'
@@ -17116,6 +17129,7 @@ time:
[email protected]: '2026-09-29T14:18:19.043Z'
[email protected]: '2026-05-29T10:51:39.065Z'
[email protected]: '2026-10-15T23:28:37.500Z'
+ [email protected]: '2026-08-08T01:15:58.520Z'
[email protected]: '2025-01-07T15:09:11.287Z'
[email protected]: '2026-05-22T08:06:26.967Z'
[email protected]: '2026-10-18T13:44:32.638Z'
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 216953b7680..513015964de 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -142,6 +142,7 @@ catalog:
'@types/react-dom': 19.3.0
'@types/sortablejs': 1.15.9
'@typescript-eslint/parser': 8.71.2
+ '@typescript-eslint/utils': 8.71.2
'@typescript/native': npm:[email protected]
'@vitejs/plugin-react': 6.1.2
'@vitejs/plugin-rsc': 0.5.38
@@ -206,6 +207,7 @@ catalog:
jotai-tanstack-query: 0.11.0
js-cookie: 3.0.8
js-yaml: 5.5.0
+ jsonc-eslint-parser: 3.3.0
jsonschema: 1.5.0
katex: 0.17.0
knip: 6.42.0
diff --git a/web/package.json b/web/package.json
index 2b747dbabea..485a2a25aa9 100644
--- a/web/package.json
+++ b/web/package.json
@@ -25,7 +25,7 @@
"i18n:check-types": "node ./scripts/generate-i18n-types.ts --check",
"i18n:generate-types": "node ./scripts/generate-i18n-types.ts",
"i18n:migrate-selectors": "node ./scripts/migrate-i18n-selectors.ts",
- "lint:a11y": "node ../packages/tooling/scripts/lint-a11y.mjs",
+ "lint:a11y": "node ../packages/tooling/scripts/lint-a11y.ts",
"lint:tss": "tsslint --project tsconfig.json",
"migrate:type-assertions": "TSSLINT_TYPE_ASSERTION_MIGRATION=true tsslint --project tsconfig.json --force --fix",
"preinstall": "npx only-allow pnpm",