[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,90 +1,355 @@
|
||||
---
|
||||
id: wiki-2026-0508-custom-eslint-rules-development
|
||||
id: wiki-2026-0508-custom-eslint-rules-dev
|
||||
title: Custom ESLint Rules Development
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [ESLint-001]
|
||||
aliases: [custom ESLint, AST rule, eslint plugin, ast visitor, autofix, semgrep alternative]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [static-Analysis, JavaScript, devtools, dx]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [eslint, ast, static-analysis, code-quality, custom-rule, plugin, autofix, semgrep]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: JavaScript / TypeScript
|
||||
framework: ESLint / Semgrep / typescript-eslint
|
||||
---
|
||||
|
||||
# Custom ESLint Rules Development (사용자 정의 ESLint 규칙 개발)
|
||||
# Custom ESLint Rules
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "팀의 코드 품질을 자동화된 문지기로 지켜라" — 단순한 문법 검사를 넘어, 프로젝트 특유의 안티 패턴이나 아키텍처 규칙을 AST(추상 구문 트리) 분석을 통해 실시간으로 강제하는 기법.
|
||||
## 매 한 줄
|
||||
> **"매 team-specific rule 의 자동 enforcement"**. 매 AST visitor pattern + 매 fixer API. 매 architectural rule (no domain → infra), 매 anti-pattern (deprecated API), 매 convention (naming). 매 modern alternative: Semgrep (multi-language).
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** 소스코드를 트리 구조(AST)로 변환한 뒤, 특정 노드 방문 시(Visitor Pattern) 규칙 위반 여부를 검사하고 수정안(Fixer)을 제안하는 정적 분석 패턴.
|
||||
- **세부 내용:**
|
||||
- **AST Exploration:** `espree` 파서를 사용하여 코드를 노드 단위(VariableDeclaration, CallExpression 등)로 분해.
|
||||
- **Rule Definition:** `meta`(메타데이터)와 `create`(실제 로직) 함수를 정의하여 규칙 생성.
|
||||
- **Context Report:** 규칙 위반 시 에러 메시지와 위치를 보고하여 개발자에게 알림.
|
||||
- **Auto-fixing:** `fixer` API를 사용하여 위반된 코드를 올바른 형태로 자동 변환하는 로직 구현.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 단순 정규표현식 기반 검사에서, 코드의 의미적 구조를 이해하는 AST 기반 분석으로 정착.
|
||||
- **정책 변화:** Antigravity 프로젝트에서는 AI 에이전트가 작성하는 코드의 일관성을 위해 전용 ESLint 플러그인을 개발하여 운영 중.
|
||||
### 매 ESLint architecture
|
||||
1. **Parser** (espree, @typescript-eslint/parser): 매 source → 매 AST.
|
||||
2. **Rule**: 매 visit AST node + 매 report.
|
||||
3. **Fixer**: 매 auto-correct.
|
||||
4. **Config**: 매 enable / disable.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Parent:** 10_Wiki/💡 Topics/AI
|
||||
- **Related:** Static-Analysis, AST, Developer-Experience
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/[[Custom-ESLint-Rules|Custom-ESLint-Rules]]-Development.md
|
||||
### 매 AST node type
|
||||
- **Program**: 매 root.
|
||||
- **VariableDeclaration**, **FunctionDeclaration**.
|
||||
- **CallExpression**, **MemberExpression**.
|
||||
- **ArrowFunctionExpression**, **ObjectExpression**, **ArrayExpression**.
|
||||
- **TSInterfaceDeclaration**, **TSTypeAliasDeclaration** (TS).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 use case
|
||||
1. **Architectural**: domain → infrastructure 의 forbid.
|
||||
2. **Convention**: naming, file structure.
|
||||
3. **Deprecation**: 매 old API 의 detect.
|
||||
4. **Security**: dangerous pattern (eval, dangerouslySetInnerHTML).
|
||||
5. **Performance**: anti-pattern (e.g., unnecessary re-render).
|
||||
6. **Domain-specific**: business rule.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 selector syntax (Esquery)
|
||||
- `Identifier[name="foo"]`: 매 specific name.
|
||||
- `CallExpression > MemberExpression`: 매 chain.
|
||||
- `:not(...)`: 매 exclusion.
|
||||
- `[callee.name="alert"]`: 매 attribute match.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### 매 modern alternative: Semgrep
|
||||
- 매 multi-language (Python, Go, Java, Rust, ...).
|
||||
- 매 pattern-based (more readable).
|
||||
- 매 ESLint custom 보다 매 fast write.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### 매 LLM-aided rule generation
|
||||
- 매 plain English → 매 ESLint rule code.
|
||||
- 매 example-based.
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
## 💻 패턴
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### Basic ESLint rule
|
||||
```js
|
||||
// eslint-rule-no-console-log.js
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description: 'Disallow console.log calls',
|
||||
recommended: true,
|
||||
},
|
||||
fixable: 'code',
|
||||
schema: [],
|
||||
messages: {
|
||||
noConsoleLog: 'Avoid console.log in production. Use logger.',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
return {
|
||||
CallExpression(node) {
|
||||
if (
|
||||
node.callee.type === 'MemberExpression' &&
|
||||
node.callee.object.name === 'console' &&
|
||||
node.callee.property.name === 'log'
|
||||
) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'noConsoleLog',
|
||||
fix(fixer) {
|
||||
// 매 auto-fix: 매 logger.info 의 replace
|
||||
return fixer.replaceText(node.callee, 'logger.info');
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Plugin structure
|
||||
```
|
||||
my-eslint-plugin/
|
||||
├── package.json
|
||||
├── lib/
|
||||
│ ├── index.js # 매 plugin entry
|
||||
│ └── rules/
|
||||
│ ├── no-console-log.js
|
||||
│ └── enforce-domain-isolation.js
|
||||
└── tests/
|
||||
└── no-console-log.test.js
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
```js
|
||||
// lib/index.js
|
||||
module.exports = {
|
||||
rules: {
|
||||
'no-console-log': require('./rules/no-console-log'),
|
||||
'enforce-domain-isolation': require('./rules/enforce-domain-isolation'),
|
||||
},
|
||||
configs: {
|
||||
recommended: {
|
||||
plugins: ['@my-org'],
|
||||
rules: {
|
||||
'@my-org/no-console-log': 'error',
|
||||
'@my-org/enforce-domain-isolation': 'error',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Architectural rule (Clean Architecture)
|
||||
```js
|
||||
// 매 src/domain/* 의 매 src/infrastructure/* 의 import 의 forbid
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
messages: {
|
||||
noInfraInDomain: 'domain layer must not import from infrastructure',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
return {
|
||||
ImportDeclaration(node) {
|
||||
const filename = context.getFilename();
|
||||
if (!filename.includes('/domain/')) return;
|
||||
|
||||
const importPath = node.source.value;
|
||||
if (importPath.includes('/infrastructure/')) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'noInfraInDomain',
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Test (RuleTester)
|
||||
```js
|
||||
const { RuleTester } = require('eslint');
|
||||
const rule = require('./no-console-log');
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
const tester = new RuleTester();
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
tester.run('no-console-log', rule, {
|
||||
valid: [
|
||||
'logger.info("hi");',
|
||||
'console.error("err");',
|
||||
],
|
||||
invalid: [
|
||||
{
|
||||
code: 'console.log("hi");',
|
||||
output: 'logger.info("hi");',
|
||||
errors: [{ messageId: 'noConsoleLog' }],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### TypeScript-aware rule
|
||||
```ts
|
||||
import { TSESTree, ESLintUtils } from '@typescript-eslint/utils';
|
||||
|
||||
const createRule = ESLintUtils.RuleCreator(name => `https://docs.example.com/${name}`);
|
||||
|
||||
export default createRule({
|
||||
name: 'no-any-type',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: { description: 'Forbid `any` type', recommended: true },
|
||||
schema: [],
|
||||
messages: { noAny: 'Avoid `any` — use `unknown` or specific type.' },
|
||||
},
|
||||
defaultOptions: [],
|
||||
create(context) {
|
||||
return {
|
||||
TSAnyKeyword(node) {
|
||||
context.report({ node, messageId: 'noAny' });
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Selector-based (esquery)
|
||||
```js
|
||||
// 매 매 React.useState() 의 매 first arg 의 type check
|
||||
module.exports = {
|
||||
create(context) {
|
||||
return {
|
||||
'CallExpression[callee.object.name="React"][callee.property.name="useState"]'(node) {
|
||||
const arg = node.arguments[0];
|
||||
if (!arg) {
|
||||
context.report({ node, message: 'useState requires initial value' });
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### Semgrep alternative
|
||||
```yaml
|
||||
# .semgrep/no-console-log.yml
|
||||
rules:
|
||||
- id: no-console-log
|
||||
pattern: console.log(...)
|
||||
message: 'Avoid console.log in production'
|
||||
severity: WARNING
|
||||
languages: [javascript, typescript]
|
||||
fix: logger.info(...)
|
||||
|
||||
- id: domain-no-infra
|
||||
patterns:
|
||||
- pattern: import $X from "$Y"
|
||||
- metavariable-pattern:
|
||||
metavariable: $Y
|
||||
pattern: '*infrastructure*'
|
||||
paths:
|
||||
include:
|
||||
- 'src/domain/**'
|
||||
message: 'domain must not import infrastructure'
|
||||
severity: ERROR
|
||||
languages: [typescript]
|
||||
```
|
||||
|
||||
### LLM-generated rule
|
||||
```python
|
||||
def generate_eslint_rule(description, examples):
|
||||
prompt = f"""Generate an ESLint custom rule.
|
||||
|
||||
Description: {description}
|
||||
|
||||
Bad examples:
|
||||
{format_examples(examples['bad'])}
|
||||
|
||||
Good examples (allowed):
|
||||
{format_examples(examples['good'])}
|
||||
|
||||
Output: complete eslint rule .js file with autofix where possible.
|
||||
Use selector syntax. Include test cases."""
|
||||
return llm.generate(prompt)
|
||||
```
|
||||
|
||||
### Apply via flat config (ESLint 9+)
|
||||
```js
|
||||
// eslint.config.js
|
||||
import myPlugin from '@my-org/eslint-plugin';
|
||||
|
||||
export default [
|
||||
{
|
||||
plugins: { '@my-org': myPlugin },
|
||||
rules: {
|
||||
'@my-org/no-console-log': 'error',
|
||||
'@my-org/enforce-domain-isolation': 'error',
|
||||
},
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
### Performance: visitor reuse
|
||||
```js
|
||||
// 매 ❌ Bad — 매 매 node 마다 fileName check
|
||||
create(context) {
|
||||
return {
|
||||
'ImportDeclaration'(node) {
|
||||
const fn = context.getFilename();
|
||||
if (!fn.includes('/domain/')) return;
|
||||
// ...
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 매 ✅ Better — 매 file-level cache
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
if (!filename.includes('/domain/')) return {}; // 매 visitor 의 skip entire
|
||||
|
||||
return {
|
||||
'ImportDeclaration'(node) { /* ... */ },
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 결정 기준
|
||||
| 상황 | Tool |
|
||||
|---|---|
|
||||
| Single language (JS/TS) | ESLint custom |
|
||||
| Multi-language | Semgrep |
|
||||
| Cross-cutting (security) | CodeQL / Semgrep |
|
||||
| Architectural | dependency-cruiser |
|
||||
| Quick + readable pattern | Semgrep |
|
||||
| AST manipulation needed | ESLint with autofix |
|
||||
| Type-aware | typescript-eslint |
|
||||
|
||||
**기본값**: 매 single-lang JS/TS = ESLint. 매 multi-lang = Semgrep.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Static-Analysis-Linting]] · [[Code-Quality]]
|
||||
- 변형: [[ESLint]] · [[Semgrep]] · [[CodeQL]] · [[dependency-cruiser]]
|
||||
- 응용: [[AST]] · [[Code_Smells]] · [[CI_CD 파이프라인 및 IDE 통합 보안]] · [[Architecture-Anti-Patterns]]
|
||||
- Adjacent: [[Abstract_Syntax_Tree]] · [[Clean-Code-Principles]] · [[Quality_Code_Review_Modern]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 team-wide convention enforcement. 매 architectural rule. 매 AI-generated code 의 normalize.
|
||||
**언제 X**: 매 single-time check (just grep). 매 dynamic / runtime issue.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **No test (RuleTester)**: 매 rule 의 buggy.
|
||||
- **No fixer**: 매 manual burden.
|
||||
- **Slow rule**: 매 매 file performance ↓.
|
||||
- **Over-broad selector**: 매 false positive.
|
||||
- **No documentation URL**: 매 dev 의 confusion.
|
||||
- **Custom rule for what built-in exists**: 매 wheel reinvent.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (ESLint docs, typescript-eslint, Semgrep docs).
|
||||
- 신뢰도 A.
|
||||
- Related: [[Static-Analysis-Linting]] · [[Code_Smells]] · [[Architecture-Anti-Patterns]] · [[CI_CD 파이프라인 및 IDE 통합 보안]] · [[Abstract_Syntax_Tree]].
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — AST + 매 basic / architectural / TS / Semgrep / LLM-gen code |
|
||||
|
||||
Reference in New Issue
Block a user