designsnitch 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ko.md +79 -19
- package/README.md +79 -19
- package/package.json +1 -1
- package/skills/designsnitch-check/SKILL.md +32 -8
- package/skills/designsnitch-eslint/SKILL.md +2 -0
- package/skills/designsnitch-palette/SKILL.md +8 -6
- package/skills/designsnitch-setup/SKILL.md +13 -1
- package/src/check.js +127 -19
- package/src/cli.js +3 -2
- package/src/colors.js +4 -2
- package/src/config.js +25 -3
- package/src/core/classes.js +12 -0
- package/src/core/css.js +4 -3
- package/src/core/tokens.js +40 -1
- package/src/format.js +5 -3
- package/src/hook.js +1 -5
- package/src/messages.js +28 -4
- package/src/rules/color-unknown.js +6 -7
- package/src/rules/color-use-token.js +23 -12
- package/src/rules/load-tokens.js +15 -9
- package/src/rules/unchecked-hex.js +25 -0
- package/src/rules/use-ds-component.js +2 -2
- package/src/rules/visit-style.js +64 -0
package/src/check.js
CHANGED
|
@@ -1,15 +1,21 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { replacementNames } from "./config.js";
|
|
3
|
+
import { replacementNames, tokenSettings } from "./config.js";
|
|
4
|
+
import { findArbitraryColors, tokenToClass } from "./core/classes.js";
|
|
4
5
|
import { normalizeHex } from "./core/color.js";
|
|
5
6
|
import { findCssColors } from "./core/css.js";
|
|
7
|
+
import { cssColorPrefixes, recommendColorCandidate, selectColorTokens, utilityColorPrefixes } from "./core/tokens.js";
|
|
6
8
|
import { createEngine } from "./engine.js";
|
|
7
9
|
import { splitPaths } from "./files.js";
|
|
8
10
|
import plugin from "./index.js";
|
|
9
11
|
import { messages, resolveLang } from "./messages.js";
|
|
10
12
|
import { loadTokens } from "./rules/load-tokens.js";
|
|
13
|
+
import uncheckedHex from "./rules/unchecked-hex.js";
|
|
11
14
|
|
|
12
15
|
const RULE_PREFIX = "designsnitch/";
|
|
16
|
+
const UNCHECKED_RULE = "designsnitch-internal/unchecked-hex";
|
|
17
|
+
const internalPlugin = { rules: { "unchecked-hex": uncheckedHex } };
|
|
18
|
+
const MAX_DECISION_LOCATIONS = 5;
|
|
13
19
|
|
|
14
20
|
/**
|
|
15
21
|
* @typedef {object} Violation
|
|
@@ -23,12 +29,26 @@ const RULE_PREFIX = "designsnitch/";
|
|
|
23
29
|
* @property {string} message
|
|
24
30
|
* @property {string} found 위반한 코드 조각 (클래스나 태그 이름)
|
|
25
31
|
* @property {string[]} candidates 대신 쓸 클래스나 컴포넌트. 없으면 빈 배열
|
|
32
|
+
* @property {string | null} recommended 바로 바꿀 후보 또는 역할에 맞는 유일한 후보
|
|
26
33
|
* @property {"replace" | "ask" | "repair"} action 이 위반을 어떻게 다룰지.
|
|
27
34
|
* replace: found 를 candidates 의 값으로 바꿀 수 있다 (교체가 안전하고 후보가 하나뿐인 오류)
|
|
28
35
|
* ask: 사람이 정해야 한다 (교체가 확실하지 않거나 후보가 하나가 아닌 경우)
|
|
29
36
|
* repair: 파일을 읽지 못했다. 문법 오류부터 고쳐야 한다
|
|
30
37
|
*/
|
|
31
38
|
|
|
39
|
+
/**
|
|
40
|
+
* @typedef {object} Decision
|
|
41
|
+
* @property {string} id
|
|
42
|
+
* @property {string} rule
|
|
43
|
+
* @property {string} subject 정규화한 색 또는 꺾쇠로 감싼 태그 이름
|
|
44
|
+
* @property {number} uses 위반 횟수
|
|
45
|
+
* @property {number} files 위반이 있는 파일 수
|
|
46
|
+
* @property {Pick<Violation, "file" | "line" | "column">[]} locations 위반 위치 최대 다섯 곳
|
|
47
|
+
* @property {string[]} candidates
|
|
48
|
+
* @property {string | null} recommended 각 위치에서 추천이 같을 때 그 후보
|
|
49
|
+
* @property {("multiple-candidates" | "no-token" | "themed-token" | "dynamic-props")[]} reasons
|
|
50
|
+
*/
|
|
51
|
+
|
|
32
52
|
/**
|
|
33
53
|
* 프로젝트를 검사한다. 프로젝트의 ESLint 설정은 쓰지 않고 designsnitch 규칙만 실행한다.
|
|
34
54
|
* @param {object} options
|
|
@@ -36,24 +56,27 @@ const RULE_PREFIX = "designsnitch/";
|
|
|
36
56
|
* @param {ReturnType<typeof import("./config.js").loadConfig>} options.config
|
|
37
57
|
* @param {string[]} [options.paths] 검사할 파일이나 디렉터리 (cwd 기준)
|
|
38
58
|
* @param {"en" | "ko"} [options.lang] 문장의 언어. 없으면 설정의 lang, 환경 변수, 영어 순으로 정한다
|
|
59
|
+
* @param {string} [options.sourceCwd] 임시 복사본을 검사할 때 원본 프로젝트 디렉터리
|
|
39
60
|
* @returns {Promise<{
|
|
40
61
|
* designSystem: { colorTokens: number, components: number, replacedTags: number },
|
|
41
62
|
* problems: string[],
|
|
42
63
|
* next: string[],
|
|
43
64
|
* summary: { files: number, errors: number, warnings: number },
|
|
44
65
|
* violations: Violation[],
|
|
66
|
+
* decisions: Decision[],
|
|
45
67
|
* }>} designSystem 은 설정에서 읽어 낸 것의 개수, problems 는 결과를 믿기 어렵게 만드는 설정 문제,
|
|
46
68
|
* next 는 이 결과를 받은 에이전트가 순서대로 할 일
|
|
47
69
|
*/
|
|
48
|
-
export async function check({ cwd, config, paths = ["."], lang }) {
|
|
70
|
+
export async function check({ cwd, config, paths = ["."], lang, sourceCwd = cwd }) {
|
|
49
71
|
lang = resolveLang(lang, config.lang);
|
|
50
72
|
const m = messages(lang);
|
|
73
|
+
const root = path.resolve(sourceCwd, config.root ?? ".");
|
|
51
74
|
// 규칙도 같은 언어를 쓰도록 설정에 실어 보낸다.
|
|
52
|
-
const settings = { designsnitch: { ...config, lang } };
|
|
75
|
+
const settings = { designsnitch: { ...config, root, lang } };
|
|
53
76
|
// 설정에 문제가 있으면 파일을 검사하기 전에 알린다.
|
|
54
77
|
const tokens = loadTokens(settings, cwd);
|
|
55
78
|
if (config.components) {
|
|
56
|
-
const dir = path.resolve(
|
|
79
|
+
const dir = path.resolve(root, config.components.path);
|
|
57
80
|
if (!fs.existsSync(dir)) {
|
|
58
81
|
throw new Error(m.componentsDirMissing({ dir }));
|
|
59
82
|
}
|
|
@@ -61,49 +84,73 @@ export async function check({ cwd, config, paths = ["."], lang }) {
|
|
|
61
84
|
const designSystem = describeDesignSystem(tokens, config);
|
|
62
85
|
const problems = [];
|
|
63
86
|
if (designSystem.colorTokens === 0) {
|
|
64
|
-
problems.push(m.noColorTokens({ tokens: config.tokens }));
|
|
87
|
+
problems.push(m.noColorTokens({ tokens: tokenSettings(config.tokens).file }));
|
|
65
88
|
}
|
|
66
89
|
|
|
67
90
|
const { scriptPaths, cssFiles } = splitPaths(cwd, paths);
|
|
68
91
|
|
|
69
92
|
// JS, TS 는 ESLint 로 규칙을 실행하고, CSS 는 직접 읽는다.
|
|
70
|
-
const
|
|
93
|
+
const recommended = plugin.configs.recommended;
|
|
94
|
+
const eslint = createEngine({
|
|
95
|
+
cwd,
|
|
96
|
+
config: {
|
|
97
|
+
plugins: { ...recommended.plugins, "designsnitch-internal": internalPlugin },
|
|
98
|
+
rules: { ...recommended.rules, [UNCHECKED_RULE]: "warn" },
|
|
99
|
+
settings,
|
|
100
|
+
},
|
|
101
|
+
});
|
|
71
102
|
const results = scriptPaths.length > 0 ? await eslint.lintFiles(scriptPaths) : [];
|
|
103
|
+
// 검사하지 못한 hex 색은 위반이 아니라 개수로만 알린다. 놓친 것이 있다는 사실을 숨기지 않기 위해서다.
|
|
104
|
+
const uncheckedFiles = results
|
|
105
|
+
.map((result) => result.messages.filter((message) => message.ruleId === UNCHECKED_RULE).length)
|
|
106
|
+
.filter((n) => n > 0);
|
|
107
|
+
const unchecked = { hexColors: uncheckedFiles.reduce((a, b) => a + b, 0), files: uncheckedFiles.length };
|
|
72
108
|
const scriptViolations = results.flatMap((result) => {
|
|
73
109
|
const file = path.relative(cwd, result.filePath).split(path.sep).join("/");
|
|
74
110
|
return result.messages
|
|
75
111
|
.filter(isOurs)
|
|
76
112
|
.map((message) => toViolation(file, result.source, message, config));
|
|
77
113
|
});
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
114
|
+
const tokenFile = path.resolve(root, tokenSettings(config.tokens).file);
|
|
115
|
+
const cssViolations = cssFiles.flatMap((file) => {
|
|
116
|
+
const source = fs.readFileSync(path.resolve(cwd, file), "utf8");
|
|
117
|
+
const skipCustomProperties = path.resolve(sourceCwd, file) === tokenFile;
|
|
118
|
+
return checkCss(file, source, tokens, m, { skipCustomProperties });
|
|
119
|
+
});
|
|
81
120
|
|
|
82
|
-
const
|
|
121
|
+
const findings = [...scriptViolations, ...cssViolations]
|
|
83
122
|
.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column)
|
|
84
|
-
.map((
|
|
123
|
+
.map((finding) => {
|
|
124
|
+
const action = actionFor(finding, finding.messageId);
|
|
125
|
+
const recommended = action === "replace" ? finding.candidates[0] : finding.recommended ?? null;
|
|
126
|
+
return { ...finding, action, recommended };
|
|
127
|
+
});
|
|
128
|
+
const violations = findings.map(({ messageId, ...violation }) => violation);
|
|
129
|
+
const decisions = groupDecisions(findings);
|
|
85
130
|
|
|
86
131
|
return {
|
|
87
132
|
designSystem,
|
|
88
133
|
problems,
|
|
89
|
-
next: nextSteps(designSystem, violations, lang),
|
|
134
|
+
next: nextSteps(designSystem, violations, lang, decisions),
|
|
90
135
|
summary: {
|
|
91
136
|
files: results.length + cssFiles.length,
|
|
92
137
|
errors: violations.filter((v) => v.severity === "error").length,
|
|
93
138
|
warnings: violations.filter((v) => v.severity === "warning").length,
|
|
94
139
|
},
|
|
95
140
|
violations,
|
|
141
|
+
decisions,
|
|
142
|
+
unchecked,
|
|
96
143
|
};
|
|
97
144
|
}
|
|
98
145
|
|
|
99
146
|
/**
|
|
100
147
|
* CSS 파일 하나의 hex 색을 토큰과 비교한다. 대체 후보는 var(--토큰) 이다.
|
|
101
|
-
* @returns {(Omit<Violation, "action"> & { messageId?: string })[]}
|
|
148
|
+
* @returns {(Omit<Violation, "action" | "recommended"> & { recommended?: string | null, messageId?: string })[]}
|
|
102
149
|
*/
|
|
103
|
-
function checkCss(file, source, tokens, m) {
|
|
150
|
+
function checkCss(file, source, tokens, m, options) {
|
|
104
151
|
let colors;
|
|
105
152
|
try {
|
|
106
|
-
colors = findCssColors(source);
|
|
153
|
+
colors = findCssColors(source, options);
|
|
107
154
|
} catch (error) {
|
|
108
155
|
const at = { line: error.line ?? 1, column: error.column ?? 1 };
|
|
109
156
|
return [
|
|
@@ -124,8 +171,10 @@ function checkCss(file, source, tokens, m) {
|
|
|
124
171
|
return colors
|
|
125
172
|
.filter((color) => !color.disabled)
|
|
126
173
|
.map(({ value, prop, disabled, ...location }) => {
|
|
127
|
-
const
|
|
174
|
+
const prefixes = cssColorPrefixes(prop);
|
|
175
|
+
const tokenNames = selectColorTokens(tokens.colors.get(normalizeHex(value)) ?? [], tokens.prefer, prefixes);
|
|
128
176
|
const candidates = tokenNames.map((name) => `var(${name})`);
|
|
177
|
+
const recommendedToken = recommendColorCandidate(tokenNames, prefixes);
|
|
129
178
|
const messageId = tokenNames.some((name) => tokens.themed.has(name)) ? "useTokenThemed" : "useToken";
|
|
130
179
|
return {
|
|
131
180
|
file,
|
|
@@ -148,6 +197,7 @@ function checkCss(file, source, tokens, m) {
|
|
|
148
197
|
}),
|
|
149
198
|
found: value,
|
|
150
199
|
candidates,
|
|
200
|
+
recommended: recommendedToken ? `var(${recommendedToken})` : null,
|
|
151
201
|
};
|
|
152
202
|
});
|
|
153
203
|
}
|
|
@@ -158,14 +208,61 @@ function actionFor({ rule, severity, candidates }, messageId) {
|
|
|
158
208
|
return severity === "error" && candidates.length === 1 ? "replace" : "ask";
|
|
159
209
|
}
|
|
160
210
|
|
|
211
|
+
function decisionSubject({ rule, found }) {
|
|
212
|
+
if (rule === "use-ds-component") return `<${found}>`;
|
|
213
|
+
const value = found.startsWith("#") ? found : findArbitraryColors(found)[0]?.value;
|
|
214
|
+
if (!value) return found;
|
|
215
|
+
const hex = value.toLowerCase();
|
|
216
|
+
return normalizeHex(hex) ?? (hex.length === 5 ? hex.replace(/[0-9a-f]/g, "$&$&") : hex);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* @param {(Violation & { messageId?: string })[]} violations
|
|
221
|
+
* @returns {Decision[]}
|
|
222
|
+
*/
|
|
223
|
+
function groupDecisions(violations) {
|
|
224
|
+
/** @type {Map<string, Omit<Decision, "id" | "files" | "reasons"> & { files: Set<string>, reasons: Set<Decision["reasons"][number]> }>} */
|
|
225
|
+
const byQuestion = new Map();
|
|
226
|
+
for (const violation of violations) {
|
|
227
|
+
if (violation.action !== "ask") continue;
|
|
228
|
+
const { rule, candidates, recommended, messageId, file, line, column } = violation;
|
|
229
|
+
const subject = decisionSubject(violation);
|
|
230
|
+
// 역할 때문에 순서만 다른 후보는 같은 질문으로 묶는다.
|
|
231
|
+
const key = JSON.stringify([rule, subject, [...candidates].sort()]);
|
|
232
|
+
let decision = byQuestion.get(key);
|
|
233
|
+
if (!decision) {
|
|
234
|
+
decision = { rule, subject, uses: 0, files: new Set(), locations: [], candidates, recommended, reasons: new Set() };
|
|
235
|
+
byQuestion.set(key, decision);
|
|
236
|
+
}
|
|
237
|
+
decision.uses += 1;
|
|
238
|
+
decision.files.add(file);
|
|
239
|
+
if (decision.locations.length < MAX_DECISION_LOCATIONS) decision.locations.push({ file, line, column });
|
|
240
|
+
if (decision.recommended !== recommended) decision.recommended = null;
|
|
241
|
+
if (candidates.length > 1) decision.reasons.add("multiple-candidates");
|
|
242
|
+
if (rule === "color-unknown") decision.reasons.add("no-token");
|
|
243
|
+
if (messageId === "useTokenThemed") decision.reasons.add("themed-token");
|
|
244
|
+
if (messageId === "useComponentAsk") decision.reasons.add("dynamic-props");
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
return [...byQuestion.values()]
|
|
248
|
+
.sort((a, b) => b.uses - a.uses)
|
|
249
|
+
.map(({ files, reasons, ...decision }, index) => ({
|
|
250
|
+
id: `decision-${index + 1}`,
|
|
251
|
+
...decision,
|
|
252
|
+
files: files.size,
|
|
253
|
+
reasons: [...reasons],
|
|
254
|
+
}));
|
|
255
|
+
}
|
|
256
|
+
|
|
161
257
|
/**
|
|
162
258
|
* 결과를 받은 에이전트가 무엇부터 해야 하는지를 순서대로 적는다.
|
|
163
259
|
* @param {{ colorTokens: number }} designSystem
|
|
164
260
|
* @param {Violation[]} violations action 이 붙은 위반들
|
|
165
261
|
* @param {"en" | "ko"} [lang]
|
|
262
|
+
* @param {Decision[]} [decisions] check 결과의 결정 목록. 훅은 위반만 보여 준다
|
|
166
263
|
* @returns {string[]}
|
|
167
264
|
*/
|
|
168
|
-
export function nextSteps(designSystem, violations, lang) {
|
|
265
|
+
export function nextSteps(designSystem, violations, lang, decisions) {
|
|
169
266
|
const m = messages(lang);
|
|
170
267
|
const noColorTokens = designSystem.colorTokens === 0;
|
|
171
268
|
// 색 토큰이 없으면 색 위반은 하나씩 다룰 일이 아니라 토큰을 정하는 일 하나로 묶인다.
|
|
@@ -173,13 +270,16 @@ export function nextSteps(designSystem, violations, lang) {
|
|
|
173
270
|
? violations.filter((v) => !v.rule.startsWith("color-"))
|
|
174
271
|
: violations;
|
|
175
272
|
const count = (action) => actionable.filter((v) => v.action === action).length;
|
|
176
|
-
const [repair, replace
|
|
273
|
+
const [repair, replace] = ["repair", "replace"].map(count);
|
|
274
|
+
const ask = decisions === undefined
|
|
275
|
+
? count("ask")
|
|
276
|
+
: decisions.filter((decision) => !noColorTokens || !decision.rule.startsWith("color-")).length;
|
|
177
277
|
const steps = [];
|
|
178
278
|
|
|
179
279
|
if (noColorTokens) steps.push(m.nextNoTokens());
|
|
180
280
|
if (repair > 0) steps.push(m.nextRepair(repair));
|
|
181
281
|
if (replace > 0) steps.push(m.nextReplace(replace));
|
|
182
|
-
if (ask > 0) steps.push(m.nextAsk(ask));
|
|
282
|
+
if (ask > 0) steps.push(decisions === undefined ? m.hookNextAsk(ask) : m.nextAsk(ask));
|
|
183
283
|
if (repair + replace > 0) steps.push(m.nextRerun());
|
|
184
284
|
|
|
185
285
|
return steps.length > 0 ? steps : [m.nextNone()];
|
|
@@ -216,6 +316,13 @@ function toViolation(file, source, message, config) {
|
|
|
216
316
|
candidates = replacementNames(config.components?.replaces?.[found]);
|
|
217
317
|
}
|
|
218
318
|
|
|
319
|
+
let recommended = null;
|
|
320
|
+
const color = rule === "color-use-token" && findArbitraryColors(found)[0];
|
|
321
|
+
if (color) {
|
|
322
|
+
const prefixes = utilityColorPrefixes(color.utility).map((prefix) => tokenToClass(color.utility, prefix));
|
|
323
|
+
recommended = recommendColorCandidate(candidates, prefixes);
|
|
324
|
+
}
|
|
325
|
+
|
|
219
326
|
return {
|
|
220
327
|
file,
|
|
221
328
|
line: message.line,
|
|
@@ -228,6 +335,7 @@ function toViolation(file, source, message, config) {
|
|
|
228
335
|
messageId: message.messageId,
|
|
229
336
|
found,
|
|
230
337
|
candidates,
|
|
338
|
+
recommended,
|
|
231
339
|
};
|
|
232
340
|
}
|
|
233
341
|
|
package/src/cli.js
CHANGED
|
@@ -3,7 +3,7 @@ import path from "node:path";
|
|
|
3
3
|
import { parseArgs } from "node:util";
|
|
4
4
|
import { check } from "./check.js";
|
|
5
5
|
import { collectColors } from "./colors.js";
|
|
6
|
-
import { CONFIG_FILE, loadConfig } from "./config.js";
|
|
6
|
+
import { CONFIG_FILE, loadConfig, tokenSettings } from "./config.js";
|
|
7
7
|
import { formatColorsText, formatText } from "./format.js";
|
|
8
8
|
import { runHook } from "./hook.js";
|
|
9
9
|
import { AGENT_CHOICES, install } from "./install.js";
|
|
@@ -30,7 +30,8 @@ const COMMANDS = {
|
|
|
30
30
|
const config = hasConfig ? loadConfig(cwd, configPath, resolveLang(flagLang)) : undefined;
|
|
31
31
|
const lang = resolveLang(flagLang, config?.lang);
|
|
32
32
|
const tokens = config ? loadTokens({ designsnitch: { ...config, lang } }, cwd).colors : undefined;
|
|
33
|
-
const
|
|
33
|
+
const tokenFile = config ? path.resolve(config.root, tokenSettings(config.tokens).file) : undefined;
|
|
34
|
+
const result = await collectColors({ cwd, paths, tokens, tokenFile });
|
|
34
35
|
return { stdout: format === "json" ? json(result) : formatColorsText(result, lang), exitCode: 0 };
|
|
35
36
|
},
|
|
36
37
|
|
package/src/colors.js
CHANGED
|
@@ -61,6 +61,7 @@ const collectRule = {
|
|
|
61
61
|
* @param {string} options.cwd 프로젝트 디렉터리
|
|
62
62
|
* @param {string[]} [options.paths] 검사할 파일이나 디렉터리 (cwd 기준)
|
|
63
63
|
* @param {Map<string, string[]>} [options.tokens] 색 값 → 토큰 이름들. 주면 색마다 tokens 를 붙인다
|
|
64
|
+
* @param {string} [options.tokenFile] 사용자 정의 속성 선언을 건너뛸 토큰 CSS 의 절대 경로
|
|
64
65
|
* @returns {Promise<{
|
|
65
66
|
* summary: { files: number, colors: number, paletteColors: number, uses: number },
|
|
66
67
|
* colors: (ColorUse & { color: string, literals: number, properties: Record<string, number>, tokens?: string[] })[],
|
|
@@ -68,7 +69,7 @@ const collectRule = {
|
|
|
68
69
|
* }>} colors 는 hex 색, palette 는 Tailwind 기본 팔레트 색. 둘 다 많이 쓰인 순서.
|
|
69
70
|
* literals 는 문자열 전체가 hex 인 곳의 수, properties 는 CSS 속성별 횟수
|
|
70
71
|
*/
|
|
71
|
-
export async function collectColors({ cwd, paths = ["."], tokens }) {
|
|
72
|
+
export async function collectColors({ cwd, paths = ["."], tokens, tokenFile }) {
|
|
72
73
|
const eslint = createEngine({
|
|
73
74
|
cwd,
|
|
74
75
|
// 수집이 목적이므로 eslint-disable 주석이 있어도 빠뜨리지 않는다.
|
|
@@ -92,9 +93,10 @@ export async function collectColors({ cwd, paths = ["."], tokens }) {
|
|
|
92
93
|
}
|
|
93
94
|
}
|
|
94
95
|
for (const file of cssFiles) {
|
|
96
|
+
const absolute = path.resolve(cwd, file);
|
|
95
97
|
let found;
|
|
96
98
|
try {
|
|
97
|
-
found = findCssColors(fs.readFileSync(
|
|
99
|
+
found = findCssColors(fs.readFileSync(absolute, "utf8"), { skipCustomProperties: absolute === tokenFile });
|
|
98
100
|
} catch {
|
|
99
101
|
continue; // 읽지 못한 CSS 는 건너뛴다
|
|
100
102
|
}
|
package/src/config.js
CHANGED
|
@@ -13,6 +13,26 @@ const EXAMPLE = `{
|
|
|
13
13
|
}`;
|
|
14
14
|
|
|
15
15
|
/** @typedef {string | string[] | { component: string | string[], when?: Record<string, (string | null)[]> }} Replacement */
|
|
16
|
+
/** @typedef {string | { file: string, exclude?: string[], prefer?: string[] }} TokenSettings */
|
|
17
|
+
|
|
18
|
+
/** @param {TokenSettings} tokens */
|
|
19
|
+
export function tokenSettings(tokens) {
|
|
20
|
+
return typeof tokens === "string" ? { file: tokens } : tokens;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function invalidTokenField(tokens) {
|
|
24
|
+
if (typeof tokens === "string") return tokens.length > 0 ? null : "tokens";
|
|
25
|
+
if (!isRecord(tokens)) return "tokens";
|
|
26
|
+
if (typeof tokens.file !== "string" || tokens.file.length === 0) return "tokens.file";
|
|
27
|
+
if (tokens.exclude !== undefined && !isPatternList(tokens.exclude, /^[^*]*\*?$/)) return "tokens.exclude";
|
|
28
|
+
if (tokens.prefer !== undefined && !isPatternList(tokens.prefer, /^[^*]+$/)) return "tokens.prefer";
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function isPatternList(values, pattern) {
|
|
33
|
+
return Array.isArray(values) &&
|
|
34
|
+
values.every((value) => typeof value === "string" && value.length > 0 && pattern.test(value));
|
|
35
|
+
}
|
|
16
36
|
|
|
17
37
|
/** @param {Replacement} [replacement] */
|
|
18
38
|
export function replacementNames(replacement) {
|
|
@@ -27,7 +47,7 @@ export function replacementNames(replacement) {
|
|
|
27
47
|
* @param {string} cwd 프로젝트 디렉터리
|
|
28
48
|
* @param {string} [configPath] cwd 기준 설정 파일 경로
|
|
29
49
|
* @param {"en" | "ko"} [lang] 오류 문장의 언어
|
|
30
|
-
* @returns {{ tokens: string, lang?: "en" | "ko", components?: { path: string, replaces: Record<string, Replacement> } }}
|
|
50
|
+
* @returns {{ tokens: TokenSettings, root: string, lang?: "en" | "ko", components?: { path: string, replaces: Record<string, Replacement> } }}
|
|
31
51
|
*/
|
|
32
52
|
export function loadConfig(cwd, configPath = CONFIG_FILE, lang) {
|
|
33
53
|
const m = messages(lang);
|
|
@@ -47,10 +67,12 @@ export function loadConfig(cwd, configPath = CONFIG_FILE, lang) {
|
|
|
47
67
|
throw new Error(m.configUnreadable({ file, reason: error.message }));
|
|
48
68
|
}
|
|
49
69
|
|
|
50
|
-
|
|
70
|
+
const tokenField = invalidTokenField(config?.tokens);
|
|
71
|
+
if (tokenField === "tokens") throw new Error(m.configNoTokens({ file }));
|
|
72
|
+
if (tokenField) throw new Error(m.invalidTokenSetting({ field: tokenField, file }));
|
|
51
73
|
if (config.lang !== undefined && !isLang(config.lang)) throw new Error(m.configBadLang({ file }));
|
|
52
74
|
if (config.components !== undefined) validateComponents(config.components, file, m);
|
|
53
|
-
return config;
|
|
75
|
+
return { ...config, root: path.dirname(file) };
|
|
54
76
|
}
|
|
55
77
|
|
|
56
78
|
function validateComponents(components, file, m) {
|
package/src/core/classes.js
CHANGED
|
@@ -44,3 +44,15 @@ export function findPaletteClasses(text) {
|
|
|
44
44
|
name: match[2],
|
|
45
45
|
}));
|
|
46
46
|
}
|
|
47
|
+
|
|
48
|
+
// 예: "#3B82F6", "1px solid #fff". bg-[#fff] 의 hex 도 걸리므로 클래스 검사와 겹치지 않게 쓴다.
|
|
49
|
+
const HEX_COLOR = /(?<![\w&#])#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})(?![\w-])/gi;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 문자열에서 hex 색 자체를 찾는다.
|
|
53
|
+
* @param {string} text
|
|
54
|
+
* @returns {{ index: number, text: string, value: string }[]}
|
|
55
|
+
*/
|
|
56
|
+
export function findHexColors(text) {
|
|
57
|
+
return [...text.matchAll(HEX_COLOR)].map((match) => ({ index: match.index, text: match[0], value: match[0] }));
|
|
58
|
+
}
|
package/src/core/css.js
CHANGED
|
@@ -7,13 +7,14 @@ const DISABLE_NEXT_LINE = "designsnitch-disable-next-line";
|
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* CSS 의 선언 값에서 hex 색을 찾는다. 줄과 열은 1부터 시작하고, 끝 열은 색 바로 다음 칸이다.
|
|
10
|
-
*
|
|
10
|
+
* 토큰 CSS 에서는 옵션을 켜서 사용자 정의 속성 선언을 건너뛸 수 있다.
|
|
11
11
|
* 바로 앞에 designsnitch-disable-next-line 주석이 있는 선언의 색은 disabled 로 표시한다.
|
|
12
12
|
* @param {string} css
|
|
13
|
+
* @param {{ skipCustomProperties?: boolean }} [options]
|
|
13
14
|
* @returns {{ line: number, column: number, endLine: number, endColumn: number, value: string, prop: string, disabled: boolean }[]}
|
|
14
15
|
* @throws {import("postcss").CssSyntaxError} CSS 를 읽지 못했을 때
|
|
15
16
|
*/
|
|
16
|
-
export function findCssColors(css) {
|
|
17
|
+
export function findCssColors(css, { skipCustomProperties = false } = {}) {
|
|
17
18
|
const lineStarts = [0];
|
|
18
19
|
for (let i = 0; i < css.length; i += 1) {
|
|
19
20
|
if (css[i] === "\n") lineStarts.push(i + 1);
|
|
@@ -26,7 +27,7 @@ export function findCssColors(css) {
|
|
|
26
27
|
|
|
27
28
|
const found = [];
|
|
28
29
|
postcss.parse(css).walkDecls((decl) => {
|
|
29
|
-
if (decl.prop.startsWith("--")) return;
|
|
30
|
+
if (skipCustomProperties && decl.prop.startsWith("--")) return;
|
|
30
31
|
|
|
31
32
|
const previous = decl.prev();
|
|
32
33
|
const disabled = previous?.type === "comment" && previous.text.includes(DISABLE_NEXT_LINE);
|
package/src/core/tokens.js
CHANGED
|
@@ -2,6 +2,11 @@ import postcss from "postcss";
|
|
|
2
2
|
import { normalizeHex } from "./color.js";
|
|
3
3
|
|
|
4
4
|
const COLOR_TOKEN = /^--color-/;
|
|
5
|
+
const ROLE_PREFIXES = {
|
|
6
|
+
text: ["--color-text-"],
|
|
7
|
+
border: ["--color-border-"],
|
|
8
|
+
bg: ["--color-bg-", "--color-surface", "--color-background"],
|
|
9
|
+
};
|
|
5
10
|
// var(--name) 또는 var(--name, 대체값)
|
|
6
11
|
const VAR_REFERENCE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/s;
|
|
7
12
|
|
|
@@ -20,9 +25,10 @@ export function parseColorTokens(css) {
|
|
|
20
25
|
/**
|
|
21
26
|
* 색 값 → 토큰 표와 서로 다른 최종 값이 있는 토큰 이름을 함께 읽는다.
|
|
22
27
|
* @param {string} css
|
|
28
|
+
* @param {string[]} [exclude] 정확한 이름 또는 끝에 *가 붙은 이름 패턴
|
|
23
29
|
* @returns {{ colors: Map<string, string[]>, themed: Set<string> }}
|
|
24
30
|
*/
|
|
25
|
-
export function parseColorTokenData(css) {
|
|
31
|
+
export function parseColorTokenData(css, exclude = []) {
|
|
26
32
|
/** @type {Map<string, string[]>} 변수 이름 → 선언된 값들 */
|
|
27
33
|
const declared = new Map();
|
|
28
34
|
postcss.parse(css).walkDecls(/^--/, (decl) => {
|
|
@@ -48,6 +54,7 @@ export function parseColorTokenData(css) {
|
|
|
48
54
|
const themed = new Set();
|
|
49
55
|
for (const [name, values] of declared) {
|
|
50
56
|
if (!COLOR_TOKEN.test(name)) continue;
|
|
57
|
+
if (exclude.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern)) continue;
|
|
51
58
|
const resolved = new Set();
|
|
52
59
|
for (const value of values.flatMap((value) => resolve(value, new Set([name])))) {
|
|
53
60
|
const color = normalizeHex(value);
|
|
@@ -63,3 +70,35 @@ export function parseColorTokenData(css) {
|
|
|
63
70
|
}
|
|
64
71
|
return { colors, themed };
|
|
65
72
|
}
|
|
73
|
+
|
|
74
|
+
export function utilityColorPrefixes(utility) {
|
|
75
|
+
const kind = utility.toLowerCase().split("-", 1)[0];
|
|
76
|
+
if (["border", "ring", "outline", "divide"].includes(kind)) return ROLE_PREFIXES.border;
|
|
77
|
+
return kind === "text" || kind === "bg" ? ROLE_PREFIXES[kind] : [];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function cssColorPrefixes(property) {
|
|
81
|
+
const name = property.toLowerCase();
|
|
82
|
+
if (name === "color") return ROLE_PREFIXES.text;
|
|
83
|
+
if (name.startsWith("border")) return ROLE_PREFIXES.border;
|
|
84
|
+
if (name.startsWith("background")) return ROLE_PREFIXES.bg;
|
|
85
|
+
return [];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const startsWithAny = (name, prefixes) => prefixes.some((prefix) => name.startsWith(prefix));
|
|
89
|
+
|
|
90
|
+
export function selectColorTokens(names, prefer, rolePrefixes) {
|
|
91
|
+
const prefix = prefer.find((prefix) => names.some((name) => name.startsWith(prefix)));
|
|
92
|
+
if (prefix !== undefined) {
|
|
93
|
+
const preferred = names.filter((name) => name.startsWith(prefix));
|
|
94
|
+
if (preferred.length === 1) return preferred;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const matching = names.filter((name) => startsWithAny(name, rolePrefixes));
|
|
98
|
+
return [...matching, ...names.filter((name) => !startsWithAny(name, rolePrefixes))];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function recommendColorCandidate(candidates, rolePrefixes) {
|
|
102
|
+
const matching = candidates.filter((candidate) => startsWithAny(candidate, rolePrefixes));
|
|
103
|
+
return matching.length === 1 ? matching[0] : null;
|
|
104
|
+
}
|
package/src/format.js
CHANGED
|
@@ -5,13 +5,14 @@ import { messages } from "./messages.js";
|
|
|
5
5
|
* @param {Awaited<ReturnType<typeof import("./check.js").check>>} result
|
|
6
6
|
* @param {"en" | "ko"} [lang]
|
|
7
7
|
*/
|
|
8
|
-
export function formatText({ designSystem, problems, summary, violations }, lang) {
|
|
8
|
+
export function formatText({ designSystem, problems, summary, violations, decisions = [], unchecked }, lang) {
|
|
9
9
|
const m = messages(lang);
|
|
10
10
|
// 첫 줄은 설정에서 무엇을 읽었는지다. 경로를 잘못 적으면 여기서 0개로 드러난다.
|
|
11
11
|
const header = [m.designSystem(designSystem), ...problems.map(m.notice), ""];
|
|
12
|
+
const uncheckedLine = unchecked?.hexColors > 0 ? [m.unchecked(unchecked)] : [];
|
|
12
13
|
|
|
13
14
|
if (violations.length === 0) {
|
|
14
|
-
return [...header, m.noViolations(summary), ""].join("\n");
|
|
15
|
+
return [...header, m.noViolations(summary), ...uncheckedLine, ""].join("\n");
|
|
15
16
|
}
|
|
16
17
|
|
|
17
18
|
const byFile = new Map();
|
|
@@ -36,7 +37,8 @@ export function formatText({ designSystem, problems, summary, violations }, lang
|
|
|
36
37
|
...header,
|
|
37
38
|
...sections,
|
|
38
39
|
m.summary(summary),
|
|
39
|
-
m.actions({ replace: count("replace"), ask: count("ask"), repair: count("repair") }),
|
|
40
|
+
m.actions({ replace: count("replace"), ask: count("ask"), repair: count("repair"), decisions: decisions.length }),
|
|
41
|
+
...uncheckedLine,
|
|
40
42
|
"",
|
|
41
43
|
].join("\n");
|
|
42
44
|
}
|
package/src/hook.js
CHANGED
|
@@ -96,11 +96,7 @@ async function checkHead({ cwd, config, files, lang }) {
|
|
|
96
96
|
}
|
|
97
97
|
if (paths.length === 0) return [];
|
|
98
98
|
|
|
99
|
-
const
|
|
100
|
-
if (config.components) {
|
|
101
|
-
baselineConfig.components = { ...config.components, path: path.resolve(cwd, config.components.path) };
|
|
102
|
-
}
|
|
103
|
-
const result = await check({ cwd: temp, config: baselineConfig, paths, lang });
|
|
99
|
+
const result = await check({ cwd: temp, config, paths, lang, sourceCwd: cwd });
|
|
104
100
|
return result.violations;
|
|
105
101
|
} finally {
|
|
106
102
|
if (temp) fs.rmSync(temp, { recursive: true, force: true });
|
package/src/messages.js
CHANGED
|
@@ -50,6 +50,14 @@ const en = {
|
|
|
50
50
|
`Node.js ${minimum} or later is required (current version: ${version}).`,
|
|
51
51
|
tokensSettingMissing: () =>
|
|
52
52
|
"designsnitch: set settings.designsnitch.tokens to the path of the token CSS file.",
|
|
53
|
+
invalidTokenSetting: ({ field, file }) => {
|
|
54
|
+
const details = {
|
|
55
|
+
"tokens.file": "a non-empty token CSS file path",
|
|
56
|
+
"tokens.exclude": "an array of non-empty token names or patterns with a trailing *",
|
|
57
|
+
"tokens.prefer": "an array of non-empty token name prefixes without wildcards",
|
|
58
|
+
};
|
|
59
|
+
return `"${field}" must be ${details[field]}.${file ? ` (${file})` : ""}`;
|
|
60
|
+
},
|
|
53
61
|
tokensFileMissing: ({ file }) => `designsnitch: token CSS file not found: ${file}`,
|
|
54
62
|
tokensUnreadable: ({ file, line, column, reason }) =>
|
|
55
63
|
`designsnitch: could not read the token CSS: ${file}:${line}:${column} ${reason}`,
|
|
@@ -85,6 +93,8 @@ const en = {
|
|
|
85
93
|
nextRepair: (n) => `action "repair" (${n}): fix the syntax error in that file first.`,
|
|
86
94
|
nextReplace: (n) => `action "replace" (${n}): replace found with the value in candidates.`,
|
|
87
95
|
nextAsk: (n) =>
|
|
96
|
+
`Before making changes, ask the user about the ${count(n, "entry", "entries")} in decisions. Include how often each comes up, the candidates, and the reasons for asking.`,
|
|
97
|
+
hookNextAsk: (n) =>
|
|
88
98
|
`action "ask" (${n}): do not change these. Ask the user, and include how often and for what each color is used, which \`designsnitch colors\` shows.`,
|
|
89
99
|
nextRerun: () => "After fixing, run the same command again.",
|
|
90
100
|
nextNone: () => "No violations.",
|
|
@@ -97,13 +107,15 @@ const en = {
|
|
|
97
107
|
severity: { error: "error", warning: "warning" },
|
|
98
108
|
summary: ({ errors, warnings, files }) =>
|
|
99
109
|
`${count(errors, "error")}, ${count(warnings, "warning")} (${count(files, "file")} checked)`,
|
|
100
|
-
actions: ({ replace, ask, repair }) =>
|
|
110
|
+
actions: ({ replace, ask, repair, decisions }) =>
|
|
101
111
|
[
|
|
102
112
|
`${replace} can be replaced right away`,
|
|
103
|
-
`${ask} ${needs(ask)} a person's decision`,
|
|
113
|
+
`${ask} ${needs(ask)} a person's decision (${count(decisions, "decision")})`,
|
|
104
114
|
...(repair > 0 ? [`${repair} ${needs(repair)} a syntax fix`] : []),
|
|
105
115
|
].join(", "),
|
|
106
116
|
noViolations: ({ files }) => `No violations. (${count(files, "file")} checked)`,
|
|
117
|
+
unchecked: ({ hexColors, files }) =>
|
|
118
|
+
`Not checked: ${count(hexColors, "hex color")} in other strings in ${count(files, "file")}, such as theme objects and chart options. \`designsnitch colors\` lists them.`,
|
|
107
119
|
|
|
108
120
|
// colors
|
|
109
121
|
colorsNone: ({ files }) => `No colors found in the code. (${count(files, "file")} checked)`,
|
|
@@ -176,6 +188,14 @@ const ko = {
|
|
|
176
188
|
`Node.js ${minimum} 이상이 필요합니다(현재 버전: ${version}).`,
|
|
177
189
|
tokensSettingMissing: () =>
|
|
178
190
|
"designsnitch: settings.designsnitch.tokens 에 토큰 CSS 파일 경로를 설정하세요.",
|
|
191
|
+
invalidTokenSetting: ({ field, file }) => {
|
|
192
|
+
const details = {
|
|
193
|
+
"tokens.file": "비어 있지 않은 토큰 CSS 파일 경로를 입력하세요",
|
|
194
|
+
"tokens.exclude": "비어 있지 않은 토큰 이름이나 끝에 *가 있는 패턴을 배열로 입력하세요",
|
|
195
|
+
"tokens.prefer": "와일드카드가 없는 토큰 이름 접두어를 배열로 입력하세요",
|
|
196
|
+
};
|
|
197
|
+
return `"${field}"에 ${details[field]}.${file ? ` (${file})` : ""}`;
|
|
198
|
+
},
|
|
179
199
|
tokensFileMissing: ({ file }) => `designsnitch: 토큰 CSS 파일을 찾을 수 없습니다: ${file}`,
|
|
180
200
|
tokensUnreadable: ({ file, line, column, reason }) =>
|
|
181
201
|
`designsnitch: 토큰 CSS를 읽을 수 없습니다: ${file}:${line}:${column} ${reason}`,
|
|
@@ -209,6 +229,8 @@ const ko = {
|
|
|
209
229
|
nextRepair: (n) => `action이 repair인 ${n}건은 그 파일의 문법 오류부터 고치세요.`,
|
|
210
230
|
nextReplace: (n) => `action이 replace인 ${n}건은 found를 candidates의 값으로 바꾸세요.`,
|
|
211
231
|
nextAsk: (n) =>
|
|
232
|
+
`변경하기 전에 decisions의 ${n}건을 사용자에게 물으세요. 사용 횟수와 후보, 확인이 필요한 이유를 함께 알려 주세요.`,
|
|
233
|
+
hookNextAsk: (n) =>
|
|
212
234
|
`action이 ask인 ${n}건은 바꾸지 말고 사용자에게 물으세요. 물을 때는 \`designsnitch colors\`로 그 색이 몇 곳에서 어떻게 쓰이는지 확인해서 근거로 함께 주세요.`,
|
|
213
235
|
nextRerun: () => "고친 뒤 같은 명령을 다시 실행하세요.",
|
|
214
236
|
nextNone: () => "위반이 없습니다.",
|
|
@@ -220,13 +242,15 @@ const ko = {
|
|
|
220
242
|
severity: { error: "오류", warning: "경고" },
|
|
221
243
|
summary: ({ errors, warnings, files }) =>
|
|
222
244
|
`오류 ${errors}개, 경고 ${warnings}개 (파일 ${files}개 검사)`,
|
|
223
|
-
actions: ({ replace, ask, repair }) =>
|
|
245
|
+
actions: ({ replace, ask, repair, decisions }) =>
|
|
224
246
|
[
|
|
225
247
|
`바로 바꿀 수 있는 것 ${replace}건`,
|
|
226
|
-
`사람이 정해야 하는 것 ${ask}
|
|
248
|
+
`사람이 정해야 하는 것 ${ask}건 (결정 ${decisions}개)`,
|
|
227
249
|
...(repair > 0 ? [`문법을 고쳐야 하는 것 ${repair}건`] : []),
|
|
228
250
|
].join(", "),
|
|
229
251
|
noViolations: ({ files }) => `위반이 없습니다. (파일 ${files}개 검사)`,
|
|
252
|
+
unchecked: ({ hexColors, files }) =>
|
|
253
|
+
`검사하지 못함: 테마 객체나 차트 옵션 같은 다른 문자열에 hex 색 ${hexColors}개 (파일 ${files}개). \`designsnitch colors\`로 볼 수 있습니다.`,
|
|
230
254
|
|
|
231
255
|
colorsNone: ({ files }) => `코드에서 색을 찾지 못했습니다. (파일 ${files}개 검사)`,
|
|
232
256
|
colorsSummary: ({ colors, paletteColors, uses, files }) =>
|
|
@@ -3,6 +3,7 @@ import { normalizeHex } from "../core/color.js";
|
|
|
3
3
|
import { loadTokens } from "./load-tokens.js";
|
|
4
4
|
import { ruleMessages, TEXT } from "./suggest.js";
|
|
5
5
|
import { visitStrings } from "./visit-strings.js";
|
|
6
|
+
import { mergeVisitors, visitInlineStyleColors } from "./visit-style.js";
|
|
6
7
|
|
|
7
8
|
/** @type {import("eslint").Rule.RuleModule} */
|
|
8
9
|
export default {
|
|
@@ -23,13 +24,11 @@ export default {
|
|
|
23
24
|
const m = ruleMessages(context);
|
|
24
25
|
const { colors } = tokens;
|
|
25
26
|
|
|
26
|
-
|
|
27
|
+
function report(found, { loc }) {
|
|
27
28
|
if (colors.has(normalizeHex(found.value))) return;
|
|
28
|
-
context.report({
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
});
|
|
33
|
-
});
|
|
29
|
+
context.report({ loc, messageId: "unknown", data: { text: m.unknownColor({ found: found.text }) } });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return mergeVisitors(visitStrings(context, findArbitraryColors, report), visitInlineStyleColors(context, report));
|
|
34
33
|
},
|
|
35
34
|
};
|