designsnitch 0.2.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 +139 -34
- package/README.md +159 -55
- package/bin/designsnitch.js +51 -17
- package/package.json +4 -4
- package/skills/designsnitch-check/SKILL.md +38 -14
- package/skills/designsnitch-eslint/SKILL.md +2 -0
- package/skills/designsnitch-hooks/SKILL.md +83 -8
- package/skills/designsnitch-palette/SKILL.md +8 -6
- package/skills/designsnitch-setup/SKILL.md +22 -2
- package/src/check.js +155 -45
- package/src/cli.js +33 -36
- package/src/colors.js +4 -2
- package/src/config.js +62 -26
- package/src/core/classes.js +12 -0
- package/src/core/css.js +4 -3
- package/src/core/tokens.js +66 -12
- package/src/format.js +29 -41
- package/src/hook.js +79 -20
- package/src/install.js +104 -46
- package/src/messages.js +299 -0
- package/src/rules/color-unknown.js +18 -8
- package/src/rules/color-use-token.js +39 -17
- package/src/rules/load-tokens.js +29 -24
- package/src/rules/suggest.js +12 -4
- package/src/rules/unchecked-hex.js +25 -0
- package/src/rules/use-ds-component.js +36 -12
- package/src/rules/visit-style.js +64 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: designsnitch-hooks
|
|
3
|
-
description: Register designsnitch as a hook of the coding agent, so the agent is told about design system errors right after it edits a file and cannot finish while errors it can fix remain. Use as part of setting up designsnitch, or when the user asks to make AI-written code follow the design system automatically.
|
|
3
|
+
description: Register designsnitch as a hook of the coding agent (Claude Code, Codex, Gemini CLI or Grok Build), so the agent is told about design system errors right after it edits a file and cannot finish while errors it can fix remain. Use as part of setting up designsnitch, or when the user asks to make AI-written code follow the design system automatically.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# designsnitch-hooks
|
|
@@ -11,7 +11,7 @@ A skill is advice: an agent may or may not follow it. A hook is run by the agent
|
|
|
11
11
|
|
|
12
12
|
## What the hook does
|
|
13
13
|
|
|
14
|
-
`npx designsnitch hook` checks only the files the agent just changed.
|
|
14
|
+
`npx designsnitch hook` checks only the files the agent just changed, and blocks only errors the change added. It compares each file with its version in git `HEAD`: errors that were already there do not block.
|
|
15
15
|
|
|
16
16
|
| When it runs | What happens |
|
|
17
17
|
| --- | --- |
|
|
@@ -20,7 +20,7 @@ A skill is advice: an agent may or may not follow it. A hook is run by the agent
|
|
|
20
20
|
|
|
21
21
|
- Warnings never block.
|
|
22
22
|
- Errors that need a person's decision (`ask`) are reported after an edit, but do not stop the agent from finishing. The agent has to stop in order to ask.
|
|
23
|
-
-
|
|
23
|
+
- Files the agent did not touch are left alone. Errors that were already in the files it touched are reported only if the change added more of them.
|
|
24
24
|
|
|
25
25
|
## 1. Register the hook in Claude Code
|
|
26
26
|
|
|
@@ -54,17 +54,92 @@ If you need to do it by hand, this is what it adds to `.claude/settings.json`.
|
|
|
54
54
|
|
|
55
55
|
`.claude/settings.json` is shared with the team through git, so the hook applies to everyone who uses Claude Code in this project. If the user wants the hook only for themselves, do not run the installer: add the entries above to `.claude/settings.local.json` by hand.
|
|
56
56
|
|
|
57
|
-
## 2.
|
|
57
|
+
## 2. Register the hook in Codex
|
|
58
58
|
|
|
59
|
-
|
|
59
|
+
```sh
|
|
60
|
+
npx designsnitch install --agent codex
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
It adds the hook to `.codex/hooks.json` and copies the skills into `.agents/skills`. Use `--agent all` to set up every supported agent together.
|
|
64
|
+
|
|
65
|
+
```json
|
|
66
|
+
{
|
|
67
|
+
"hooks": {
|
|
68
|
+
"PostToolUse": [
|
|
69
|
+
{
|
|
70
|
+
"matcher": "apply_patch",
|
|
71
|
+
"hooks": [{ "type": "command", "command": "npx designsnitch hook", "timeout": 60 }]
|
|
72
|
+
}
|
|
73
|
+
],
|
|
74
|
+
"Stop": [
|
|
75
|
+
{
|
|
76
|
+
"hooks": [{ "type": "command", "command": "npx designsnitch hook", "timeout": 60 }]
|
|
77
|
+
}
|
|
78
|
+
]
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Two things are different in Codex. Tell the user about both.
|
|
84
|
+
|
|
85
|
+
- **The hook does not run until the user approves it.** Codex runs project hooks only in a project the user has trusted, and only hooks the user has approved. You cannot do this for them. Ask the user to open Codex in the project and approve when it asks.
|
|
86
|
+
- **Codex often edits files with shell commands, which the `apply_patch` matcher does not see.** Those edits are still caught when Codex is about to finish: the `Stop` hook checks every file git reports as changed.
|
|
87
|
+
|
|
88
|
+
## 3. Register the hook in Gemini CLI
|
|
89
|
+
|
|
90
|
+
```sh
|
|
91
|
+
npx designsnitch install --agent gemini
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
It adds the hook to `.gemini/settings.json` and copies the skills into `.agents/skills`, which Gemini CLI reads as workspace skills. Gemini CLI uses different event names, and its `timeout` is in milliseconds.
|
|
95
|
+
|
|
96
|
+
```json
|
|
97
|
+
{
|
|
98
|
+
"hooks": {
|
|
99
|
+
"AfterTool": [
|
|
100
|
+
{
|
|
101
|
+
"matcher": "write_file|replace",
|
|
102
|
+
"hooks": [{ "name": "designsnitch", "type": "command", "command": "npx designsnitch hook", "timeout": 60000 }]
|
|
103
|
+
}
|
|
104
|
+
],
|
|
105
|
+
"AfterAgent": [
|
|
106
|
+
{
|
|
107
|
+
"hooks": [{ "name": "designsnitch", "type": "command", "command": "npx designsnitch hook", "timeout": 60000 }]
|
|
108
|
+
}
|
|
109
|
+
]
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
- `AfterTool` runs after `write_file` or `replace`. Exit code 2 replaces the tool's result with the errors, and the turn continues.
|
|
115
|
+
- `AfterAgent` runs when Gemini CLI is about to answer. Exit code 2 rejects the answer and makes it try again with the errors as feedback. `stop_hook_active` keeps it from looping.
|
|
116
|
+
|
|
117
|
+
Tell the user that Gemini CLI warns before it runs a new project hook, and that they need to allow it. If they have turned on folder trust, they also need to trust the folder. This setup follows the official Gemini CLI documentation and has not been tested with Gemini CLI. If the user reports that the hook does not fire, check that the installed Gemini CLI version supports hooks.
|
|
118
|
+
|
|
119
|
+
## 4. Register the hook in Grok Build
|
|
120
|
+
|
|
121
|
+
```sh
|
|
122
|
+
npx designsnitch install --agent grok
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
It writes `.grok/hooks/designsnitch.json` with the same `PostToolUse` and `Stop` hooks as Claude Code (`timeout` in seconds), and copies the skills into `.grok/skills`. Grok Build sends the hook its input in camelCase (`hookEventName`, `toolInput`), which `designsnitch hook` understands.
|
|
126
|
+
|
|
127
|
+
Tell the user two things.
|
|
128
|
+
|
|
129
|
+
- **The hook does not run until the project is trusted.** Ask the user to run `/hooks-trust` in Grok Build, or to start it with `--trust`.
|
|
130
|
+
- **Grok Build may report the errors without stopping.** Its documentation calls `PreToolUse` the only blocking event and does not say what exit code 2 does after a tool or at the end of a turn. This setup follows the official xAI documentation and has not been tested with Grok Build.
|
|
131
|
+
|
|
132
|
+
## 5. Other agents
|
|
133
|
+
|
|
134
|
+
`designsnitch hook` does not depend on a particular agent. It reads an optional JSON object from stdin:
|
|
60
135
|
|
|
61
136
|
- `tool_input.file_path`: the file that was just edited. Without it, the files that git reports as changed are checked.
|
|
62
|
-
- `hook_event_name
|
|
137
|
+
- `hook_event_name` (or `hookEventName`): `Stop`, `SubagentStop` or `AfterAgent` means the agent is about to finish.
|
|
63
138
|
- `stop_hook_active`: when true, the hook does not block again.
|
|
64
139
|
|
|
65
140
|
It exits with 2 and writes what to fix to stderr when it blocks, and exits with 0 otherwise. If the agent in use supports command hooks with these conventions, register the same command there. Check that agent's hook documentation for the file and the event names, and tell the user if you could not confirm that it works.
|
|
66
141
|
|
|
67
|
-
##
|
|
142
|
+
## 6. Verify
|
|
68
143
|
|
|
69
144
|
Make the hook fire once.
|
|
70
145
|
|
|
@@ -79,7 +154,7 @@ It should print the error and exit with 2.
|
|
|
79
154
|
|
|
80
155
|
3. Undo the test change and run it again. It should print nothing and exit with 0.
|
|
81
156
|
|
|
82
|
-
##
|
|
157
|
+
## 7. Tell the user
|
|
83
158
|
|
|
84
159
|
Say which file you changed and what the hook will now do. Mention that it only looks at files the agent changes, so existing violations elsewhere stay until someone cleans them up with the `designsnitch-check` skill.
|
|
85
160
|
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: designsnitch-palette
|
|
3
|
-
description: Create color tokens for a React/Next.js + Tailwind project that has none, based on the colors its code already uses. Use when a project has no color tokens or palette, when `designsnitch check` reports that no color token could be read, or when the user asks to derive a color palette or color tokens from existing code.
|
|
3
|
+
description: Create color tokens for a React/Next.js + Tailwind project that has none or too few, based on the colors its code already uses. Use when a project has no color tokens or palette, when `designsnitch check` reports that no color token could be read, when most colors in the code have no token (many color-unknown warnings), or when the user asks to derive a color palette or color tokens from existing code.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# designsnitch-palette
|
|
7
7
|
|
|
8
|
-
Some projects have no color tokens: colors are written straight into the code as `bg-[#3B82F6]`, `text-gray-700` or `style={{ color: "#3B82F6" }}`. designsnitch has nothing to check such code against. This skill turns the colors the code already uses into a set of tokens.
|
|
8
|
+
Some projects have no color tokens: colors are written straight into the code as `bg-[#3B82F6]`, `text-gray-700` or `style={{ color: "#3B82F6" }}`. designsnitch has nothing to check such code against. Others have a few tokens, while most colors in the code have none, and every one of those is a warning. This skill turns the colors the code already uses into a set of tokens, or fills the gaps next to the tokens that exist.
|
|
9
9
|
|
|
10
10
|
The CLI collects the colors. You analyze them and propose tokens. The user decides. Nothing is written before the user approves, because the tokens become the standard all UI code is judged against.
|
|
11
11
|
|
|
@@ -46,7 +46,7 @@ This works without a config file. Pass paths to limit it to part of the project.
|
|
|
46
46
|
- `colors` are hex colors, most used first. `utilities` counts uses per Tailwind utility (`bg-[#484646]` counts under `bg`). `literals` counts strings that are a hex color on their own, such as inline styles and chart options. `properties` counts uses per CSS property in `.css` files.
|
|
47
47
|
- `palette` are colors from Tailwind's default palette used by name, such as `text-gray-700`.
|
|
48
48
|
- `examples` gives a few locations, each in a different file. Open them when you need to see how a color is used.
|
|
49
|
-
- If a config file exists, each color also has `tokens`: the tokens that already have this value. Colors with a non-empty `tokens` are already covered. Work on the rest.
|
|
49
|
+
- If a config file exists, each color also has `tokens`: the tokens that already have this value. Colors with a non-empty `tokens` are already covered. Work on the rest. A color one step away from an existing token is a near duplicate of that token (see below), not a new color.
|
|
50
50
|
|
|
51
51
|
## 2. Analyze
|
|
52
52
|
|
|
@@ -58,6 +58,8 @@ Go through `colors` from the top and sort each color into one of these.
|
|
|
58
58
|
|
|
59
59
|
**The long tail.** It is used once or twice. Do not give it a token by default. List these for the user.
|
|
60
60
|
|
|
61
|
+
**A scattered palette.** Sometimes most colors are long tail: dozens of grays, each used once or twice and each a little different, such as `#929b93`, `#8e978f` and `#919a92`. This is common in code an AI wrote one screen at a time. Proposing tokens only for the few colors used most covers almost nothing. Group the colors instead: put colors that look the same at a glance in one group, and treat each group as one color with the summed uses. If an existing token sits in a group, the group belongs to that token. Then sort the groups as above. Tell the user that merging a group changes what is rendered by a small amount, show the spread of each group (its lightest and darkest value), and let them decide group by group.
|
|
62
|
+
|
|
61
63
|
Then work out what each color of its own is for. `utilities` and `properties` show this.
|
|
62
64
|
|
|
63
65
|
| Mostly used with | Likely role |
|
|
@@ -80,14 +82,14 @@ Show the user a proposal before writing anything.
|
|
|
80
82
|
|
|
81
83
|
Naming:
|
|
82
84
|
|
|
83
|
-
- If the project already has CSS variables or a naming habit, follow it.
|
|
85
|
+
- If the project already has tokens, CSS variables or a naming habit, follow it. New tokens sit next to the existing ones and use the same pattern.
|
|
84
86
|
- Otherwise name a color by its role when it has a clear one (`--color-text-primary`, `--color-border-default`, `--color-surface`), and by a scale when it is a general color (`--color-primary-500`, `--color-neutral-200`).
|
|
85
87
|
- Every token starts with `--color-`. Tailwind turns `--color-text-primary` into classes such as `text-text-primary` and `bg-text-primary`.
|
|
86
88
|
- Do not reuse a name from Tailwind's default palette, such as `--color-blue-500`, unless the user wants to override that color.
|
|
87
89
|
|
|
88
90
|
With the table, tell the user:
|
|
89
91
|
|
|
90
|
-
- How much the proposed tokens cover: the share of all uses, for example "12 tokens cover 81% of uses".
|
|
92
|
+
- How much the proposed tokens cover: the share of all uses, for example "12 tokens cover 81% of uses". If the share is small, say why, and check whether the colors are scattered (see above) before handing over a proposal that covers little.
|
|
91
93
|
- The near duplicates you want to merge, each with both values and their use counts.
|
|
92
94
|
- The long tail you left out.
|
|
93
95
|
- The default palette colors in use, and the question of whether to keep them.
|
|
@@ -130,7 +132,7 @@ Tell the user what the first check found. Every place that writes a tokenized co
|
|
|
130
132
|
Two kinds of use stay as they are:
|
|
131
133
|
|
|
132
134
|
- Near duplicates the user chose to merge still have their old value in the code. They show up as `color-unknown` warnings. Replacing them changes what is rendered, so do it only for the merges the user approved.
|
|
133
|
-
- Hex colors in
|
|
135
|
+
- Hex colors in strings other than classes and inline styles, such as theme objects, and default palette classes are not flagged by the check. The check counts the former in `unchecked`.
|
|
134
136
|
|
|
135
137
|
## What not to do
|
|
136
138
|
|
|
@@ -53,6 +53,14 @@ Read the files in that directory and find the components whose root element is a
|
|
|
53
53
|
|
|
54
54
|
Leave out components that only happen to contain a raw tag deep inside, such as a modal that has a close button. List the components a developer should reach for instead of writing the tag.
|
|
55
55
|
|
|
56
|
+
Open each component before you list it, and check that it fits the ordinary uses of the tag. A component built for one look or one kind of content does not replace the tag in general. An `IconButton` that sizes and styles itself for a single icon is not what a text button should become, and listing it tells every `<button>` with text to switch to it. If the component can only replace some uses, and `when` cannot tell those uses apart by an attribute value, leave it out and tell the user why. Listing a wrong replacement is worse than listing none: it turns correct code into errors.
|
|
57
|
+
|
|
58
|
+
Check which variants of the tag each component covers. An `Input` built for text fields does not replace `<input type="file">`, `<input type="range">` or a checkbox. When a component covers only some variants, write it with `when`, listing the attribute values it covers (`null` means the attribute is absent). Read the component's props and its root element to decide. If you cannot tell, leave `when` out and tell the user which variants you were unsure about.
|
|
59
|
+
|
|
60
|
+
```json
|
|
61
|
+
"input": { "component": "Input", "when": { "type": ["text", "email", "password", null] } }
|
|
62
|
+
```
|
|
63
|
+
|
|
56
64
|
## 4. Write the file
|
|
57
65
|
|
|
58
66
|
```json
|
|
@@ -62,13 +70,21 @@ Leave out components that only happen to contain a raw tag deep inside, such as
|
|
|
62
70
|
"path": "./src/components/ui",
|
|
63
71
|
"replaces": {
|
|
64
72
|
"button": ["SolidButton", "GlassButton", "IconButton"],
|
|
65
|
-
"input": "Input"
|
|
73
|
+
"input": { "component": "Input", "when": { "type": ["text", "email", "password", null] } }
|
|
66
74
|
}
|
|
67
75
|
}
|
|
68
76
|
}
|
|
69
77
|
```
|
|
70
78
|
|
|
71
|
-
Paths are relative to the project root.
|
|
79
|
+
Paths are relative to the directory of the config file. Put the file in the project root unless the user asks otherwise.
|
|
80
|
+
|
|
81
|
+
If two or more tokens share one value, every hex color with that value will need a person's decision. When it is clear which family should win, for example a project whose semantic tokens (`--color-brand-*`) are built on raw scale tokens (`--color-blue-*`), suggest the object form of `tokens` to the user. `prefer` picks a token family when several match, and `exclude` drops tokens that should not be used at all, such as a legacy set. Only add them after the user agrees.
|
|
82
|
+
|
|
83
|
+
```json
|
|
84
|
+
"tokens": { "file": "./src/app/globals.css", "prefer": ["--color-brand-"], "exclude": ["--color-legacy-*"] }
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Messages are in English by default. If the user works in Korean, add `"lang": "ko"` to the file so that the CLI, the ESLint plugin and the hook speak Korean.
|
|
72
88
|
|
|
73
89
|
## 5. Verify
|
|
74
90
|
|
|
@@ -82,9 +98,12 @@ Look at `designSystem` and `problems` in the result.
|
|
|
82
98
|
- `designSystem.components` should match the number of components you listed.
|
|
83
99
|
- `problems` should be empty.
|
|
84
100
|
- Exit code 2 with a message about a missing path means a path in the config is wrong.
|
|
101
|
+
- Every `use-ds-component` error should point to a component that really fits that place. Open two or three of them. If a component keeps being suggested where it does not belong, go back to step 3.
|
|
85
102
|
|
|
86
103
|
Fix the config until these hold. Ignore the violations for now: fixing them is the job of the `designsnitch-check` skill.
|
|
87
104
|
|
|
105
|
+
Then look at how many colors have no token. Run `npx designsnitch colors --format json` and count the colors whose `tokens` is empty, and their uses. If the tokens cover only a small part of the colors in use, for example a handful of tokens against dozens of colors with no token, the project does not really have a palette yet. Do not leave this as a pile of warnings. Follow the `designsnitch-palette` skill: it proposes tokens for the colors that have none, next to the ones that exist.
|
|
106
|
+
|
|
88
107
|
## 6. Wire the ESLint plugin
|
|
89
108
|
|
|
90
109
|
Follow the `designsnitch-eslint` skill now. It puts the rules into the project's ESLint, and installs ESLint if the project has none. Setup is not finished until this is done: the config file alone does not block anything.
|
|
@@ -105,3 +124,4 @@ If you were unsure about a choice, say so and give the alternative. For example,
|
|
|
105
124
|
- Do not edit the token CSS without the user's agreement.
|
|
106
125
|
- Do not change an existing config file without asking.
|
|
107
126
|
- Do not start fixing violations as part of setup.
|
|
127
|
+
- Do not list a component as a replacement for a tag without reading it.
|
package/src/check.js
CHANGED
|
@@ -1,13 +1,21 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { replacementNames, tokenSettings } from "./config.js";
|
|
4
|
+
import { findArbitraryColors, tokenToClass } from "./core/classes.js";
|
|
3
5
|
import { normalizeHex } from "./core/color.js";
|
|
4
6
|
import { findCssColors } from "./core/css.js";
|
|
7
|
+
import { cssColorPrefixes, recommendColorCandidate, selectColorTokens, utilityColorPrefixes } from "./core/tokens.js";
|
|
5
8
|
import { createEngine } from "./engine.js";
|
|
6
9
|
import { splitPaths } from "./files.js";
|
|
7
10
|
import plugin from "./index.js";
|
|
11
|
+
import { messages, resolveLang } from "./messages.js";
|
|
8
12
|
import { loadTokens } from "./rules/load-tokens.js";
|
|
13
|
+
import uncheckedHex from "./rules/unchecked-hex.js";
|
|
9
14
|
|
|
10
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;
|
|
11
19
|
|
|
12
20
|
/**
|
|
13
21
|
* @typedef {object} Violation
|
|
@@ -21,87 +29,128 @@ const RULE_PREFIX = "designsnitch/";
|
|
|
21
29
|
* @property {string} message
|
|
22
30
|
* @property {string} found 위반한 코드 조각 (클래스나 태그 이름)
|
|
23
31
|
* @property {string[]} candidates 대신 쓸 클래스나 컴포넌트. 없으면 빈 배열
|
|
32
|
+
* @property {string | null} recommended 바로 바꿀 후보 또는 역할에 맞는 유일한 후보
|
|
24
33
|
* @property {"replace" | "ask" | "repair"} action 이 위반을 어떻게 다룰지.
|
|
25
|
-
* replace: found 를 candidates 의 값으로
|
|
26
|
-
* ask: 사람이 정해야 한다 (
|
|
34
|
+
* replace: found 를 candidates 의 값으로 바꿀 수 있다 (교체가 안전하고 후보가 하나뿐인 오류)
|
|
35
|
+
* ask: 사람이 정해야 한다 (교체가 확실하지 않거나 후보가 하나가 아닌 경우)
|
|
27
36
|
* repair: 파일을 읽지 못했다. 문법 오류부터 고쳐야 한다
|
|
28
37
|
*/
|
|
29
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
|
+
|
|
30
52
|
/**
|
|
31
53
|
* 프로젝트를 검사한다. 프로젝트의 ESLint 설정은 쓰지 않고 designsnitch 규칙만 실행한다.
|
|
32
54
|
* @param {object} options
|
|
33
55
|
* @param {string} options.cwd 프로젝트 디렉터리
|
|
34
56
|
* @param {ReturnType<typeof import("./config.js").loadConfig>} options.config
|
|
35
57
|
* @param {string[]} [options.paths] 검사할 파일이나 디렉터리 (cwd 기준)
|
|
58
|
+
* @param {"en" | "ko"} [options.lang] 문장의 언어. 없으면 설정의 lang, 환경 변수, 영어 순으로 정한다
|
|
59
|
+
* @param {string} [options.sourceCwd] 임시 복사본을 검사할 때 원본 프로젝트 디렉터리
|
|
36
60
|
* @returns {Promise<{
|
|
37
61
|
* designSystem: { colorTokens: number, components: number, replacedTags: number },
|
|
38
62
|
* problems: string[],
|
|
39
63
|
* next: string[],
|
|
40
64
|
* summary: { files: number, errors: number, warnings: number },
|
|
41
65
|
* violations: Violation[],
|
|
66
|
+
* decisions: Decision[],
|
|
42
67
|
* }>} designSystem 은 설정에서 읽어 낸 것의 개수, problems 는 결과를 믿기 어렵게 만드는 설정 문제,
|
|
43
68
|
* next 는 이 결과를 받은 에이전트가 순서대로 할 일
|
|
44
69
|
*/
|
|
45
|
-
export async function check({ cwd, config, paths = ["."] }) {
|
|
46
|
-
|
|
70
|
+
export async function check({ cwd, config, paths = ["."], lang, sourceCwd = cwd }) {
|
|
71
|
+
lang = resolveLang(lang, config.lang);
|
|
72
|
+
const m = messages(lang);
|
|
73
|
+
const root = path.resolve(sourceCwd, config.root ?? ".");
|
|
74
|
+
// 규칙도 같은 언어를 쓰도록 설정에 실어 보낸다.
|
|
75
|
+
const settings = { designsnitch: { ...config, root, lang } };
|
|
47
76
|
// 설정에 문제가 있으면 파일을 검사하기 전에 알린다.
|
|
48
77
|
const tokens = loadTokens(settings, cwd);
|
|
49
78
|
if (config.components) {
|
|
50
|
-
const dir = path.resolve(
|
|
79
|
+
const dir = path.resolve(root, config.components.path);
|
|
51
80
|
if (!fs.existsSync(dir)) {
|
|
52
|
-
throw new Error(
|
|
81
|
+
throw new Error(m.componentsDirMissing({ dir }));
|
|
53
82
|
}
|
|
54
83
|
}
|
|
55
84
|
const designSystem = describeDesignSystem(tokens, config);
|
|
56
85
|
const problems = [];
|
|
57
86
|
if (designSystem.colorTokens === 0) {
|
|
58
|
-
problems.push(
|
|
59
|
-
`색 토큰을 하나도 읽지 못했습니다: ${config.tokens}. ` +
|
|
60
|
-
"--color-* 변수의 값이 hex이거나 var()로 hex를 가리켜야 읽을 수 있습니다. " +
|
|
61
|
-
'지금은 모든 hex가 "토큰에 없음" 경고로 나옵니다.',
|
|
62
|
-
);
|
|
87
|
+
problems.push(m.noColorTokens({ tokens: tokenSettings(config.tokens).file }));
|
|
63
88
|
}
|
|
64
89
|
|
|
65
90
|
const { scriptPaths, cssFiles } = splitPaths(cwd, paths);
|
|
66
91
|
|
|
67
92
|
// JS, TS 는 ESLint 로 규칙을 실행하고, CSS 는 직접 읽는다.
|
|
68
|
-
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
|
+
});
|
|
69
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 };
|
|
70
108
|
const scriptViolations = results.flatMap((result) => {
|
|
71
109
|
const file = path.relative(cwd, result.filePath).split(path.sep).join("/");
|
|
72
110
|
return result.messages
|
|
73
111
|
.filter(isOurs)
|
|
74
112
|
.map((message) => toViolation(file, result.source, message, config));
|
|
75
113
|
});
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
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
|
+
});
|
|
79
120
|
|
|
80
|
-
const
|
|
121
|
+
const findings = [...scriptViolations, ...cssViolations]
|
|
81
122
|
.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column)
|
|
82
|
-
.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);
|
|
83
130
|
|
|
84
131
|
return {
|
|
85
132
|
designSystem,
|
|
86
133
|
problems,
|
|
87
|
-
next: nextSteps(designSystem, violations),
|
|
134
|
+
next: nextSteps(designSystem, violations, lang, decisions),
|
|
88
135
|
summary: {
|
|
89
136
|
files: results.length + cssFiles.length,
|
|
90
137
|
errors: violations.filter((v) => v.severity === "error").length,
|
|
91
138
|
warnings: violations.filter((v) => v.severity === "warning").length,
|
|
92
139
|
},
|
|
93
140
|
violations,
|
|
141
|
+
decisions,
|
|
142
|
+
unchecked,
|
|
94
143
|
};
|
|
95
144
|
}
|
|
96
145
|
|
|
97
146
|
/**
|
|
98
147
|
* CSS 파일 하나의 hex 색을 토큰과 비교한다. 대체 후보는 var(--토큰) 이다.
|
|
99
|
-
* @returns {Violation[]}
|
|
148
|
+
* @returns {(Omit<Violation, "action" | "recommended"> & { recommended?: string | null, messageId?: string })[]}
|
|
100
149
|
*/
|
|
101
|
-
function checkCss(file, source,
|
|
150
|
+
function checkCss(file, source, tokens, m, options) {
|
|
102
151
|
let colors;
|
|
103
152
|
try {
|
|
104
|
-
colors = findCssColors(source);
|
|
153
|
+
colors = findCssColors(source, options);
|
|
105
154
|
} catch (error) {
|
|
106
155
|
const at = { line: error.line ?? 1, column: error.column ?? 1 };
|
|
107
156
|
return [
|
|
@@ -122,8 +171,11 @@ function checkCss(file, source, colorTokens) {
|
|
|
122
171
|
return colors
|
|
123
172
|
.filter((color) => !color.disabled)
|
|
124
173
|
.map(({ value, prop, disabled, ...location }) => {
|
|
125
|
-
const
|
|
174
|
+
const prefixes = cssColorPrefixes(prop);
|
|
175
|
+
const tokenNames = selectColorTokens(tokens.colors.get(normalizeHex(value)) ?? [], tokens.prefer, prefixes);
|
|
126
176
|
const candidates = tokenNames.map((name) => `var(${name})`);
|
|
177
|
+
const recommendedToken = recommendColorCandidate(tokenNames, prefixes);
|
|
178
|
+
const messageId = tokenNames.some((name) => tokens.themed.has(name)) ? "useTokenThemed" : "useToken";
|
|
127
179
|
return {
|
|
128
180
|
file,
|
|
129
181
|
...location,
|
|
@@ -131,57 +183,106 @@ function checkCss(file, source, colorTokens) {
|
|
|
131
183
|
? {
|
|
132
184
|
rule: "color-use-token",
|
|
133
185
|
severity: "error",
|
|
134
|
-
|
|
186
|
+
messageId,
|
|
187
|
+
message: m[messageId]({
|
|
188
|
+
found: value,
|
|
189
|
+
tokens: tokenNames.join(", "),
|
|
190
|
+
candidates: candidates.join(", "),
|
|
191
|
+
}),
|
|
135
192
|
}
|
|
136
193
|
: {
|
|
137
194
|
rule: "color-unknown",
|
|
138
195
|
severity: "warning",
|
|
139
|
-
message:
|
|
196
|
+
message: m.unknownCssColor({ value }),
|
|
140
197
|
}),
|
|
141
198
|
found: value,
|
|
142
199
|
candidates,
|
|
200
|
+
recommended: recommendedToken ? `var(${recommendedToken})` : null,
|
|
143
201
|
};
|
|
144
202
|
});
|
|
145
203
|
}
|
|
146
204
|
|
|
147
|
-
function actionFor({ rule, severity, candidates }) {
|
|
205
|
+
function actionFor({ rule, severity, candidates }, messageId) {
|
|
148
206
|
if (rule === "parse-error") return "repair";
|
|
207
|
+
if (messageId === "useComponentAsk" || messageId === "useTokenThemed") return "ask";
|
|
149
208
|
return severity === "error" && candidates.length === 1 ? "replace" : "ask";
|
|
150
209
|
}
|
|
151
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
|
+
|
|
152
257
|
/**
|
|
153
258
|
* 결과를 받은 에이전트가 무엇부터 해야 하는지를 순서대로 적는다.
|
|
154
259
|
* @param {{ colorTokens: number }} designSystem
|
|
155
260
|
* @param {Violation[]} violations action 이 붙은 위반들
|
|
261
|
+
* @param {"en" | "ko"} [lang]
|
|
262
|
+
* @param {Decision[]} [decisions] check 결과의 결정 목록. 훅은 위반만 보여 준다
|
|
156
263
|
* @returns {string[]}
|
|
157
264
|
*/
|
|
158
|
-
export function nextSteps(designSystem, violations) {
|
|
265
|
+
export function nextSteps(designSystem, violations, lang, decisions) {
|
|
266
|
+
const m = messages(lang);
|
|
159
267
|
const noColorTokens = designSystem.colorTokens === 0;
|
|
160
268
|
// 색 토큰이 없으면 색 위반은 하나씩 다룰 일이 아니라 토큰을 정하는 일 하나로 묶인다.
|
|
161
269
|
const actionable = noColorTokens
|
|
162
270
|
? violations.filter((v) => !v.rule.startsWith("color-"))
|
|
163
271
|
: violations;
|
|
164
272
|
const count = (action) => actionable.filter((v) => v.action === action).length;
|
|
165
|
-
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;
|
|
166
277
|
const steps = [];
|
|
167
278
|
|
|
168
|
-
if (noColorTokens)
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
if (repair > 0) steps.push(`action이 repair인 ${repair}건은 그 파일의 문법 오류부터 고치세요.`);
|
|
174
|
-
if (replace > 0) {
|
|
175
|
-
steps.push(`action이 replace인 ${replace}건은 found를 candidates의 값으로 바꾸세요.`);
|
|
176
|
-
}
|
|
177
|
-
if (ask > 0) {
|
|
178
|
-
steps.push(
|
|
179
|
-
`action이 ask인 ${ask}건은 바꾸지 말고 사용자에게 물으세요. 물을 때는 \`designsnitch colors\`로 그 색이 몇 곳에서 어떻게 쓰이는지 확인해서 근거로 함께 주세요.`,
|
|
180
|
-
);
|
|
181
|
-
}
|
|
182
|
-
if (repair + replace > 0) steps.push("고친 뒤 같은 명령을 다시 실행하세요.");
|
|
279
|
+
if (noColorTokens) steps.push(m.nextNoTokens());
|
|
280
|
+
if (repair > 0) steps.push(m.nextRepair(repair));
|
|
281
|
+
if (replace > 0) steps.push(m.nextReplace(replace));
|
|
282
|
+
if (ask > 0) steps.push(decisions === undefined ? m.hookNextAsk(ask) : m.nextAsk(ask));
|
|
283
|
+
if (repair + replace > 0) steps.push(m.nextRerun());
|
|
183
284
|
|
|
184
|
-
return steps.length > 0 ? steps : [
|
|
285
|
+
return steps.length > 0 ? steps : [m.nextNone()];
|
|
185
286
|
}
|
|
186
287
|
|
|
187
288
|
function describeDesignSystem(tokens, config) {
|
|
@@ -189,7 +290,7 @@ function describeDesignSystem(tokens, config) {
|
|
|
189
290
|
const replaces = Object.values(config.components?.replaces ?? {});
|
|
190
291
|
return {
|
|
191
292
|
colorTokens: countNames(tokens.colors),
|
|
192
|
-
components: new Set(replaces.
|
|
293
|
+
components: new Set(replaces.flatMap(replacementNames)).size,
|
|
193
294
|
replacedTags: replaces.length,
|
|
194
295
|
};
|
|
195
296
|
}
|
|
@@ -212,7 +313,14 @@ function toViolation(file, source, message, config) {
|
|
|
212
313
|
let candidates = (message.suggestions ?? []).map((suggestion) => suggestion.fix.text);
|
|
213
314
|
if (rule === "use-ds-component") {
|
|
214
315
|
// 컴포넌트는 import 까지 바꿔야 해서 제안(자동 교체)이 없다. 설정에서 후보를 찾는다.
|
|
215
|
-
candidates =
|
|
316
|
+
candidates = replacementNames(config.components?.replaces?.[found]);
|
|
317
|
+
}
|
|
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);
|
|
216
324
|
}
|
|
217
325
|
|
|
218
326
|
return {
|
|
@@ -224,8 +332,10 @@ function toViolation(file, source, message, config) {
|
|
|
224
332
|
rule,
|
|
225
333
|
severity: message.severity === 2 ? "error" : "warning",
|
|
226
334
|
message: message.message,
|
|
335
|
+
messageId: message.messageId,
|
|
227
336
|
found,
|
|
228
337
|
candidates,
|
|
338
|
+
recommended,
|
|
229
339
|
};
|
|
230
340
|
}
|
|
231
341
|
|