designsnitch 0.1.0 → 0.3.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/src/install.js ADDED
@@ -0,0 +1,153 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { CONFIG_FILE } from "./config.js";
5
+ import { messages } from "./messages.js";
6
+
7
+ const SKILLS_DIR = fileURLToPath(new URL("../skills", import.meta.url));
8
+ const HOOK_COMMAND = "npx designsnitch hook";
9
+
10
+ /**
11
+ * 에이전트마다 스킬을 읽는 곳, 훅을 등록하는 파일, 이벤트 이름이 다르다.
12
+ * 훅이 하는 일(표준 입력의 JSON 을 읽고, 막을 때 종료 코드 2와 stderr)은 같다.
13
+ * editEvent 는 파일을 고친 직후, stopEvent 는 작업을 끝내려 할 때다.
14
+ */
15
+ const AGENTS = {
16
+ claude: {
17
+ skillsDir: ".claude/skills",
18
+ hooksFile: ".claude/settings.json",
19
+ editEvent: "PostToolUse",
20
+ stopEvent: "Stop",
21
+ editTools: "Edit|Write|MultiEdit",
22
+ hook: { type: "command", command: HOOK_COMMAND },
23
+ approval: null,
24
+ },
25
+ codex: {
26
+ skillsDir: ".agents/skills",
27
+ hooksFile: ".codex/hooks.json",
28
+ editEvent: "PostToolUse",
29
+ stopEvent: "Stop",
30
+ // Codex 는 셸 명령으로도 파일을 고친다. 그런 수정은 Stop 훅이 git 에서 바뀐 파일을 보고 잡는다.
31
+ editTools: "apply_patch",
32
+ hook: { type: "command", command: HOOK_COMMAND, timeout: 60 },
33
+ // 신뢰한 프로젝트에서, 사용자가 승인한 훅만 실행한다.
34
+ approval: "codexTrust",
35
+ },
36
+ // geminicli.com 의 공식 문서 기준. timeout 은 밀리초다.
37
+ gemini: {
38
+ skillsDir: ".agents/skills",
39
+ hooksFile: ".gemini/settings.json",
40
+ editEvent: "AfterTool",
41
+ stopEvent: "AfterAgent",
42
+ editTools: "write_file|replace",
43
+ hook: { name: "designsnitch", type: "command", command: HOOK_COMMAND, timeout: 60000 },
44
+ // 새 프로젝트 훅은 실행하기 전에 경고하고 허용을 받는다.
45
+ approval: "geminiTrust",
46
+ },
47
+ // docs.x.ai 의 공식 문서 기준. 훅은 .grok/hooks/*.json 어느 파일에 둬도 된다. timeout 은 초다.
48
+ // Claude Code 의 도구 이름(Edit, Write)은 Grok 의 도구로 자동으로 연결된다고 문서에 적혀 있다.
49
+ grok: {
50
+ skillsDir: ".grok/skills",
51
+ hooksFile: ".grok/hooks/designsnitch.json",
52
+ editEvent: "PostToolUse",
53
+ stopEvent: "Stop",
54
+ editTools: "Edit|Write|MultiEdit",
55
+ hook: { type: "command", command: HOOK_COMMAND, timeout: 60 },
56
+ // 신뢰한 프로젝트의 훅만 실행한다(/hooks-trust 또는 --trust).
57
+ approval: "grokTrust",
58
+ },
59
+ };
60
+
61
+ export const AGENT_CHOICES = [...Object.keys(AGENTS), "all"];
62
+
63
+ /**
64
+ * 프로젝트에 스킬과 에이전트 훅을 설치한다.
65
+ * 여러 번 실행해도 된다. 스킬은 최신으로 덮어쓰고, 훅은 없을 때만 더한다.
66
+ * @param {{ cwd: string, lang?: "en" | "ko", agent?: "claude" | "codex" | "gemini" | "grok" | "all" }} options
67
+ * @returns {{ stdout: string, exitCode: 0 }}
68
+ * @throws {Error} 훅을 등록할 파일을 읽을 수 없을 때. 이때는 아무것도 바꾸지 않는다
69
+ */
70
+ export function install({ cwd, lang, agent = "claude" }) {
71
+ const m = messages(lang);
72
+ const targets = (agent === "all" ? Object.keys(AGENTS) : [agent]).map((name) => AGENTS[name]);
73
+
74
+ // 훅 파일이 깨져 있으면 아무것도 건드리기 전에 멈춘다.
75
+ const settings = new Map(
76
+ targets.map((target) => [target, readJson(path.join(cwd, target.hooksFile), m)]),
77
+ );
78
+
79
+ const skills = fs.readdirSync(SKILLS_DIR).filter((name) => !name.startsWith("."));
80
+ const lines = [];
81
+ const steps = [];
82
+
83
+ const copiedTo = new Set();
84
+ for (const target of targets) {
85
+ // Codex 와 Gemini CLI 는 같은 .agents/skills 를 읽는다. 한 번만 복사한다.
86
+ if (!copiedTo.has(target.skillsDir)) {
87
+ copiedTo.add(target.skillsDir);
88
+ for (const skill of skills) {
89
+ fs.cpSync(path.join(SKILLS_DIR, skill), path.join(cwd, target.skillsDir, skill), { recursive: true });
90
+ }
91
+ lines.push(m.skillsCopied({ n: skills.length, dir: target.skillsDir }));
92
+ }
93
+
94
+ const file = path.join(cwd, target.hooksFile);
95
+ const added = addHooks(settings.get(target), target);
96
+ if (added) {
97
+ fs.mkdirSync(path.dirname(file), { recursive: true });
98
+ fs.writeFileSync(file, `${JSON.stringify(settings.get(target), null, 2)}\n`);
99
+ }
100
+
101
+ lines.push(added ? m.hookRegistered({ file: target.hooksFile }) : m.hookAlready({ file: target.hooksFile }));
102
+ if (added && target.approval) steps.push(m[target.approval]());
103
+ }
104
+
105
+ if (!isInstalled(cwd)) steps.push(m.installPackage());
106
+ if (!fs.existsSync(path.join(cwd, CONFIG_FILE))) steps.push(m.askAgent({ configFile: CONFIG_FILE }));
107
+
108
+ if (steps.length > 0) lines.push("", m.nextTitle, ...steps.map((step) => `- ${step}`));
109
+ lines.push("");
110
+ return { stdout: lines.join("\n"), exitCode: 0 };
111
+ }
112
+
113
+ function readJson(file, m) {
114
+ if (!fs.existsSync(file)) return {};
115
+ try {
116
+ const value = JSON.parse(fs.readFileSync(file, "utf8"));
117
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
118
+ } catch {
119
+ // 아래에서 같은 오류로 알린다.
120
+ }
121
+ throw new Error(m.settingsUnreadable({ file }));
122
+ }
123
+
124
+ /** 훅이 없는 이벤트에만 더한다. 하나라도 더했으면 true. */
125
+ function addHooks(settings, target) {
126
+ const entries = {
127
+ [target.editEvent]: { matcher: target.editTools, hooks: [target.hook] },
128
+ [target.stopEvent]: { hooks: [target.hook] },
129
+ };
130
+ settings.hooks ??= {};
131
+ let added = false;
132
+ for (const [event, entry] of Object.entries(entries)) {
133
+ const existing = (settings.hooks[event] ??= []);
134
+ const registered = existing.some((item) =>
135
+ item.hooks?.some((hook) => hook.command?.includes("designsnitch hook")),
136
+ );
137
+ if (!registered) {
138
+ existing.push(structuredClone(entry));
139
+ added = true;
140
+ }
141
+ }
142
+ return added;
143
+ }
144
+
145
+ function isInstalled(cwd) {
146
+ if (fs.existsSync(path.join(cwd, "node_modules/designsnitch"))) return true;
147
+ try {
148
+ const pkg = JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8"));
149
+ return Boolean(pkg.dependencies?.designsnitch ?? pkg.devDependencies?.designsnitch);
150
+ } catch {
151
+ return false;
152
+ }
153
+ }
@@ -0,0 +1,275 @@
1
+ /**
2
+ * 사람과 에이전트가 읽는 문장을 한곳에 모은다. 영어가 기본이고 한국어를 고를 수 있다.
3
+ * 규칙 이름, JSON 필드 이름, 출력의 구조는 언어와 무관하다.
4
+ */
5
+
6
+ export const LANGS = ["en", "ko"];
7
+
8
+ /** @returns {lang is "en" | "ko"} */
9
+ export const isLang = (lang) => LANGS.includes(lang);
10
+
11
+ /**
12
+ * 쓸 언어를 정한다. 앞의 것이 우선한다: 직접 준 값, 환경 변수 DESIGNSNITCH_LANG, 영어.
13
+ * @param {...unknown} candidates 우선순위 순서의 후보. 알 수 없는 값은 건너뛴다
14
+ * @returns {"en" | "ko"}
15
+ */
16
+ export function resolveLang(...candidates) {
17
+ return [...candidates, process.env.DESIGNSNITCH_LANG, "en"].find(isLang);
18
+ }
19
+
20
+ /** @param {"en" | "ko"} [lang] */
21
+ export function messages(lang) {
22
+ return resolveLang(lang) === "ko" ? ko : en;
23
+ }
24
+
25
+ const count = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
26
+ // "1 needs", "2 need"
27
+ const needs = (n) => (n === 1 ? "needs" : "need");
28
+
29
+ const en = {
30
+ // 규칙
31
+ useToken: ({ found, tokens, candidates }) =>
32
+ `${found} has the same color as ${tokens}. Use instead: ${candidates}`,
33
+ useTokenThemed: ({ found, tokens, candidates }) =>
34
+ `${found} has the same color as ${tokens}. Candidates: ${candidates}. ` +
35
+ "A candidate token has different values across themes. Using it can change the color in another theme.",
36
+ unknownColor: ({ found }) => `The color of ${found} is not in the tokens.`,
37
+ unknownCssColor: ({ value }) => `The color ${value} is not in the tokens.`,
38
+ useComponent: ({ tag, component, path }) =>
39
+ `Use a design system component instead of <${tag}>: ${component} (${path})`,
40
+ useComponentAsk: ({ tag, component, path, dynamicAttribute }) => {
41
+ const reason = dynamicAttribute === undefined
42
+ ? "The element has spread attributes."
43
+ : `The "${dynamicAttribute}" attribute has a dynamic value.`;
44
+ return `Check whether <${tag}> can be replaced with ${component} (${path}). ${reason}`;
45
+ },
46
+ replaceWith: ({ className }) => `Replace with ${className}`,
47
+
48
+ // 실행하지 못했을 때
49
+ nodeVersionUnsupported: ({ minimum, version }) =>
50
+ `Node.js ${minimum} or later is required (current version: ${version}).`,
51
+ tokensSettingMissing: () =>
52
+ "designsnitch: set settings.designsnitch.tokens to the path of the token CSS file.",
53
+ tokensFileMissing: ({ file }) => `designsnitch: token CSS file not found: ${file}`,
54
+ tokensUnreadable: ({ file, line, column, reason }) =>
55
+ `designsnitch: could not read the token CSS: ${file}:${line}:${column} ${reason}`,
56
+ componentsDirMissing: ({ dir }) => `Design system component directory not found: ${dir}`,
57
+ configMissing: ({ file, example }) =>
58
+ `Config file not found: ${file}\n` +
59
+ `Create it with content like this. The designsnitch-setup skill can write it by reading the repository.\n${example}`,
60
+ configUnreadable: ({ file, reason }) => `Could not read the config file: ${file}\n${reason}`,
61
+ configNoTokens: ({ file }) =>
62
+ `The config file has no "tokens" (the path of the token CSS file): ${file}`,
63
+ configNoComponentsPath: ({ file }) =>
64
+ `The config file has no "components.path" (the design system component directory): ${file}`,
65
+ configNoReplaces: ({ file }) =>
66
+ `The config file has no "components.replaces" (raw tags and the components that replace them): ${file}`,
67
+ configBadReplace: ({ tag, file }) =>
68
+ `"components.replaces.${tag}" in the config file must be a component name, an array of names, or an object with a "component" field: ${file}`,
69
+ configBadReplaceComponent: ({ tag, file }) =>
70
+ `"components.replaces.${tag}.component" in the config file must be a component name or a non-empty array of names: ${file}`,
71
+ configBadWhen: ({ tag, file }) =>
72
+ `"components.replaces.${tag}.when" in the config file must be an object mapping attributes to allowed values: ${file}`,
73
+ configBadWhenValues: ({ tag, attribute, file }) =>
74
+ `"components.replaces.${tag}.when.${attribute}" in the config file must be an array of strings or null values: ${file}`,
75
+ configBadLang: ({ file }) => `"lang" in the config file must be "en" or "ko": ${file}`,
76
+ settingsUnreadable: ({ file }) => `Could not read ${file}. Fix the JSON and run again.`,
77
+
78
+ // check
79
+ noColorTokens: ({ tokens }) =>
80
+ `No color token could be read from ${tokens}. ` +
81
+ "A --color-* variable is read when its value is a hex color or a var() that leads to one. " +
82
+ 'Until then every hex color is reported as "not in the tokens".',
83
+ nextNoTokens: () =>
84
+ "There are no color tokens, so there is nothing to judge colors against. Before fixing any color, collect the colors in use with `designsnitch colors` and decide the tokens.",
85
+ nextRepair: (n) => `action "repair" (${n}): fix the syntax error in that file first.`,
86
+ nextReplace: (n) => `action "replace" (${n}): replace found with the value in candidates.`,
87
+ nextAsk: (n) =>
88
+ `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
+ nextRerun: () => "After fixing, run the same command again.",
90
+ nextNone: () => "No violations.",
91
+
92
+ // 사람용 출력
93
+ designSystem: ({ colorTokens, components }) =>
94
+ `Design system: ${count(colorTokens, "color token")}, ` +
95
+ (components > 0 ? count(components, "component") : "no components configured"),
96
+ notice: (problem) => `Note: ${problem}`,
97
+ severity: { error: "error", warning: "warning" },
98
+ summary: ({ errors, warnings, files }) =>
99
+ `${count(errors, "error")}, ${count(warnings, "warning")} (${count(files, "file")} checked)`,
100
+ actions: ({ replace, ask, repair }) =>
101
+ [
102
+ `${replace} can be replaced right away`,
103
+ `${ask} ${needs(ask)} a person's decision`,
104
+ ...(repair > 0 ? [`${repair} ${needs(repair)} a syntax fix`] : []),
105
+ ].join(", "),
106
+ noViolations: ({ files }) => `No violations. (${count(files, "file")} checked)`,
107
+
108
+ // colors
109
+ colorsNone: ({ files }) => `No colors found in the code. (${count(files, "file")} checked)`,
110
+ colorsSummary: ({ colors, paletteColors, uses, files }) =>
111
+ `Colors used in the code: ${colors} hex, ${paletteColors} from the default palette (${count(uses, "use")}, ${count(files, "file")} checked)`,
112
+ hexTitle: "Hex colors",
113
+ paletteTitle: "Tailwind default palette",
114
+ usage: ({ uses, files }) => `${count(uses, "use")} ${count(files, "file")}`,
115
+ literals: (n) => `string ${n}`,
116
+ css: (n) => `CSS ${n}`,
117
+ tokenNote: (tokens) => (tokens.length > 0 ? `token: ${tokens.join(", ")}` : "no token"),
118
+
119
+ // hook
120
+ hookHeader: (n) => `designsnitch: ${count(n, "design system error")} in the files you just changed.`,
121
+ nextTitle: "What to do next",
122
+
123
+ // install
124
+ skillsCopied: ({ n, dir }) => `Copied ${count(n, "skill")} to ${dir}.`,
125
+ hookRegistered: ({ file }) => `Registered the hook in ${file}.`,
126
+ hookAlready: ({ file }) => `The hook is already registered in ${file}.`,
127
+ codexTrust: () =>
128
+ "Codex runs project hooks only in a trusted project, and only hooks you have approved. Open Codex in this project and approve the project and the hook when it asks.",
129
+ geminiTrust: () =>
130
+ "Gemini CLI warns before it runs a new project hook. Open Gemini CLI in this project and allow the hook. If you have turned on folder trust, trust this folder too.",
131
+ grokTrust: () =>
132
+ "Grok Build runs project hooks only in a trusted project. Open Grok Build in this project and trust it with /hooks-trust, or start it with --trust.",
133
+ installPackage: () =>
134
+ "Install the package in the project so the hook runs quickly every time: npm install --save-dev designsnitch",
135
+ askAgent: ({ configFile }) =>
136
+ `Ask your coding agent: "Set up designsnitch in this project." It finds the token CSS and the shared components, writes ${configFile}, and puts the rules into ESLint.`,
137
+
138
+ cliUsage: `Usage: designsnitch <command> [paths...] [--format text|json] [--config file] [--lang en|ko]
139
+
140
+ Commands
141
+ check Checks that UI code follows the design system.
142
+ colors Lists the colors the code uses. Works without a config file.
143
+ hook Called from a coding agent's hook. Exits with 2 when a file just changed has errors.
144
+ install Installs the skills and the agent hook into the project.
145
+
146
+ Options
147
+ paths Files or directories to look at (default: the current directory)
148
+ --format Output format: text (default) or json
149
+ --config Path of the config file (default: designsnitch.config.json)
150
+ --lang Language of the messages: en (default) or ko
151
+ --agent For install, the agent to install for: --agent claude|codex|gemini|grok|all (default: claude)
152
+
153
+ Exit codes of check: 0 no errors, 1 errors found, 2 could not run
154
+ `,
155
+ };
156
+
157
+ const ko = {
158
+ useToken: ({ found, tokens, candidates }) =>
159
+ `${found}의 색은 토큰 ${tokens}의 값입니다. 대신 사용: ${candidates}`,
160
+ useTokenThemed: ({ found, tokens, candidates }) =>
161
+ `${found}의 색은 토큰 ${tokens}의 값입니다. 후보: ${candidates}. ` +
162
+ "후보 중 테마마다 값이 다른 토큰이 있어 그 토큰으로 바꾸면 다른 테마에서 색이 바뀔 수 있습니다.",
163
+ unknownColor: ({ found }) => `${found}의 색은 토큰에 없습니다.`,
164
+ unknownCssColor: ({ value }) => `${value}의 색은 토큰에 없습니다.`,
165
+ useComponent: ({ tag, component, path }) =>
166
+ `<${tag}> 대신 디자인 시스템 컴포넌트를 사용하세요: ${component} (${path})`,
167
+ useComponentAsk: ({ tag, component, path, dynamicAttribute }) => {
168
+ const reason = dynamicAttribute === undefined
169
+ ? "요소에 spread 속성이 있습니다."
170
+ : `"${dynamicAttribute}" 속성 값이 동적입니다.`;
171
+ return `<${tag}>를 ${component} (${path})로 바꿀 수 있는지 확인하세요. ${reason}`;
172
+ },
173
+ replaceWith: ({ className }) => `${className}(으)로 바꾸기`,
174
+
175
+ nodeVersionUnsupported: ({ minimum, version }) =>
176
+ `Node.js ${minimum} 이상이 필요합니다(현재 버전: ${version}).`,
177
+ tokensSettingMissing: () =>
178
+ "designsnitch: settings.designsnitch.tokens 에 토큰 CSS 파일 경로를 설정하세요.",
179
+ tokensFileMissing: ({ file }) => `designsnitch: 토큰 CSS 파일을 찾을 수 없습니다: ${file}`,
180
+ tokensUnreadable: ({ file, line, column, reason }) =>
181
+ `designsnitch: 토큰 CSS를 읽을 수 없습니다: ${file}:${line}:${column} ${reason}`,
182
+ componentsDirMissing: ({ dir }) => `디자인 시스템 컴포넌트 경로를 찾을 수 없습니다: ${dir}`,
183
+ configMissing: ({ file, example }) =>
184
+ `설정 파일이 없습니다: ${file}\n` +
185
+ `다음과 같은 내용으로 만드세요. designsnitch-setup 스킬을 따르면 저장소를 읽어서 만들 수 있습니다.\n${example}`,
186
+ configUnreadable: ({ file, reason }) => `설정 파일을 읽을 수 없습니다: ${file}\n${reason}`,
187
+ configNoTokens: ({ file }) => `설정 파일에 "tokens"(토큰 CSS 파일 경로)가 없습니다: ${file}`,
188
+ configNoComponentsPath: ({ file }) =>
189
+ `설정 파일의 "components.path"(디자인 시스템 컴포넌트 경로)가 없습니다: ${file}`,
190
+ configNoReplaces: ({ file }) =>
191
+ `설정 파일의 "components.replaces"(raw 태그와 대체 컴포넌트)가 없습니다: ${file}`,
192
+ configBadReplace: ({ tag, file }) =>
193
+ `설정 파일의 "components.replaces.${tag}"는 컴포넌트 이름, 이름의 배열 또는 "component" 필드가 있는 객체여야 합니다: ${file}`,
194
+ configBadReplaceComponent: ({ tag, file }) =>
195
+ `설정 파일의 "components.replaces.${tag}.component"는 컴포넌트 이름 또는 이름이 하나 이상 담긴 배열이어야 합니다: ${file}`,
196
+ configBadWhen: ({ tag, file }) =>
197
+ `설정 파일의 "components.replaces.${tag}.when"은 속성별 허용 값을 지정하는 객체여야 합니다: ${file}`,
198
+ configBadWhenValues: ({ tag, attribute, file }) =>
199
+ `설정 파일의 "components.replaces.${tag}.when.${attribute}"는 문자열 또는 null을 담은 배열이어야 합니다: ${file}`,
200
+ configBadLang: ({ file }) => `설정 파일의 "lang"은 "en"이나 "ko"여야 합니다: ${file}`,
201
+ settingsUnreadable: ({ file }) => `${file} 을 읽을 수 없습니다. JSON 형식을 고친 뒤 다시 실행하세요.`,
202
+
203
+ noColorTokens: ({ tokens }) =>
204
+ `색 토큰을 하나도 읽지 못했습니다: ${tokens}. ` +
205
+ "--color-* 변수의 값이 hex이거나 var()로 hex를 가리켜야 읽을 수 있습니다. " +
206
+ '지금은 모든 hex가 "토큰에 없음" 경고로 나옵니다.',
207
+ nextNoTokens: () =>
208
+ "색 토큰이 없어서 색을 판정할 기준이 없습니다. 색을 고치기 전에 `designsnitch colors`로 쓰이는 색을 모아 토큰부터 정하세요.",
209
+ nextRepair: (n) => `action이 repair인 ${n}건은 그 파일의 문법 오류부터 고치세요.`,
210
+ nextReplace: (n) => `action이 replace인 ${n}건은 found를 candidates의 값으로 바꾸세요.`,
211
+ nextAsk: (n) =>
212
+ `action이 ask인 ${n}건은 바꾸지 말고 사용자에게 물으세요. 물을 때는 \`designsnitch colors\`로 그 색이 몇 곳에서 어떻게 쓰이는지 확인해서 근거로 함께 주세요.`,
213
+ nextRerun: () => "고친 뒤 같은 명령을 다시 실행하세요.",
214
+ nextNone: () => "위반이 없습니다.",
215
+
216
+ designSystem: ({ colorTokens, components }) =>
217
+ `디자인 시스템: 색 토큰 ${colorTokens}개, ` +
218
+ (components > 0 ? `컴포넌트 ${components}개` : "컴포넌트 설정 없음"),
219
+ notice: (problem) => `주의: ${problem}`,
220
+ severity: { error: "오류", warning: "경고" },
221
+ summary: ({ errors, warnings, files }) =>
222
+ `오류 ${errors}개, 경고 ${warnings}개 (파일 ${files}개 검사)`,
223
+ actions: ({ replace, ask, repair }) =>
224
+ [
225
+ `바로 바꿀 수 있는 것 ${replace}건`,
226
+ `사람이 정해야 하는 것 ${ask}건`,
227
+ ...(repair > 0 ? [`문법을 고쳐야 하는 것 ${repair}건`] : []),
228
+ ].join(", "),
229
+ noViolations: ({ files }) => `위반이 없습니다. (파일 ${files}개 검사)`,
230
+
231
+ colorsNone: ({ files }) => `코드에서 색을 찾지 못했습니다. (파일 ${files}개 검사)`,
232
+ colorsSummary: ({ colors, paletteColors, uses, files }) =>
233
+ `코드에서 쓰는 색: hex ${colors}개, 기본 팔레트 ${paletteColors}개 (사용 ${uses}곳, 파일 ${files}개 검사)`,
234
+ hexTitle: "hex 색",
235
+ paletteTitle: "Tailwind 기본 팔레트",
236
+ usage: ({ uses, files }) => `${uses}곳 파일 ${files}개`,
237
+ literals: (n) => `문자열 ${n}`,
238
+ css: (n) => `CSS ${n}`,
239
+ tokenNote: (tokens) => (tokens.length > 0 ? `토큰: ${tokens.join(", ")}` : "토큰 없음"),
240
+
241
+ hookHeader: (n) => `designsnitch: 방금 고친 파일에 디자인 시스템 오류가 ${n}건 있습니다.`,
242
+ nextTitle: "다음에 할 일",
243
+
244
+ skillsCopied: ({ n, dir }) => `스킬 ${n}개를 ${dir} 에 복사했습니다.`,
245
+ hookRegistered: ({ file }) => `훅을 ${file} 에 등록했습니다.`,
246
+ hookAlready: ({ file }) => `훅은 이미 ${file} 에 등록되어 있습니다.`,
247
+ codexTrust: () =>
248
+ "Codex는 신뢰한 프로젝트에서, 사용자가 승인한 훅만 실행합니다. 이 프로젝트에서 Codex를 열고 프로젝트 신뢰와 훅 승인을 요청받으면 승인하세요.",
249
+ geminiTrust: () =>
250
+ "Gemini CLI는 프로젝트에 새 훅이 생기면 실행하기 전에 경고합니다. 이 프로젝트에서 Gemini CLI를 열고 훅을 허용하세요. 폴더 신뢰 기능을 켜 두었다면 이 폴더도 신뢰해야 합니다.",
251
+ grokTrust: () =>
252
+ "Grok Build는 신뢰한 프로젝트의 훅만 실행합니다. 이 프로젝트에서 Grok Build를 열고 /hooks-trust 로 신뢰하거나 --trust 로 시작하세요.",
253
+ installPackage: () =>
254
+ "훅이 매번 빠르게 돌도록 프로젝트에 설치하세요: npm install --save-dev designsnitch",
255
+ askAgent: ({ configFile }) =>
256
+ `코딩 에이전트에게 "이 프로젝트에 designsnitch를 설정해 줘"라고 요청하세요. 토큰 CSS와 공용 컴포넌트를 찾아 ${configFile} 을 만들고 ESLint에 규칙을 넣습니다.`,
257
+
258
+ cliUsage: `사용법: designsnitch <명령> [경로...] [--format text|json] [--config 파일] [--lang en|ko]
259
+
260
+ 명령
261
+ check UI 코드가 디자인 시스템을 따르는지 검사합니다.
262
+ colors 코드에서 쓰는 색을 모아 보여줍니다. 설정 파일이 없어도 됩니다.
263
+ hook 코딩 에이전트의 훅에서 부릅니다. 방금 고친 파일에 오류가 있으면 2로 끝납니다.
264
+ install 스킬과 에이전트 훅을 프로젝트에 설치합니다.
265
+
266
+ 옵션
267
+ 경로 볼 파일이나 디렉터리 (기본: 현재 디렉터리)
268
+ --format 출력 형식. text(기본) 또는 json
269
+ --config 설정 파일 경로 (기본: designsnitch.config.json)
270
+ --lang 메시지의 언어. en(기본) 또는 ko
271
+ --agent install 에서 설치할 에이전트. --agent claude|codex|gemini|grok|all (기본: claude)
272
+
273
+ check 의 종료 코드: 0 오류 없음, 1 오류 있음, 2 실행하지 못함
274
+ `,
275
+ };
@@ -1,24 +1,35 @@
1
1
  import { findArbitraryColors } from "../core/classes.js";
2
2
  import { normalizeHex } from "../core/color.js";
3
3
  import { loadTokens } from "./load-tokens.js";
4
+ import { ruleMessages, TEXT } from "./suggest.js";
4
5
  import { visitStrings } from "./visit-strings.js";
5
6
 
6
7
  /** @type {import("eslint").Rule.RuleModule} */
7
8
  export default {
8
9
  meta: {
9
10
  type: "suggestion",
10
- docs: { description: "토큰에 없는 색을 hex로 쓰면 알린다" },
11
+ docs: { description: "Report hex colors that have no matching token" },
11
12
  schema: [],
12
- messages: {
13
- unknown: "{{found}}의 색은 토큰에 없습니다.",
14
- },
13
+ messages: { unknown: TEXT },
15
14
  },
16
15
  create(context) {
17
- const { colors } = loadTokens(context.settings, context.cwd);
16
+ let tokens;
17
+ try {
18
+ tokens = loadTokens(context.settings, context.cwd);
19
+ } catch {
20
+ // 토큰 설정 문제는 color-use-token 에서만 보고한다.
21
+ return {};
22
+ }
23
+ const m = ruleMessages(context);
24
+ const { colors } = tokens;
18
25
 
19
26
  return visitStrings(context, findArbitraryColors, (found, { loc }) => {
20
27
  if (colors.has(normalizeHex(found.value))) return;
21
- context.report({ loc, messageId: "unknown", data: { found: found.text } });
28
+ context.report({
29
+ loc,
30
+ messageId: "unknown",
31
+ data: { text: m.unknownColor({ found: found.text }) },
32
+ });
22
33
  });
23
34
  },
24
35
  };
@@ -1,37 +1,48 @@
1
1
  import { findArbitraryColors, tokenToClass } from "../core/classes.js";
2
2
  import { normalizeHex } from "../core/color.js";
3
3
  import { loadTokens } from "./load-tokens.js";
4
- import { REPLACE_MESSAGES, suggestClasses } from "./suggest.js";
4
+ import { ruleMessages, suggestClasses, TEXT } from "./suggest.js";
5
5
  import { visitStrings } from "./visit-strings.js";
6
6
 
7
7
  /** @type {import("eslint").Rule.RuleModule} */
8
8
  export default {
9
9
  meta: {
10
10
  type: "problem",
11
- docs: { description: "토큰이 있는 색을 hex로 쓰지 않는다" },
11
+ docs: { description: "Use the token instead of writing its color as a hex value" },
12
12
  hasSuggestions: true,
13
13
  schema: [],
14
- messages: {
15
- ...REPLACE_MESSAGES,
16
- useToken: "{{found}}의 색은 토큰 {{tokens}}의 값입니다. 대신 사용: {{classes}}",
17
- },
14
+ messages: { useToken: TEXT, useTokenThemed: TEXT, replace: TEXT, tokensConfig: TEXT },
18
15
  },
19
16
  create(context) {
20
- const { colors } = loadTokens(context.settings, context.cwd);
17
+ let tokens;
18
+ try {
19
+ tokens = loadTokens(context.settings, context.cwd);
20
+ } catch (error) {
21
+ return {
22
+ Program(node) {
23
+ context.report({ node, messageId: "tokensConfig", data: { text: error.message } });
24
+ },
25
+ };
26
+ }
27
+ const m = ruleMessages(context);
28
+ const { colors, themed } = tokens;
21
29
 
22
30
  return visitStrings(context, findArbitraryColors, (found, { loc, range }) => {
23
31
  const tokenNames = colors.get(normalizeHex(found.value));
24
32
  if (!tokenNames) return;
25
33
  const classes = tokenNames.map((name) => tokenToClass(found.utility, name));
34
+ const messageId = tokenNames.some((name) => themed.has(name)) ? "useTokenThemed" : "useToken";
26
35
  context.report({
27
36
  loc,
28
- messageId: "useToken",
37
+ messageId,
29
38
  data: {
30
- found: found.text,
31
- tokens: tokenNames.join(", "),
32
- classes: classes.join(", "),
39
+ text: m[messageId]({
40
+ found: found.text,
41
+ tokens: tokenNames.join(", "),
42
+ candidates: classes.join(", "),
43
+ }),
33
44
  },
34
- suggest: suggestClasses(range, classes),
45
+ suggest: suggestClasses(range, classes, m),
35
46
  });
36
47
  });
37
48
  },
@@ -1,11 +1,12 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { parseColorTokens, parseScaleTokens } from "../core/tokens.js";
3
+ import { parseColorTokenData } from "../core/tokens.js";
4
+ import { messages, resolveLang } from "../messages.js";
4
5
 
5
6
  /**
6
7
  * @typedef {object} Tokens
7
8
  * @property {Map<string, string[]>} colors 색 값 → 토큰 이름들
8
- * @property {ReturnType<typeof parseScaleTokens>} scale 간격 단위, radius, 폰트 크기 토큰
9
+ * @property {Set<string>} themed 테마마다 값이 다른 토큰 이름들
9
10
  */
10
11
 
11
12
  /** @type {Map<string, { mtimeMs: number, tokens: Tokens }>} */
@@ -17,26 +18,31 @@ const cache = new Map();
17
18
  * @returns {Tokens}
18
19
  */
19
20
  export function loadTokens(settings, cwd) {
21
+ const m = messages(resolveLang(settings?.designsnitch?.lang));
20
22
  const tokensPath = settings?.designsnitch?.tokens;
21
- if (typeof tokensPath !== "string") {
22
- throw new Error(
23
- "designsnitch: settings.designsnitch.tokens 에 토큰 CSS 파일 경로를 설정하세요.",
24
- );
25
- }
23
+ if (typeof tokensPath !== "string") throw new Error(m.tokensSettingMissing());
26
24
 
27
25
  const file = path.resolve(cwd, tokensPath);
28
- let stat;
29
26
  try {
30
- stat = fs.statSync(file);
31
- } catch {
32
- throw new Error(`designsnitch: 토큰 CSS 파일을 찾을 수 없습니다: ${file}`);
33
- }
27
+ const { mtimeMs } = fs.statSync(file);
28
+ const cached = cache.get(file);
29
+ if (cached?.mtimeMs === mtimeMs) return cached.tokens;
34
30
 
35
- const cached = cache.get(file);
36
- if (cached?.mtimeMs === stat.mtimeMs) return cached.tokens;
37
-
38
- const css = fs.readFileSync(file, "utf8");
39
- const tokens = { colors: parseColorTokens(css), scale: parseScaleTokens(css) };
40
- cache.set(file, { mtimeMs: stat.mtimeMs, tokens });
41
- return tokens;
31
+ const tokens = parseColorTokenData(fs.readFileSync(file, "utf8"));
32
+ cache.set(file, { mtimeMs, tokens });
33
+ return tokens;
34
+ } catch (error) {
35
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") {
36
+ throw new Error(m.tokensFileMissing({ file }));
37
+ }
38
+ // 기준이 되는 파일이 깨져 있으면 무엇도 판정할 수 없다. 어디가 깨졌는지 알려준다.
39
+ throw new Error(
40
+ m.tokensUnreadable({
41
+ file,
42
+ line: error.line ?? 1,
43
+ column: error.column ?? 1,
44
+ reason: error.reason ?? error.message,
45
+ }),
46
+ );
47
+ }
42
48
  }
@@ -1,16 +1,24 @@
1
- /** 클래스 교체 제안을 쓰는 규칙이 meta.messages 에 넣는 메시지. */
2
- export const REPLACE_MESSAGES = { replace: "{{className}}(으)로 바꾸기" };
1
+ import { messages, resolveLang } from "../messages.js";
2
+
3
+ /** 규칙의 문장은 실행할 때 언어에 맞춰 만든다. meta.messages 에는 자리만 둔다. */
4
+ export const TEXT = "{{text}}";
5
+
6
+ /** 규칙이 쓸 언어의 문장들. settings.designsnitch.lang, 환경 변수, 영어 순으로 정한다. */
7
+ export function ruleMessages(context) {
8
+ return messages(resolveLang(context.settings?.designsnitch?.lang));
9
+ }
3
10
 
4
11
  /**
5
12
  * 찾은 클래스를 후보 클래스로 바꾸는 제안 목록을 만든다.
6
13
  * 후보가 하나여도 자동 수정이 아니라 제안으로 둔다. 무엇으로 바꿀지는 쓰는 쪽이 정한다.
7
14
  * @param {[number, number]} range 찾은 클래스의 소스 범위
8
15
  * @param {string[]} classNames
16
+ * @param {ReturnType<typeof messages>} m
9
17
  */
10
- export function suggestClasses(range, classNames) {
18
+ export function suggestClasses(range, classNames, m) {
11
19
  return classNames.map((className) => ({
12
20
  messageId: "replace",
13
- data: { className },
21
+ data: { text: m.replaceWith({ className }) },
14
22
  fix: (fixer) => fixer.replaceTextRange(range, className),
15
23
  }));
16
24
  }