dev: migrate to Biome for linting/formatting (#5423)

* Migrate to Biome for linting/formatting and simplify hooks

- Add biome.jsonc and @biomejs CLI; configure VS Code to use Biome for format/fix and imports
- Replace verbose Husky pre-commit with lint-staged runner
- Remove ESLint setup and custom rule package (no-direct-vscode-api) and its tests
- Update package.json/package-lock and webview-ui package to reflect tooling change
- Add VS Code host typings and grit definitions under src/hosts

Rationale: unify lint/format tooling, speed up pre-commit checks, and reduce maintenance overhead from custom ESLint rules.

* remove eslint dependencies

* preserve eslint rules

* clean up

* update files list

* add docs

* fix build

* clean up

* update VSCode API usage detection in Grit rule

This commit updates the Grit rule for detecting VSCode API usage:
- Narrow down the list of monitored VSCode API methods
- Add more specific diagnostic messages for direct API usage
- Introduce a new check for `workspaceFolders` property
- Exclude `src/extension.ts` from the Grit rule in Biome configuration

The changes aim to improve code abstraction and provide clearer guidance for replacing direct VSCode API calls.

* adds new cacheService rule

* add back pre-commit

* Remove ESLint custom rule and update linting references

Remove custom ESLint rule for VSCode state API enforcement along with its tests, remove ESLint extension recommendation, and update documentation to use generic "linter" terminology instead of ESLint-specific references.

* update vscode.d.ts for IntelliSense

* remove format on save

* clean up default values

* update to 2.1.4

* buf lint

* format
This commit is contained in:
Bee authored and GitHub committed 2025-08-18 13:34:09 -07:00
1 parent 0054b21d67
commit 5d75a311f4
29 files changed
+653 -5892

No files matched your search

-34
View File
@@ -1,34 +0,0 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"plugins": ["@typescript-eslint", "eslint-rules"],
"rules": {
"@typescript-eslint/naming-convention": [
"warn",
{
"selector": "import",
"format": ["camelCase", "PascalCase"]
}
],
"@typescript-eslint/semi": "off",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off",
"react-hooks/exhaustive-deps": "off",
"eslint-rules/no-direct-vscode-api": "warn",
"eslint-rules/no-direct-vscode-state-api": "error",
"no-restricted-syntax": [
"error",
{
"selector": "VariableDeclarator[id.type=\"ObjectPattern\"][init.object.name=\"process\"][init.property.name=\"env\"]",
"message": "Use process.env.VARIABLE_NAME directly instead of destructuring"
}
]
},
"ignorePatterns": ["out", "dist", "dist-standalone", "**/*.d.ts", "node_modules"]
}
+3 -9
View File
@@ -71,13 +71,7 @@ jobs:
- name: Install xvfb on Linux
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y xvfb
- name: Install local modules on windows
if: runner.os == 'Windows' && steps.root-cache.outputs.cache-hit == 'true'
run: |
npm install eslint-plugin-eslint-rules
cd webview-ui/ && npm install eslint-plugin-eslint-rules
- name: Set up NPM on Windows
if: runner.os == 'Windows'
run: |
@@ -86,10 +80,10 @@ jobs:
- name: Type Check
run: npm run check-types
- name: ESLint Check
- name: Lint Check
run: npm run lint
- name: Prettier / Format Check
- name: Format Check
run: npm run format
# Build the extension before running tests
Executable → Regular
+1 -17
View File
@@ -1,17 +1 @@
echo "Running pre-commit checks..."
# Run ESLint
echo "Running ESLint..."
npm run lint || {
echo "❌ ESLint check failed. Please fix the errors and try committing again."
exit 1
}
# Run Prettier
echo "Running Prettier..."
npx lint-staged --verbose || {
echo "❌ Prettier failed. Please fix the errors and try committing again."
exit 1
}
echo "✅ All checks passed!"
lint-staged
-10
View File
@@ -1,10 +0,0 @@
dist/
node_modules
webview-ui/build/
*.md
package-lock.json
src/core/prompts/system.ts
src/core/prompts/model_prompts/claude4.ts
evals/
docs/
out/
-8
View File
@@ -1,8 +0,0 @@
{
"tabWidth": 4,
"useTabs": true,
"printWidth": 130,
"semi": false,
"bracketSameLine": true,
"endOfLine": "lf"
}
+2 -2
View File
@@ -2,9 +2,9 @@
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"dbaeumer.vscode-eslint",
"connor4312.esbuild-problem-matchers",
"ms-vscode.extension-test-runner",
"bradlc.vscode-tailwindcss"
"bradlc.vscode-tailwindcss",
"biomejs.biome"
]
}
+21 -2
View File
@@ -6,12 +6,31 @@
},
"search.exclude": {
"out": true, // set this to false to include "out" folder in search results
"dist": true // set this to false to include "dist" folder in search results
"dist": true, // set this to false to include "dist" folder in search results,
"node_modules": true,
"dist-standalone": true
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off",
"typescript.preferences.quoteStyle": "double",
// Protobuf settings
"protoc": {
"options": ["--proto_path=proto"]
"options": [
"--proto_path=proto"
]
},
// Enable Lint and format using Biome
"biome.enabled": true,
"[typescript]": {
"editor.defaultFormatter": "biomejs.biome"
},
"[typescriptreact]": {
"editor.defaultFormatter": "biomejs.biome"
},
"[jsonc]": {
"editor.defaultFormatter": "biomejs.biome"
},
"[json]": {
"editor.defaultFormatter": "biomejs.biome"
}
}
+1 -1
View File
@@ -147,7 +147,7 @@ Anyone can contribute code to Cline, but we ask that you follow these guidelines
- Run `npm run lint` to check code style
- Run `npm run format` to automatically format code
- All PRs must pass CI checks which include both linting and formatting
- Address any ESLint warnings or errors before submitting
- Address any warnings or errors from linter before submitting
- Follow TypeScript best practices and maintain type safety
3. **Testing**
+166
View File
@@ -0,0 +1,166 @@
{
"$schema": "https://biomejs.dev/schemas/2.1.4/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true,
"defaultBranch": "main"
},
"assist": {
"enabled": true,
"actions": {
"source": {
"organizeImports": "on",
"useSortedAttributes": "on"
}
}
},
"linter": {
"enabled": true,
"domains": {
"react": "recommended"
},
// Ideally we would want to turn on all the rules that are currently off,
// keeping them off currently to make sure only changes on the migrations
// are included in the initial PR before we apply the format and lint changes.
// TODO: turn on all rules that are currently off if applicable.
// TODO: Remove --diagnostic-level=error from CI commands.
"rules": {
"recommended": true,
"correctness": {
"useExhaustiveDependencies": "off",
"noUndeclaredVariables": "off",
"noUnusedVariables": "off",
"noEmptyPattern": "off",
"useJsxKeyInIterable": "off",
"noInnerDeclarations": "off",
"useHookAtTopLevel": "off",
"useYield": "off",
"noUnusedFunctionParameters": "off",
"noConstructorReturn": "off",
"noInvalidPositionAtImportRule": "off",
"noSwitchDeclarations": "off",
"noUnusedImports": "off"
},
"a11y": "off",
"style": {
"useNodejsImportProtocol": "off",
"useImportType": "off",
"useBlockStatements": "warn",
"useNamingConvention": "off",
"useThrowOnlyError": "info",
"useConsistentArrayType": "off",
"noParameterAssign": "off",
"useAsConstAssertion": "off",
"useDefaultParameterLast": "off",
"noNonNullAssertion": "off",
"useEnumInitializers": "off",
"useSelfClosingElements": "off",
"useSingleVarDeclarator": "off",
"noUnusedTemplateLiteral": "off",
"useNumberNamespace": "off",
"noInferrableTypes": "off",
"useTemplate": "off",
"noUselessElse": "off"
},
"suspicious": {
"noDoubleEquals": "warn",
"noImplicitAnyLet": "info",
"noThenProperty": "off",
"noAsyncPromiseExecutor": "off",
"noImportAssign": "off",
"noExplicitAny": "off",
"noControlCharactersInRegex": "off",
"noShadowRestrictedNames": "off",
"noArrayIndexKey": "info",
"noAssignInExpressions": "warn"
},
"complexity": {
"noUselessConstructor": "off",
"useOptionalChain": "off",
"noBannedTypes": "off",
"useLiteralKeys": "off",
"noUselessCatch": "off",
"noUselessSwitchCase": "off",
"noStaticOnlyClass": "off"
},
"security": {
"noDangerouslySetInnerHtml": "warn"
}
}
},
"formatter": {
"enabled": true,
"indentStyle": "tab",
"indentWidth": 4,
"lineWidth": 130,
"lineEnding": "lf",
"formatWithErrors": false,
// TODO: Enable formatter for all files - currently off to keep PR changes minimal
"includes": [
"**",
"!src/core/prompts/**",
"!webview-ui/src/components/chat/**"
]
},
"javascript": {
"formatter": {
"semicolons": "asNeeded",
"arrowParentheses": "always",
"bracketSameLine": true,
"bracketSpacing": true,
"jsxQuoteStyle": "double",
"quoteProperties": "asNeeded",
"trailingCommas": "all"
}
},
"json": {
"formatter": {
"trailingCommas": "none",
"expand": "always"
}
},
"files": {
"includes": [
"**",
"!**/dist/**",
"!**/dist-*/**",
"!**/out/**",
"!**/evals/**",
"!**/playwright/**",
"!**/test-results/**",
"!**/node_modules/**",
"!**/webview-ui/build/**"
]
},
"plugins": [
"src/dev/grit/process-env.grit"
],
"overrides": [
{
"includes": [
"**",
"!**/hosts/vscode/**",
"!**/test/**",
"!src/extension.ts"
],
"plugins": [
"src/dev/grit/vscode-api.grit"
]
},
{
"includes": [
"**",
"!src/core/storage/state-migrations.ts",
"!src/core/storage/FileContextTracker.ts",
"!src/core/context/context-tracking/FileContextTracker.ts",
"!src/common.ts",
"!src/core/storage/utils/state-helpers.ts",
"!src/extension.ts"
],
"plugins": [
"src/dev/grit/use-cache-service.grit"
]
}
]
}
@@ -1,118 +0,0 @@
const { RuleTester: DirectApiRuleTester } = require("eslint")
const noDirectVscodeApiRule = require("../no-direct-vscode-api")
const directApiRuleTester = new DirectApiRuleTester({
parser: require.resolve("@typescript-eslint/parser"),
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
})
directApiRuleTester.run("no-direct-vscode-api", noDirectVscodeApiRule, {
valid: [
// Should allow vscode.postMessage in grpc-client-base.ts
{
code: `vscode.postMessage({ type: "grpc_request", data: {} })`,
filename: "grpc-client-base.ts",
},
{
code: `vscode.postMessage({ type: "grpc_request_cancel" })`,
filename: "/path/to/grpc-client-base.ts",
},
// Should allow in exception directories
{
code: `vscode.workspace.workspaceFolders`,
filename: "/src/hosts/vscode/host-bridge.ts",
},
{
code: `vscode.workspace.fs.stat(uri)`,
filename: "/standalone/runtime-files/helpers.ts",
},
// Should allow other vscode API calls
{
code: `vscode.commands.registerCommand("Hello")`,
filename: "/foo/bar.ts",
},
// Should allow postMessage calls on other objects
{
code: `window.postMessage({ type: "test" }, "*")`,
filename: "/foo/bar.ts",
},
// Should allow variables named vscode but not calling postMessage
{
code: `const vscode = { other: "method" }; vscode.other()`,
filename: "/foo/bar.ts",
},
// Should allow vscode.postMessage in test files
{
code: `vscode.postMessage({ type: "newTask", text: message.text })`,
filename: "/foo/bar.test.ts",
},
],
invalid: [
// Should disallow vscode.postMessage in regular files
{
code: `vscode.postMessage({ type: "test", data: {} })`,
filename: "/foo/bar.ts",
errors: [
{
messageId: "useGrpcClient",
},
],
},
// Should disallow vscode.postMessage in components
{
code: `vscode.postMessage({ type: "apiConfiguration", apiConfiguration })`,
filename: "ApiOptions.tsx",
errors: [
{
messageId: "useGrpcClient",
},
],
},
// Should disallow property access for disallowed APIs
{
code: `const folders = vscode.workspace.workspaceFolders;`,
filename: "workspace.ts",
errors: [
{
messageId: "useHostBridgeWorkspace",
},
],
},
// Should disallow method calls for disallowed APIs
{
code: `const relativePath = vscode.workspace.asRelativePath(filePath);`,
filename: "path-utils.ts",
errors: [
{
messageId: "usePathUtils",
},
],
},
// Should disallow nested property access
{
code: `const stats = await vscode.workspace.fs.stat(uri);`,
filename: "file-utils.ts",
errors: [
{
messageId: "useFsUtils",
},
],
},
// Should disallow getting a workspace folder
{
code: `const folder = vscode.workspace.getWorkspaceFolder(uri);`,
filename: "path-helper.ts",
errors: [
{
messageId: "usePathUtils",
},
],
},
],
})
@@ -1,171 +0,0 @@
const { RuleTester: StateApiRuleTester } = require("eslint")
const noDirectVscodeStateApiRule = require("../no-direct-vscode-state-api")
const stateApiRuleTester = new StateApiRuleTester({
parser: require.resolve("@typescript-eslint/parser"),
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
})
stateApiRuleTester.run("no-direct-vscode-state-api", noDirectVscodeStateApiRule, {
valid: [
// Should allow state APIs in CacheService.ts
{
code: `await context.globalState.update("myKey", value);`,
filename: "CacheService.ts",
},
{
code: `const value = context.globalState.get("myKey");`,
filename: "/src/core/storage/CacheService.ts",
},
{
code: `await context.secrets.store("apiKey", value);`,
filename: "CacheService.ts",
},
// Should allow state APIs in state-helpers.ts
{
code: `const value = context.globalState.get("myKey");`,
filename: "state-helpers.ts",
},
{
code: `await context.secrets.get("apiKey");`,
filename: "/src/core/storage/utils/state-helpers.ts",
},
// Should allow state APIs in state-migrations.ts
{
code: `await context.globalState.update("myKey", value);`,
filename: "state-migrations.ts",
},
{
code: `const value = context.workspaceState.get("myKey");`,
filename: "/src/core/storage/state-migrations.ts",
},
// Should allow state APIs in extension.ts
{
code: `const distinctId = context.globalState.get<string>("cline.distinctId");`,
filename: "extension.ts",
},
{
code: `await context.globalState.update("clineVersion", currentVersion);`,
filename: "/src/extension.ts",
},
{
code: `const secret = await context.secrets.get("clineAccountId");`,
filename: "extension.ts",
},
// Should allow state APIs in test files
{
code: `context.globalState.get("testKey")`,
filename: "/foo/bar.test.ts",
},
// Should allow non-state API calls
{
code: `const value = someOtherObject.globalState.get("myKey");`,
filename: "some-file.ts",
},
{
code: `await myContext.secrets.store("key", "value");`,
filename: "some-file.ts",
},
],
invalid: [
// Should disallow context.globalState.get
{
code: `const value = context.globalState.get("myKey");`,
filename: "some-file.ts",
errors: [
{
messageId: "useCacheServiceGlobalGet",
},
],
},
// Should disallow context.globalState.update
{
code: `await context.globalState.update("myKey", "myValue");`,
filename: "some-file.ts",
errors: [
{
messageId: "useCacheServiceGlobalSet",
},
],
},
// Should disallow context.workspaceState.get
{
code: `const value = context.workspaceState.get("myKey");`,
filename: "some-file.ts",
errors: [
{
messageId: "useCacheServiceWorkspaceGet",
},
],
},
// Should disallow context.workspaceState.update
{
code: `await context.workspaceState.update("myKey", "myValue");`,
filename: "some-file.ts",
errors: [
{
messageId: "useCacheServiceWorkspaceSet",
},
],
},
// Should disallow context.secrets.get
{
code: `const secret = await context.secrets.get("apiKey");`,
filename: "some-file.ts",
errors: [
{
messageId: "useCacheServiceSecretsGet",
},
],
},
// Should disallow context.secrets.store
{
code: `await context.secrets.store("apiKey", "secret-value");`,
filename: "some-file.ts",
errors: [
{
messageId: "useCacheServiceSecretsSet",
},
],
},
// Should disallow context.secrets.delete
{
code: `await context.secrets.delete("apiKey");`,
filename: "some-file.ts",
errors: [
{
messageId: "useCacheServiceSecretsSet",
},
],
},
// Should disallow chained state API calls
{
code: `const value = await context.globalState.get("key") || "default";`,
filename: "some-file.ts",
errors: [
{
messageId: "useCacheServiceGlobalGet",
},
],
},
// Should disallow state API calls in Promise.all
{
code: `await Promise.all([context.secrets.get("key1"), context.secrets.get("key2")]);`,
filename: "some-file.ts",
errors: [
{
messageId: "useCacheServiceSecretsGet",
},
{
messageId: "useCacheServiceSecretsGet",
},
],
},
],
})
-19
View File
@@ -1,19 +0,0 @@
// eslint-rules/index.js
const noDirectVscodeApi = require("./no-direct-vscode-api")
const noDirectVscodeStateApi = require("./no-direct-vscode-state-api")
module.exports = {
rules: {
"no-direct-vscode-api": noDirectVscodeApi,
"no-direct-vscode-state-api": noDirectVscodeStateApi,
},
configs: {
recommended: {
plugins: ["local"],
rules: {
"local/no-direct-vscode-api": "warn",
"local/no-direct-vscode-state-api": "error",
},
},
},
}
-224
View File
@@ -1,224 +0,0 @@
const { ESLintUtils } = require("@typescript-eslint/utils")
const path = require("path")
const createRule = ESLintUtils.RuleCreator((name) => `https://cline.bot/eslint-rules/${name}`)
// Configuration of disallowed VSCode APIs and their recommended alternatives
const disallowedApis = {
"vscode.postMessage": {
messageId: "useGrpcClient",
},
"vscode.workspace.fs.stat": {
messageId: "useFsUtils",
},
"vscode.workspace.fs.writeFile": {
messageId: "useFsUtils",
},
"vscode.workspace.workspaceFolders": {
messageId: "useHostBridgeWorkspace",
},
"vscode.workspace.asRelativePath": {
messageId: "usePathUtils",
},
"vscode.workspace.getWorkspaceFolder": {
messageId: "usePathUtils",
},
"vscode.window.showTextDocument": {
messageId: "useHostBridge",
},
"vscode.workspace.applyEdit": {
messageId: "useHostBridge",
},
"vscode.window.onDidChangeActiveTextEditor": {
messageId: "useHostBridge",
},
"vscode.env.openExternal": {
messageId: "useUtils",
},
"vscode.window.showWarningMessage": {
messageId: "useHostBridgeShowMessage",
},
"vscode.window.showOpenDialog": {
messageId: "useHostBridgeShowMessage",
},
"vscode.window.showErrorMessage": {
messageId: "useHostBridgeShowMessage",
},
"vscode.window.showInformationMessage": {
messageId: "useHostBridgeShowMessage",
},
"vscode.window.showInputBox": {
messageId: "useHostBridge",
},
"vscode.workspace.findFiles": {
messageId: "useNative",
},
}
module.exports = createRule({
name: "no-direct-vscode-api",
meta: {
type: "problem",
docs: {
description:
"Disallow direct VSCode API usage in favor of Cline's abstraction layers, except in src/hosts/vscode and standalone/runtime-files directories",
recommended: "error",
},
messages: {
useGrpcClient:
"Use gRPC service clients instead of vscode.postMessage().\n" +
"Example: AccountServiceClient.methodName(RequestType.create({...})) instead of vscode.postMessage({type: '...'}).\n" +
"Found: {{code}}",
useFsUtils:
"Use utilities in @/utils/fs instead of vscode.workspace.fs\n" +
"Example: import { isDirectory } from '@/utils/fs' or use the file system methods from the host bridge provider.\n" +
"Found: {{code}}",
usePathUtils:
"Use path utilities from @/utils/path instead of VSCode workspace path methods.\n" +
"This provides consistent path handling across different environments.\n" +
"Found: {{code}}",
useHostBridgeWorkspace:
"Use HostProvider.workspace.getWorkspacePaths({}) instead of vscode.workspace.workspaceFolders.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
useHostBridgeShowMessage:
"Use HostProvider.window.showMessage instead of the vscode.window.showMessage.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
useHostBridge:
"Use the host bridge instead of calling vscode APIs directly.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
useUtils:
"Use utilities in @/utils instead of calling vscode APIs directly.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
useNative:
"Use a native Javascript API instead of calling the vscode API.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
},
schema: [],
},
defaultOptions: [],
create(context) {
// Pattern for checking memberExpressions like vscode.workspace.fs.stat
function checkMemberExpression(node) {
if (isExcluded(context.filename)) {
// Skip if this file is being excluded.
return
}
// For handling nested properties like vscode.workspace.fs.stat
function getFullPropertyPath(node) {
if (node.type !== "MemberExpression") {
return node.name || ""
}
const objectPart = getFullPropertyPath(node.object)
const propertyPart = node.property.name || ""
return objectPart ? `${objectPart}.${propertyPart}` : propertyPart
}
// Check if the expression matches one of our disallowed patterns
if (node.object && node.object.type === "Identifier" && node.object.name === "vscode") {
const fullPath = `vscode.${node.property.name}`
checkDisallowedApi(fullPath, node)
}
// Handle nested expressions like vscode.workspace.fs.stat
else if (node.object && node.object.type === "MemberExpression") {
const fullPath = getFullPropertyPath(node)
// Only proceed if it starts with vscode
if (fullPath.startsWith("vscode.")) {
checkDisallowedApi(fullPath, node)
}
}
}
// Check if an expression matches a disallowed API and report if it does
function checkDisallowedApi(expressionPath, node) {
// Check exact matches
if (disallowedApis[expressionPath]) {
reportViolation(expressionPath, node)
return
}
// Check prefix matches (for nested properties)
for (const disallowedApi in disallowedApis) {
// For direct property access like vscode.workspace.workspaceFolders
if (expressionPath === disallowedApi) {
reportViolation(disallowedApi, node)
return
}
// For method calls like vscode.workspace.asRelativePath(...)
if (expressionPath.startsWith(`${disallowedApi}.`) || expressionPath.startsWith(`${disallowedApi}(`)) {
reportViolation(disallowedApi, node)
return
}
}
}
// Report a violation with the appropriate message
function reportViolation(disallowedApi, node) {
const sourceCode = context.sourceCode
const config = disallowedApis[disallowedApi]
// For method calls, get the whole call expression
let reportNode = node
let parentNode = sourceCode.getAncestors(node).pop()
if (parentNode && parentNode.type === "CallExpression" && parentNode.callee === node) {
reportNode = parentNode
}
const callText = sourceCode.getText(reportNode).trim()
context.report({
node: reportNode,
messageId: config.messageId,
data: {
code: callText,
},
})
}
function isExcluded(filename) {
// Check if current file is in an exception directory or is grpc-client-base.ts
if (path.basename(filename) === "grpc-client-base.ts") {
return true
}
// Skip checking files in src/hosts/vscode or standalone/runtime-files
if (filename.includes("/src/hosts/vscode/")) {
return true
}
if (filename.includes("/standalone/runtime-files/")) {
return true
}
// Skip checking test files
if (filename.endsWith(".test.ts")) {
return true
}
}
return {
// Detect basic member expressions (e.g., vscode.postMessage)
MemberExpression(node) {
checkMemberExpression(node)
},
// Detect property access through destructuring
VariableDeclarator(node) {
// Skip if this file is in an exception directory or is grpc-client-base.ts
if (isExcluded(context.filename)) {
return
}
// Destructuring pattern checks removed as developers don't use the API this way
// They always use direct imports: import * as vscode from "vscode" and direct access: vscode.thing.foo
},
}
},
})
-144
View File
@@ -1,144 +0,0 @@
const { ESLintUtils } = require("@typescript-eslint/utils")
const path = require("path")
const createRule = ESLintUtils.RuleCreator((name) => `https://cline.bot/eslint-rules/${name}`)
// Configuration for context-based state APIs
const disallowedContextApis = {
"globalState.get": {
messageId: "useCacheServiceGlobalGet",
},
"globalState.update": {
messageId: "useCacheServiceGlobalSet",
},
"workspaceState.get": {
messageId: "useCacheServiceWorkspaceGet",
},
"workspaceState.update": {
messageId: "useCacheServiceWorkspaceSet",
},
"secrets.get": {
messageId: "useCacheServiceSecretsGet",
},
"secrets.store": {
messageId: "useCacheServiceSecretsSet",
},
"secrets.delete": {
messageId: "useCacheServiceSecretsSet",
},
}
module.exports = createRule({
name: "no-direct-vscode-state-api",
meta: {
type: "problem",
docs: {
description:
"Disallow direct VSCode state API usage (context.globalState, context.workspaceState, context.secrets) in favor of CacheService",
recommended: "error",
},
messages: {
useCacheServiceGlobalGet:
"Use CacheService.getGlobalStateKey() instead of context.globalState.get().\n" +
"The CacheService provides fast in-memory access with automatic persistence.\n" +
"Example: cacheService.getGlobalStateKey('myKey') instead of context.globalState.get('myKey').\n" +
"Found: {{code}}",
useCacheServiceGlobalSet:
"Use CacheService.setGlobalState() instead of context.globalState.update().\n" +
"The CacheService provides immediate updates with debounced persistence.\n" +
"Example: cacheService.setGlobalState('myKey', value) instead of context.globalState.update('myKey', value).\n" +
"Found: {{code}}",
useCacheServiceWorkspaceGet:
"Use CacheService.getWorkspaceStateKey() instead of context.workspaceState.get().\n" +
"The CacheService provides fast in-memory access with automatic persistence.\n" +
"Example: cacheService.getWorkspaceStateKey('myKey') instead of context.workspaceState.get('myKey').\n" +
"Found: {{code}}",
useCacheServiceWorkspaceSet:
"Use CacheService.setWorkspaceState() instead of context.workspaceState.update().\n" +
"The CacheService provides immediate updates with debounced persistence.\n" +
"Example: cacheService.setWorkspaceState('myKey', value) instead of context.workspaceState.update('myKey', value).\n" +
"Found: {{code}}",
useCacheServiceSecretsGet:
"Use CacheService.getSecretKey() instead of context.secrets.get().\n" +
"The CacheService provides fast in-memory access with automatic persistence.\n" +
"Example: cacheService.getSecretKey('mySecret') instead of context.secrets.get('mySecret').\n" +
"Found: {{code}}",
useCacheServiceSecretsSet:
"Use CacheService.setSecret() instead of context.secrets.store() or context.secrets.delete().\n" +
"The CacheService provides immediate updates with debounced persistence.\n" +
"Example: cacheService.setSecret('mySecret', value) instead of context.secrets.store('mySecret', value).\n" +
"For deletion, use: cacheService.setSecret('mySecret', undefined).\n" +
"Found: {{code}}",
},
schema: [],
},
defaultOptions: [],
create(context) {
function isExcluded(filename) {
// Skip checking test files
if (filename.endsWith(".test.ts")) {
return true
}
// Skip checking specific state-related files that need direct access
const basename = path.basename(filename)
if (
basename === "CacheService.ts" ||
basename === "state-helpers.ts" ||
basename === "state-migrations.ts" ||
basename === "extension.ts" ||
basename === "common.ts" // CI might report errors from this virtual file
) {
return true
}
return false
}
// Check for context-based state API calls
function checkContextStateApi(node) {
if (isExcluded(context.filename)) {
return
}
// Check if this is a member expression like context.globalState.get
if (
node.type === "MemberExpression" &&
node.object &&
node.object.type === "MemberExpression" &&
node.object.object &&
node.object.object.type === "Identifier" &&
node.object.object.name === "context"
) {
const stateType = node.object.property.name // e.g., "globalState", "workspaceState", "secrets"
const method = node.property.name // e.g., "get", "update", "store", "delete"
const apiPath = `${stateType}.${method}`
if (disallowedContextApis[apiPath]) {
// For method calls, get the whole call expression
let reportNode = node
let parentNode = context.sourceCode.getAncestors(node).pop()
if (parentNode && parentNode.type === "CallExpression" && parentNode.callee === node) {
reportNode = parentNode
}
const callText = context.sourceCode.getText(reportNode).trim()
context.report({
node: reportNode,
messageId: disallowedContextApis[apiPath].messageId,
data: {
code: callText,
},
})
}
}
}
return {
// Detect member expressions (e.g., context.globalState.get)
MemberExpression(node) {
checkContextStateApi(node)
},
}
},
})
-2479
View File
File diff suppressed because it is too large. Load diff
-31
View File
@@ -1,31 +0,0 @@
{
"name": "eslint-plugin-eslint-rules",
"version": "1.0.0",
"description": "Custom ESLint rules for Cline",
"main": "index.js",
"scripts": {
"test": "mocha --no-config --require ts-node/register __tests__/**/*.test.ts"
},
"keywords": [
"eslint",
"eslintplugin"
],
"author": "Cline Bot Inc.",
"license": "Apache-2.0",
"dependencies": {
"@typescript-eslint/utils": "^8.33.0"
},
"devDependencies": {
"@types/eslint": "^8.0.0",
"@types/mocha": "^10.0.7",
"@types/node": "^20.0.0",
"@typescript-eslint/parser": "^7.14.1",
"eslint": "^8.57.0",
"mocha": "^10.0.0",
"ts-node": "^10.9.2",
"typescript": "^5.4.5"
},
"peerDependencies": {
"eslint": ">=8.0.0"
}
}
-16
View File
@@ -1,16 +0,0 @@
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "dist",
"resolveJsonModule": true,
"declaration": true
},
"include": ["**/*.ts", "**/*.js", "**/*.tsx", "__tests__/**/*"],
"exclude": ["node_modules", "dist"]
}
+165 -1193
View File
File diff suppressed because it is too large. Load diff
+6 -11
View File
@@ -347,14 +347,14 @@
"watch:tsc": "tsc --noEmit --watch --project tsconfig.json",
"package": "npm run check-types && npm run build:webview && npm run lint && node esbuild.mjs --production",
"protos": "node scripts/build-proto.mjs",
"postprotos": "prettier src/shared/proto src/core/controller src/hosts/ webview-ui/src/services src/generated --write --log-level warn",
"postprotos": "biome format src/shared/proto src/core/controller src/hosts/ webview-ui/src/services src/generated --no-errors-on-unmatched",
"clean": "rimraf dist dist-standalone webview-ui/build src/generated out/",
"compile-tests": "node ./scripts/build-tests.js",
"watch-tests": "tsc -p . -w --outDir out",
"check-types": "npm run protos && npx tsc --noEmit && cd webview-ui && npx tsc -b --noEmit",
"lint": "eslint src --ext ts && eslint webview-ui/src --ext ts && buf lint && cd webview-ui && npm run lint",
"format": "prettier . --check",
"format:fix": "prettier . --write",
"lint": "biome lint --no-errors-on-unmatched --files-ignore-unknown=true --diagnostic-level=error && buf lint",
"format": "biome format --changed --no-errors-on-unmatched --files-ignore-unknown=true --diagnostic-level=error",
"format:fix": "biome check --changed --no-errors-on-unmatched --files-ignore-unknown=true --write",
"pretest": "npm run compile && npm run compile-tests && npm run compile-standalone && npm run lint",
"test": "npm-run-all test:unit test:integration",
"test:ci": "node scripts/test-ci.js",
@@ -380,10 +380,11 @@
},
"lint-staged": {
"*": [
"prettier --write --ignore-unknown --log-level=log"
"biome check --write --staged --no-errors-on-unmatched --files-ignore-unknown=true"
]
},
"devDependencies": {
"@biomejs/biome": "^2.1.4",
"@bufbuild/buf": "^1.54.0",
"@changesets/cli": "^2.27.12",
"@types/chai": "^5.0.1",
@@ -398,23 +399,17 @@
"@types/sinon": "^17.0.4",
"@types/turndown": "^5.0.5",
"@types/vscode": "^1.84.0",
"@typescript-eslint/eslint-plugin": "^7.14.1",
"@typescript-eslint/parser": "^7.18.0",
"@typescript-eslint/utils": "^8.33.0",
"@vscode/test-cli": "^0.0.10",
"@vscode/test-electron": "^2.5.2",
"@vscode/vsce": "^3.6.0",
"chai": "^4.3.10",
"chalk": "^5.3.0",
"esbuild": "^0.25.0",
"eslint": "^8.57.0",
"eslint-plugin-eslint-rules": "file:eslint-rules",
"grpc-tools": "^1.13.0",
"husky": "^9.1.7",
"lint-staged": "^16.1.0",
"minimatch": "^3.0.3",
"npm-run-all": "^4.1.5",
"prettier": "^3.3.3",
"protoc-gen-ts": "^0.8.7",
"proxyquire": "^2.1.3",
"rimraf": "^6.0.1",
+2
View File
@@ -7,6 +7,7 @@ import { cp } from "fs/promises"
import { glob } from "glob"
import minimatch from "minimatch"
import path from "path"
const BUILD_DIR = "dist-standalone"
const RUNTIME_DEPS_DIR = "standalone/runtime-files"
@@ -104,6 +105,7 @@ function createIsIgnored(standaloneIgnores) {
".eslintrc*",
".babelrc*",
".prettierrc*",
"biome.json*",
".cz-config.js",
".commitlintrc*",
"webpack.config.js",
+3
View File
@@ -0,0 +1,3 @@
`const { $vars } = process.env` where {
register_diagnostic(span=$vars, message="Use process.env.VARIABLE_NAME directly instead of destructuring.")
}
+12
View File
@@ -0,0 +1,12 @@
`$fn($args)` where {
or {
$fn <: `context.globalState.get`,
$fn <: `context.globalState.update`,
$fn <: `context.workspaceState.get`,
$fn <: `context.workspaceState.update`,
$fn <: `context.secrets.get`,
$fn <: `context.secrets.store`,
$fn <: `context.secrets.delete`
},
register_diagnostic(span=$fn, message="Use CacheService instead.")
}
+25
View File
@@ -0,0 +1,25 @@
or {
`$fn($args)` where {
or {
$fn <: `vscode.workspace.fs.stat`,
$fn <: `vscode.workspace.fs.writeFile`,
$fn <: `vscode.workspace.asRelativePath`,
$fn <: `vscode.workspace.getWorkspaceFolder`,
$fn <: `vscode.window.showTextDocument`,
$fn <: `vscode.workspace.applyEdit`,
$fn <: `vscode.window.onDidChangeActiveTextEditor`,
$fn <: `vscode.env.openExternal`,
$fn <: `vscode.window.showWarningMessage`,
$fn <: `vscode.window.showOpenDialog`,
$fn <: `vscode.window.showErrorMessage`,
$fn <: `vscode.window.showInformationMessage`,
$fn <: `vscode.window.showInputBox`,
$fn <: `vscode.workspace.findFiles`
},
register_diagnostic(span=$fn, message="Replace this with methods from the host bridge provider or appropriate abstraction layer.")
},
`vscode.$method.$var` where {
$var <: `workspaceFolders`,
register_diagnostic(span=$var, message="Use HostProvider.workspace.getWorkspacePaths({}) instead.")
}
}
+240
View File
@@ -0,0 +1,240 @@
/// <reference types="vscode" />
/**
* TypeScript declaration overrides to show deprecation warnings for direct VSCode API usage.
* These APIs should be accessed through Cline's abstraction layers instead.
*
* This approach uses TypeScript's module augmentation to add deprecation warnings
* and make them discoverable in IntelliSense by marking them as @internal.
*
* Exemptions: Files in src/hosts/vscode/ and standalone/runtime-files/ directories
* are allowed to use these APIs directly as they provide the abstraction layer.
*
* To ensure error on usage, update src/dev/grit/vscode-api.grit to include the banned apis.
*/
declare module "vscode" {
export interface ExtensionContext {
/**
* @deprecated Use gRPC service clients instead of vscode.postMessage().
* Example: AccountServiceClient.methodName(RequestType.create({...})) instead of vscode.postMessage({type: '...'}).
* This provides better type safety and consistent communication patterns.
* @internal
*/
postMessage?: (message: any) => Thenable<boolean>
/**
* @deprecated Use CacheService.getGlobalStateKey() instead of context.globalState.get().
* Example: cacheService.getGlobalStateKey('myKey') instead of context.globalState.get('myKey').
* This provides better performance with in-memory caching and consistent state management.
* @internal
*/
readonly globalState: {
/**
* @deprecated Use CacheService.getGlobalStateKey() instead of context.globalState.get().
* Example: cacheService.getGlobalStateKey('myKey') instead of context.globalState.get('myKey').
* This provides better performance with in-memory caching and consistent state management.
* @internal
*/
get<T>(key: string): T | undefined
/**
* @deprecated Use CacheService.setGlobalState() instead of context.globalState.update().
* Example: cacheService.setGlobalState('myKey', value) instead of context.globalState.update('myKey', value).
* This provides better performance with in-memory caching and consistent state management.
* @internal
*/
update(key: string, value: any): Thenable<void>
}
/**
* @deprecated Use CacheService.getWorkspaceStateKey() instead of context.workspaceState.get().
* Example: cacheService.getWorkspaceStateKey('myKey') instead of context.workspaceState.get('myKey').
* This provides better performance with in-memory caching and consistent state management.
* @internal
*/
readonly workspaceState: {
/**
* @deprecated Use CacheService.getWorkspaceStateKey() instead of context.workspaceState.get().
* Example: cacheService.getWorkspaceStateKey('myKey') instead of context.workspaceState.get('myKey').
* This provides better performance with in-memory caching and consistent state management.
* @internal
*/
get<T>(key: string): T | undefined
/**
* @deprecated Use CacheService.setWorkspaceState() instead of context.workspaceState.update().
* Example: cacheService.setWorkspaceState('myKey', value) instead of context.workspaceState.update('myKey', value).
* This provides better performance with in-memory caching and consistent state management.
* @internal
*/
update(key: string, value: any): Thenable<void>
}
/**
* @deprecated Use CacheService.getSecretKey() and CacheService.setSecret() instead of context.secrets.
* Example: cacheService.getSecretKey('apiKey') instead of context.secrets.get('apiKey').
* This provides better performance with in-memory caching and consistent state management.
* @internal
*/
readonly secrets: {
/**
* @deprecated Use CacheService.getSecretKey() instead of context.secrets.get().
* Example: cacheService.getSecretKey('apiKey') instead of context.secrets.get('apiKey').
* This provides better performance with in-memory caching and consistent state management.
* @internal
*/
get(key: string): Thenable<string | undefined>
/**
* @deprecated Use CacheService.setSecret() instead of context.secrets.store().
* Example: cacheService.setSecret('apiKey', value) instead of context.secrets.store('apiKey', value).
* This provides better performance with in-memory caching and consistent state management.
* @internal
*/
store(key: string, value: string): Thenable<void>
/**
* @deprecated Use CacheService.setSecret() with undefined instead of context.secrets.delete().
* Example: cacheService.setSecret('apiKey', undefined) instead of context.secrets.delete('apiKey').
* This provides better performance with in-memory caching and consistent state management.
* @internal
*/
delete(key: string): Thenable<void>
}
}
export namespace workspace {
export namespace fs {
/**
* @deprecated Use utilities in @/utils/fs instead of vscode.workspace.fs.stat.
* Example: import { isDirectory } from '@/utils/fs' or use the file system methods from the host bridge provider.
* This provides consistent file system access across VSCode and standalone environments.
* @internal
*/
export function stat(uri: Uri): Thenable<FileStat>
/**
* @deprecated Use utilities in @/utils/fs instead of vscode.workspace.fs.writeFile.
* Example: import { writeFile } from '@/utils/fs' or use the file system methods from the host bridge provider.
* This provides consistent file system access across VSCode and standalone environments.
* @internal
*/
export function writeFile(uri: Uri, content: Uint8Array): Thenable<void>
}
/**
* @deprecated Use HostProvider.workspace.getWorkspacePaths({}) instead of vscode.workspace.workspaceFolders.
* This provides a consistent abstraction across VSCode and standalone environments.
* @internal
*/
export const workspaceFolders: readonly WorkspaceFolder[] | undefined
/**
* @deprecated Use path utilities from @/utils/path instead of vscode.workspace.asRelativePath.
* This provides consistent path handling across different environments.
* @internal
*/
export function asRelativePath(pathOrUri: string | Uri, includeWorkspaceFolder?: boolean): string
/**
* @deprecated Use path utilities from @/utils/path instead of vscode.workspace.getWorkspaceFolder.
* This provides consistent path handling across different environments.
* @internal
*/
export function getWorkspaceFolder(uri: Uri): WorkspaceFolder | undefined
/**
* @deprecated Use the host bridge instead of vscode.workspace.applyEdit.
* This provides a consistent abstraction across VSCode and standalone environments.
* @internal
*/
export function applyEdit(edit: WorkspaceEdit): Thenable<boolean>
/**
* @deprecated Use a native JavaScript API instead of vscode.workspace.findFiles.
* This provides a consistent abstraction across VSCode and standalone environments.
* @internal
*/
export function findFiles(
include: GlobPattern,
exclude?: GlobPattern | null,
maxResults?: number,
token?: CancellationToken,
): Thenable<Uri[]>
}
export namespace env {
/**
* @deprecated Use utilities in @/utils instead of vscode.env.openExternal.
* This provides a consistent abstraction across VSCode and standalone environments.
* @internal
*/
export function openExternal(target: Uri): Thenable<boolean>
}
export namespace window {
/**
* @deprecated Use the host bridge instead of vscode.window.showTextDocument.
* This provides a consistent abstraction across VSCode and standalone environments.
* @internal
*/
export function showTextDocument(
document: TextDocument | Uri,
column?: ViewColumn,
preserveFocus?: boolean,
): Thenable<TextEditor>
/**
* @deprecated Use HostProvider.window.showMessage instead of vscode.window.showWarningMessage.
* This provides a consistent abstraction across VSCode and standalone environments.
* @internal
*/
export function showWarningMessage(message: string, ...items: string[]): Thenable<string | undefined>
/**
* @deprecated Use HostProvider.window.showMessage instead of vscode.window.showErrorMessage.
* This provides a consistent abstraction across VSCode and standalone environments.
* @internal
*/
export function showErrorMessage(message: string, ...items: string[]): Thenable<string | undefined>
/**
* @deprecated Use HostProvider.window.showMessage instead of vscode.window.showInformationMessage.
* This provides a consistent abstraction across VSCode and standalone environments.
* @internal
*/
export function showInformationMessage(message: string, ...items: string[]): Thenable<string | undefined>
/**
* @deprecated Use HostProvider.window.showMessage instead of vscode.window.showOpenDialog.
* This provides a consistent abstraction across VSCode and standalone environments.
* @internal
*/
export function showOpenDialog(options?: OpenDialogOptions): Thenable<Uri[] | undefined>
/**
* @deprecated Use the host bridge instead of vscode.window.showInputBox.
* This provides a consistent abstraction across VSCode and standalone environments.
* @internal
*/
export function showInputBox(options?: InputBoxOptions, token?: CancellationToken): Thenable<string | undefined>
/**
* @deprecated Use the host bridge instead of vscode.window.onDidChangeActiveTextEditor.
* This provides a consistent abstraction across VSCode and standalone environments.
* @internal
*/
export const onDidChangeActiveTextEditor: Event<TextEditor | undefined>
}
export interface Webview {
/**
* @deprecated Use gRPC service clients instead of webview.postMessage().
* Example: AccountServiceClient.methodName(RequestType.create({...})) instead of webview.postMessage({type: '...'}).
* This provides better type safety and consistent communication patterns.
* @internal
*/
postMessage(message: any): Thenable<boolean>
}
export interface WebviewPanel {
/**
* Access to the webview belonging to this panel.
* Note: webview.postMessage is deprecated - use gRPC service clients instead.
*/
readonly webview: Webview
}
}
@@ -1,8 +1,7 @@
/* eslint-disable eslint-rules/no-direct-vscode-api */
import { describe, it, beforeEach, afterEach } from "mocha"
import { strict as assert } from "assert"
import * as vscode from "vscode"
import { afterEach, beforeEach, describe, it } from "mocha"
import pWaitFor from "p-wait-for"
import * as vscode from "vscode"
import { getOpenTabs } from "@/hosts/vscode/hostbridge/window/getOpenTabs"
import { GetOpenTabsRequest } from "@/shared/proto/host/window"
@@ -1,6 +1,5 @@
/* eslint-disable eslint-rules/no-direct-vscode-api */
import { describe, it, beforeEach, afterEach } from "mocha"
import { strict as assert } from "assert"
import { afterEach, beforeEach, describe, it } from "mocha"
import * as vscode from "vscode"
import { getVisibleTabs } from "@/hosts/vscode/hostbridge/window/getVisibleTabs"
import { GetVisibleTabsRequest } from "@/shared/proto/host/window"
-38
View File
@@ -1,38 +0,0 @@
{
"root": true,
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module"
},
"plugins": ["@typescript-eslint", "react-hooks", "react-refresh", "eslint-rules"],
"env": {
"browser": true,
"es2020": true
},
"rules": {
"react-hooks/rules-of-hooks": "error",
// "react-refresh/only-export-components": [
// "warn",
// {
// "allowConstantExport": true
// }
// ],
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-empty-object-type": "off",
"no-case-declarations": "off",
"prefer-const": "off",
"no-extra-semi": "off",
"eslint-rules/no-direct-vscode-api": "warn",
"no-restricted-syntax": [
"error",
{
"selector": "VariableDeclarator[id.type=\"ObjectPattern\"][init.object.name=\"process\"][init.property.name=\"env\"]",
"message": "Use process.env.VARIABLE_NAME directly instead of destructuring"
}
]
},
"ignorePatterns": ["build"]
}
+2 -1353
View File
File diff suppressed because it is too large. Load diff
+1 -7
View File
@@ -8,7 +8,7 @@
"build": "tsc -b && vite build",
"build:test": "tsc -b && vite build -- --dev-build",
"preview": "vite preview",
"lint": "eslint . --ext .ts,.tsx",
"lint": "biome lint --changed --no-errors-on-unmatched",
"test": "vitest run",
"test:watch": "vitest dev",
"test:coverage": "vitest run --coverage",
@@ -45,7 +45,6 @@
"uuid": "^9.0.1"
},
"devDependencies": {
"@eslint/js": "^9.17.0",
"@tailwindcss/vite": "^4.1.4",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.2.0",
@@ -59,16 +58,11 @@
"@types/vscode-webview": "^1.57.5",
"@vitejs/plugin-react-swc": "^3.5.0",
"@vitest/coverage-v8": "^3.0.9",
"eslint": "^8.57.0",
"eslint-plugin-eslint-rules": "file:../eslint-rules",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.16",
"globals": "^15.14.0",
"jsdom": "^26.0.0",
"react-devtools": "^6.1.2",
"tailwindcss": "^4.1.5",
"typescript": "^5.7.3",
"typescript-eslint": "^8.18.2",
"vite": "^6.3.4",
"vitest": "^3.0.5"
},