@atom63/eslint-plugin 0.0.0-stage → 0.1.0-beta.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/LICENSE +27 -0
- package/README.md +75 -2
- package/bin/atom63-lint-baseline.mjs +34 -0
- package/generated/rule-data.json +5360 -0
- package/package.json +41 -3
- package/src/core/craft.mjs +450 -0
- package/src/core/escapes.mjs +149 -0
- package/src/core/warnings.mjs +101 -0
- package/src/index.mjs +90 -0
- package/src/lib/data.mjs +16 -0
- package/src/lib/define.mjs +109 -0
- package/src/lib/scans.mjs +10 -0
- package/src/rules/craft.mjs +76 -0
- package/src/rules/escapes.mjs +70 -0
- package/src/rules/no-deprecated-value.mjs +71 -0
- package/src/rules/warnings.mjs +28 -0
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@atom63/eslint-plugin",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-beta.0",
|
|
4
|
+
"description": "ESLint rules that keep code on the Atom63 design system: its components, tokens and contracts. Runs in ESLint 9+ and in Oxlint as a JS plugin.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/atom63/atom63-design-system.git",
|
|
9
|
+
"directory": "packages/eslint-plugin"
|
|
10
|
+
},
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": "./src/index.mjs",
|
|
17
|
+
"./core/craft": "./src/core/craft.mjs",
|
|
18
|
+
"./core/escapes": "./src/core/escapes.mjs"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"src",
|
|
22
|
+
"generated",
|
|
23
|
+
"bin",
|
|
24
|
+
"!src/**/*.test.mjs"
|
|
25
|
+
],
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"eslint": ">=9",
|
|
28
|
+
"typescript": ">=5"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"eslint": "10.15.0",
|
|
32
|
+
"oxlint": "1.96.0",
|
|
33
|
+
"typescript": "~6.0.3",
|
|
34
|
+
"typescript-eslint": "8.74.0"
|
|
35
|
+
},
|
|
36
|
+
"bin": {
|
|
37
|
+
"atom63-lint-baseline": "./bin/atom63-lint-baseline.mjs"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"test": "node --test \"src/**/*.test.mjs\" \"test/*.test.mjs\"",
|
|
41
|
+
"generate:data": "node scripts/generate-data.mjs",
|
|
42
|
+
"check:data": "node scripts/generate-data.mjs --check"
|
|
43
|
+
}
|
|
6
44
|
}
|
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Craft rules: mechanical checks for design-system source that a review can
|
|
3
|
+
* miss. Each rule reports `{ rule, match, line }`; check-craft.mjs compares the
|
|
4
|
+
* results against a committed baseline so existing debt can be paid down
|
|
5
|
+
* without letting new debt in.
|
|
6
|
+
*
|
|
7
|
+
* - `raw-color`: component styles take color from tokens. Flags literal colors
|
|
8
|
+
* in CSS declarations, including CSS named colors such as `white` (also
|
|
9
|
+
* inside `color-mix()`), and Tailwind palette or arbitrary color utilities in
|
|
10
|
+
* TS/TSX. `#0000` (the transparent "no shadow" idiom), `transparent` and
|
|
11
|
+
* `currentColor` pass, and so do masks, where a color only carries alpha.
|
|
12
|
+
* - `physical-properties`: spacing, text alignment, side borders, corner
|
|
13
|
+
* radii and `left`/`right` insets use logical directions
|
|
14
|
+
* (`inset-inline-start`/`-end`) so layouts mirror in right-to-left scripts.
|
|
15
|
+
* `top`/`bottom` do not mirror and pass. Padding that follows a physical
|
|
16
|
+
* safe-area inset (`env(safe-area-inset-left)`) passes.
|
|
17
|
+
* - `focus-visible`: focus styles follow `:focus-visible`, so a pointer press
|
|
18
|
+
* does not draw a keyboard focus ring. `:focus-within` passes, and so does a
|
|
19
|
+
* `:focus` rule or `focus:` utility that only removes the outline.
|
|
20
|
+
* - `focus-ring-outline`: focus rings are outlines. Flags a `box-shadow` that
|
|
21
|
+
* reads a focus-ring token (a custom property whose name contains
|
|
22
|
+
* `focus-ring`, or the shadcn `--ring` and `--sidebar-ring`) in any rule,
|
|
23
|
+
* and Tailwind `ring-*` utilities under a focus variant. Any later
|
|
24
|
+
* box-shadow on the element would replace a ring drawn that way, and
|
|
25
|
+
* forced-colors mode drops shadows. Elevation, border and separator shadows
|
|
26
|
+
* (such as the Avatar group ring) read no focus-ring token, so they pass.
|
|
27
|
+
* - `mode-branch`: component code never branches on light or dark mode; tokens
|
|
28
|
+
* and UIProvider resolve it. Flags CSS selectors that test `.dark`,
|
|
29
|
+
* `.light` or `[data-a63-mode]`, and Tailwind `dark:` variants in TS/TSX.
|
|
30
|
+
* - `unknown-token`: every `--a63-*` variable read without a fallback exists.
|
|
31
|
+
* Flags `var(--a63-…)` in CSS and TS/TSX, and Tailwind's `(--a63-…)`
|
|
32
|
+
* shorthand, when the name is neither a token in the manifest nor declared
|
|
33
|
+
* in the scanned source. A misspelled or invented name resolves to nothing,
|
|
34
|
+
* so the property silently drops. `var(--a63-…, fallback)` passes: a read
|
|
35
|
+
* with a fallback is a hook the caller may set. Runs only when the scanner
|
|
36
|
+
* is given the known names (`knownTokens`).
|
|
37
|
+
* - `token-role`: a token paints the role it was made for. Flags a fill (a
|
|
38
|
+
* `--a63-surface-*` token, the primary, neutral or danger action fill, a
|
|
39
|
+
* selected background) read as the text color, and a `--a63-text-*` token
|
|
40
|
+
* read as a background. In CSS that is `color` or `background` set to one
|
|
41
|
+
* `var()`; a `color-mix()` passes. In TS/TSX it is a `text-*` or `bg-*`
|
|
42
|
+
* utility whose Tailwind role (`roles`, from styles' tailwind/roles.json)
|
|
43
|
+
* maps to such a token, such as `text-primary`, and the arbitrary forms
|
|
44
|
+
* `text-(--a63-…)` and `text-[var(--a63-…)]`. A fill is contrast-checked
|
|
45
|
+
* against its own foreground, not against the page, so as text it can fail
|
|
46
|
+
* (the primary action fill is 2.9:1 on the dark page); the text roles are
|
|
47
|
+
* `--a63-text-*`, such as `--a63-text-accent` and `--a63-text-danger`.
|
|
48
|
+
* The danger action fill (`--a63-action-danger`, `-hover`) is held tighter:
|
|
49
|
+
* it keeps step 600 in dark mode (about 2.8:1 on the page), so any read of
|
|
50
|
+
* it in a text, border or outline color is flagged, `color-mix()` included,
|
|
51
|
+
* and so are `border-*`, `outline-*` and `decoration-*` utilities that map
|
|
52
|
+
* to it (`border-destructive`). Edges use `--a63-border-danger`, text
|
|
53
|
+
* `--a63-text-danger`, icons and accents `--a63-status-danger`; button,
|
|
54
|
+
* badge and menu fills still read it as a background.
|
|
55
|
+
* - `internal-token`: code outside the component packages (templates,
|
|
56
|
+
* examples, consumer apps) reads and writes only public tokens. Flags a read
|
|
57
|
+
* (`var(--a63-…)`, with or without a fallback, and Tailwind's `(--a63-…)`
|
|
58
|
+
* shorthand) or a write (`--a63-…:` in CSS, a style object or an arbitrary
|
|
59
|
+
* property utility) of a token the manifest marks `tier: internal`, and a
|
|
60
|
+
* write of a public token marked read-only (the brand ramp, which the brand
|
|
61
|
+
* axis derives). Internal tokens can change in any release; the public tier
|
|
62
|
+
* (styles' src/tokens/public-tier.json) is the stable surface. Names the
|
|
63
|
+
* manifest does not list (a file's own hooks) pass. Runs only when the
|
|
64
|
+
* scanner is given the tiers (`tiers`).
|
|
65
|
+
*
|
|
66
|
+
* Some physical directions are the point: a sheet docked to the left edge, or
|
|
67
|
+
* an optical nudge on a glyph that never mirrors. CSS rules scoped to
|
|
68
|
+
* `[data-side='left'|'right']` pass on their own. Anything else is exempted by
|
|
69
|
+
* a `craft-allow: <rule>` comment, with a reason, on the same line or the line
|
|
70
|
+
* above.
|
|
71
|
+
*/
|
|
72
|
+
|
|
73
|
+
const CSS_COMMENT = /\/\*[\s\S]*?\*\//g
|
|
74
|
+
const JS_COMMENT = /\/\*[\s\S]*?\*\/|(^|[^:\\])\/\/[^\n]*/g
|
|
75
|
+
|
|
76
|
+
const PALETTE =
|
|
77
|
+
'red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose|slate|gray|zinc|neutral|stone|black|white'
|
|
78
|
+
const COLOR_UTILITY = `(?:bg|text|border(?:-[trblxyse])?|ring|ring-offset|fill|stroke|from|via|to|outline|decoration|caret|accent|divide|placeholder|shadow)`
|
|
79
|
+
const PALETTE_UTILITY = new RegExp(`^${COLOR_UTILITY}-(?:${PALETTE})(?:-\\d{2,3})?(?:\\/\\d+)?$`)
|
|
80
|
+
const ARBITRARY_COLOR_UTILITY = new RegExp(
|
|
81
|
+
`^${COLOR_UTILITY}-\\[(?:#|rgba?\\(|hsla?\\(|oklch\\(|oklab\\()`
|
|
82
|
+
)
|
|
83
|
+
const PHYSICAL_UTILITY =
|
|
84
|
+
/^-?(?:ml|mr|pl|pr|scroll-ml|scroll-mr|scroll-pl|scroll-pr|border-l|border-r|rounded-l|rounded-r|rounded-tl|rounded-tr|rounded-bl|rounded-br)(?:-|$)|^text-(?:left|right)$/
|
|
85
|
+
const FOCUS_VARIANT = /(?:^|:)(?:group-|peer-)?focus:/
|
|
86
|
+
const FOCUS_RESET_UTILITY = /^(?:outline-none|outline-hidden|outline-0|ring-0|shadow-none)$/
|
|
87
|
+
const SAFE_AREA = /env\(safe-area-inset-(?:left|right)\)/
|
|
88
|
+
const FOCUS_RING_VARIANT = /focus/
|
|
89
|
+
const RING_UTILITY = /^ring(?:-|$)/
|
|
90
|
+
|
|
91
|
+
// The CSS named colors (CSS Color 4), matched as whole words so custom
|
|
92
|
+
// property names such as `--a63-text-white` and keywords such as `aqua` in
|
|
93
|
+
// `[data-a63-theme='aqua']` selectors are not colors here.
|
|
94
|
+
const CSS_NAMED_COLORS =
|
|
95
|
+
'lightgoldenrodyellow|mediumspringgreen|mediumaquamarine|mediumslateblue|mediumturquoise|mediumvioletred|blanchedalmond|cornflowerblue|darkolivegreen|lightslategray|lightslategrey|lightsteelblue|mediumseagreen|darkgoldenrod|darkslateblue|darkslategray|darkslategrey|darkturquoise|lavenderblush|lightseagreen|palegoldenrod|paleturquoise|palevioletred|rebeccapurple|antiquewhite|darkseagreen|lemonchiffon|lightskyblue|mediumorchid|mediumpurple|midnightblue|darkmagenta|deepskyblue|floralwhite|forestgreen|greenyellow|lightsalmon|lightyellow|navajowhite|saddlebrown|springgreen|yellowgreen|aquamarine|blueviolet|chartreuse|darkorange|darkorchid|darksalmon|darkviolet|dodgerblue|ghostwhite|lightcoral|lightgreen|mediumblue|papayawhip|powderblue|sandybrown|whitesmoke|aliceblue|burlywood|cadetblue|chocolate|darkgreen|darkkhaki|firebrick|gainsboro|goldenrod|indianred|lawngreen|lightblue|lightcyan|lightgray|lightgrey|lightpink|limegreen|mintcream|mistyrose|olivedrab|orangered|palegreen|peachpuff|rosybrown|royalblue|slateblue|slategray|slategrey|steelblue|turquoise|cornsilk|darkblue|darkcyan|darkgray|darkgrey|deeppink|honeydew|lavender|moccasin|seagreen|seashell|crimson|darkred|dimgray|dimgrey|fuchsia|hotpink|magenta|oldlace|skyblue|thistle|bisque|indigo|maroon|orange|orchid|purple|salmon|sienna|silver|tomato|violet|yellow|azure|beige|black|brown|coral|green|ivory|khaki|linen|olive|wheat|white|aqua|blue|cyan|gold|gray|grey|lime|navy|peru|pink|plum|snow|teal|red|tan'
|
|
96
|
+
const CSS_LITERAL_COLOR = new RegExp(
|
|
97
|
+
`#[0-9a-fA-F]{3,8}\\b|\\brgba?\\(|\\bhsla?\\(|\\boklch\\((?=\\s*[\\d.])|\\boklab\\((?=\\s*[\\d.])|(?<![\\w-])(?:${CSS_NAMED_COLORS})(?![\\w-])`,
|
|
98
|
+
'gi'
|
|
99
|
+
)
|
|
100
|
+
const CSS_PHYSICAL_PROPERTY =
|
|
101
|
+
/^(?:left|right)$|^(?:margin|padding|scroll-margin|scroll-padding)-(?:left|right)$|^border-(?:left|right)(?:-(?:width|style|color))?$|^border-(?:top|bottom)-(?:left|right)-radius$/
|
|
102
|
+
const CSS_FOCUS = /:focus(?![-\w])/
|
|
103
|
+
const CSS_FOCUS_RESET = /^(?:outline(?:-style)?\s*:\s*(?:none|0)|box-shadow\s*:\s*none)$/
|
|
104
|
+
const CSS_MASK_PROPERTY = /^(?:-webkit-)?mask(?:-image)?$/
|
|
105
|
+
const CSS_VAR_NAME = /var\(\s*(--[\w-]+)/g
|
|
106
|
+
const RING_TOKEN = /focus-ring|^--(?:sidebar-)?ring$/
|
|
107
|
+
const isRingToken = name => RING_TOKEN.test(name)
|
|
108
|
+
|
|
109
|
+
const CSS_MODE_SELECTOR = /(?<![\w-])\.(?:dark|light)(?![\w-])|\[data-a63-mode\b/
|
|
110
|
+
const MODE_VARIANT = /(?:^|:)dark:/
|
|
111
|
+
|
|
112
|
+
// `var(--a63-name)` with nothing after the name, and Tailwind's `(--a63-name)`.
|
|
113
|
+
const TOKEN_READ = /var\(\s*(--a63-[\w-]+)\s*\)|(?<=[\w-])\((--a63-[\w-]+)\)/g
|
|
114
|
+
// `--a63-name:` in CSS, `'--a63-name':` in a style object, `[--a63-name:` in a
|
|
115
|
+
// utility, and a whole string `'--a63-name'`, the name a script sets at runtime.
|
|
116
|
+
const TOKEN_DECLARATION = /(?<![\w-])(--a63-[\w-]+)['"]?\s*:|(?<=['"`])(--a63-[\w-]+)(?=['"`])/g
|
|
117
|
+
|
|
118
|
+
// Every read of an `--a63-*` name, fallback or not, and every write of one.
|
|
119
|
+
const ANY_TOKEN_READ = /var\(\s*(--a63-[\w-]+)|(?<=[\w-])\((--a63-[\w-]+)\)/g
|
|
120
|
+
const TOKEN_WRITE = /(?<![\w-])(--a63-[\w-]+)['"]?\s*:(?!:)/g
|
|
121
|
+
|
|
122
|
+
const DATA_SIDE = /\[data-side=['"]?(?:left|right)\b/
|
|
123
|
+
const ALLOW = /craft-allow:\s*([a-z-]+)/g
|
|
124
|
+
const FILL_TOKEN =
|
|
125
|
+
/^--a63-(?:surface-[\w-]+|action-(?:primary|neutral|danger)(?:-(?:hover|active|pressed))?|selected(?:-accent)?-background)$/
|
|
126
|
+
const TEXT_TOKEN = /^--a63-text-[\w-]+$/
|
|
127
|
+
const TEXT_PROPERTY = /^(?:color|-webkit-text-fill-color)$/
|
|
128
|
+
const FILL_PROPERTY = /^background(?:-color)?$/
|
|
129
|
+
const SINGLE_TOKEN_VALUE = /^var\(\s*(--a63-[\w-]+)\s*\)(?:\s*!important)?$/
|
|
130
|
+
const ROLE_UTILITY = /^(text|bg|border(?:-[trblxyse])?|outline|decoration)-(.+?)(?:\/\d+)?$/
|
|
131
|
+
const DANGER_FILL = /^--a63-action-danger(?:-hover)?$/
|
|
132
|
+
const DANGER_FILL_READ = /var\(\s*(--a63-action-danger(?:-hover)?)\s*[,)]/
|
|
133
|
+
const EDGE_PROPERTY =
|
|
134
|
+
/^(?:border(?:-(?:top|right|bottom|left|block|inline)(?:-(?:start|end))?)?(?:-color)?|outline(?:-color)?|text-decoration(?:-color)?|caret-color)$/
|
|
135
|
+
const ARBITRARY_TOKEN = /^(?:\((--a63-[\w-]+)\)|\[var\((--a63-[\w-]+)\)\])$/
|
|
136
|
+
|
|
137
|
+
/** Whether `kind` (`text` or `bg`) painting `token` puts it outside its role. */
|
|
138
|
+
const misusesRole = (kind, token) =>
|
|
139
|
+
kind === 'text'
|
|
140
|
+
? FILL_TOKEN.test(token)
|
|
141
|
+
: kind === 'bg'
|
|
142
|
+
? TEXT_TOKEN.test(token)
|
|
143
|
+
: DANGER_FILL.test(token)
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Drop violations a `craft-allow` comment exempts. A comment that shares its
|
|
147
|
+
* line with code covers that line; a comment on a line of its own covers the
|
|
148
|
+
* line below.
|
|
149
|
+
*/
|
|
150
|
+
function allowances(text) {
|
|
151
|
+
const allowed = new Map()
|
|
152
|
+
text.split('\n').forEach((line, index) => {
|
|
153
|
+
const code = line.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/g, '').replace(/[{}\s]/g, '')
|
|
154
|
+
const at = code ? index + 1 : index + 2
|
|
155
|
+
for (const [, rule] of line.matchAll(ALLOW)) {
|
|
156
|
+
if (!allowed.has(at)) allowed.set(at, new Set())
|
|
157
|
+
allowed.get(at).add(rule)
|
|
158
|
+
}
|
|
159
|
+
})
|
|
160
|
+
return found => found.filter(({ rule, line }) => !allowed.get(line)?.has(rule))
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function lineAt(text, index) {
|
|
164
|
+
let line = 1
|
|
165
|
+
for (let i = 0; i < index; i++) if (text.charCodeAt(i) === 10) line++
|
|
166
|
+
return line
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Blank out comments while keeping offsets, so line numbers stay right. */
|
|
170
|
+
function blank(text, pattern) {
|
|
171
|
+
return text.replace(pattern, match => match.replace(/[^\n]/g, ' '))
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The `--a63-*` names a source declares, so its own reads are not unknown.
|
|
176
|
+
* @param {string} text
|
|
177
|
+
* @returns {string[]}
|
|
178
|
+
*/
|
|
179
|
+
export function declaredTokens(text) {
|
|
180
|
+
return [...text.matchAll(TOKEN_DECLARATION)].map(([, declared, named]) => declared ?? named)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** `unknown-token` violations in comment-blanked source. */
|
|
184
|
+
function unknownTokens(src, knownTokens) {
|
|
185
|
+
if (!knownTokens) return []
|
|
186
|
+
const known = new Set([...knownTokens, ...declaredTokens(src)])
|
|
187
|
+
const found = []
|
|
188
|
+
for (const match of src.matchAll(TOKEN_READ)) {
|
|
189
|
+
const name = match[1] ?? match[2]
|
|
190
|
+
if (!known.has(name)) {
|
|
191
|
+
found.push({ rule: 'unknown-token', match: name, line: lineAt(src, match.index) })
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return found
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* `internal-token` violations in comment-blanked source. `tiers` maps a
|
|
199
|
+
* manifest token to `{ tier, readOnly }`.
|
|
200
|
+
* @param {string} src
|
|
201
|
+
* @param {Map<string, { tier: string, readOnly?: boolean }> | undefined} tiers
|
|
202
|
+
*/
|
|
203
|
+
function internalTokens(src, tiers) {
|
|
204
|
+
if (!tiers) return []
|
|
205
|
+
const found = []
|
|
206
|
+
for (const match of src.matchAll(ANY_TOKEN_READ)) {
|
|
207
|
+
const name = match[1] ?? match[2]
|
|
208
|
+
if (tiers.get(name)?.tier === 'internal') {
|
|
209
|
+
found.push({ rule: 'internal-token', match: name, line: lineAt(src, match.index) })
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
for (const match of src.matchAll(TOKEN_WRITE)) {
|
|
213
|
+
const name = match[1]
|
|
214
|
+
const token = tiers.get(name)
|
|
215
|
+
if (token?.tier === 'internal' || token?.readOnly) {
|
|
216
|
+
found.push({ rule: 'internal-token', match: `${name}:`, line: lineAt(src, match.index) })
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return found
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* The public token closest to an internal one: the first public token its
|
|
224
|
+
* value reads, following aliases, or null. Read-only tokens are skipped: they
|
|
225
|
+
* are not something to set instead.
|
|
226
|
+
* @param {string} name
|
|
227
|
+
* @param {{ cssVar: string, tier?: string, aliases?: string[] }[]} entries manifest entries
|
|
228
|
+
* @param {Record<string, { readOnly?: boolean }>} [publicTier] the manifest's `publicTier`
|
|
229
|
+
* @returns {string | null}
|
|
230
|
+
*/
|
|
231
|
+
export function nearestPublicToken(name, entries, publicTier = {}) {
|
|
232
|
+
const byVar = new Map()
|
|
233
|
+
for (const entry of entries) {
|
|
234
|
+
if (!byVar.has(entry.cssVar)) byVar.set(entry.cssVar, [])
|
|
235
|
+
byVar.get(entry.cssVar).push(entry)
|
|
236
|
+
}
|
|
237
|
+
const seen = new Set()
|
|
238
|
+
let frontier = [name.replace(/:$/, '')]
|
|
239
|
+
while (frontier.length > 0) {
|
|
240
|
+
const next = []
|
|
241
|
+
for (const cssVar of frontier) {
|
|
242
|
+
if (seen.has(cssVar)) continue
|
|
243
|
+
seen.add(cssVar)
|
|
244
|
+
for (const entry of byVar.get(cssVar) ?? []) {
|
|
245
|
+
for (const alias of entry.aliases ?? []) {
|
|
246
|
+
if (byVar.get(alias)?.[0]?.tier === 'public' && !publicTier[alias]?.readOnly) return alias
|
|
247
|
+
next.push(alias)
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
frontier = next
|
|
252
|
+
}
|
|
253
|
+
return null
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Manifest entries as the `tiers` map the scanners take.
|
|
258
|
+
* @param {{ cssVar: string, tier?: string }[]} entries
|
|
259
|
+
* @param {Record<string, { readOnly?: boolean }>} [publicTier] the manifest's `publicTier`
|
|
260
|
+
*/
|
|
261
|
+
export function tokenTiers(entries, publicTier = {}) {
|
|
262
|
+
const tiers = new Map()
|
|
263
|
+
for (const entry of entries) {
|
|
264
|
+
if (!entry.tier || tiers.has(entry.cssVar)) continue
|
|
265
|
+
tiers.set(entry.cssVar, {
|
|
266
|
+
tier: entry.tier,
|
|
267
|
+
...(publicTier[entry.cssVar]?.readOnly ? { readOnly: true } : {}),
|
|
268
|
+
})
|
|
269
|
+
}
|
|
270
|
+
return tiers
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** True when the flat rule body starting at `start` only removes the outline. */
|
|
274
|
+
function onlyResetsFocus(src, start) {
|
|
275
|
+
const end = src.indexOf('}', start)
|
|
276
|
+
const declarations = src
|
|
277
|
+
.slice(start, end === -1 ? undefined : end)
|
|
278
|
+
.split(';')
|
|
279
|
+
.map(part => part.trim().replace(/\s+/g, ' '))
|
|
280
|
+
.filter(Boolean)
|
|
281
|
+
return declarations.length > 0 && declarations.every(part => CSS_FOCUS_RESET.test(part))
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* @param {string} css
|
|
286
|
+
* @param {{ knownTokens?: Iterable<string>, tiers?: Map<string, { tier: string, readOnly?: boolean }> }} [options]
|
|
287
|
+
* @returns {{ rule: string, match: string, line: number }[]}
|
|
288
|
+
*/
|
|
289
|
+
export function scanCss(css, { knownTokens, tiers } = {}) {
|
|
290
|
+
const src = blank(css, CSS_COMMENT)
|
|
291
|
+
const found = [...unknownTokens(src, knownTokens), ...internalTokens(src, tiers)]
|
|
292
|
+
const selectors = []
|
|
293
|
+
// A declaration is `name: value` ending at `;` or `}`; a selector ends at `{`.
|
|
294
|
+
const statement = /([^{};]*)([{};])/g
|
|
295
|
+
let m
|
|
296
|
+
while ((m = statement.exec(src))) {
|
|
297
|
+
const body = m[1]
|
|
298
|
+
const offset = m.index + body.length - body.trimStart().length
|
|
299
|
+
const text = body.trim()
|
|
300
|
+
if (m[2] === '{') selectors.push(text)
|
|
301
|
+
if (!text) {
|
|
302
|
+
if (m[2] === '}') selectors.pop()
|
|
303
|
+
continue
|
|
304
|
+
}
|
|
305
|
+
const line = lineAt(src, offset)
|
|
306
|
+
if (m[2] === '{') {
|
|
307
|
+
if (CSS_FOCUS.test(text) && !onlyResetsFocus(src, statement.lastIndex)) {
|
|
308
|
+
found.push({ rule: 'focus-visible', match: text, line })
|
|
309
|
+
}
|
|
310
|
+
if (CSS_MODE_SELECTOR.test(text)) {
|
|
311
|
+
found.push({ rule: 'mode-branch', match: text.replace(/\s+/g, ' '), line })
|
|
312
|
+
}
|
|
313
|
+
continue
|
|
314
|
+
}
|
|
315
|
+
// A declaration that ends its block (no trailing `;`) closes the block too.
|
|
316
|
+
if (m[2] === '}') statement.lastIndex = m.index + body.length
|
|
317
|
+
const colon = text.indexOf(':')
|
|
318
|
+
if (colon === -1 || text.startsWith('@')) continue
|
|
319
|
+
const property = text.slice(0, colon).trim()
|
|
320
|
+
const value = text.slice(colon + 1).trim()
|
|
321
|
+
const sided = selectors.some(selector => DATA_SIDE.test(selector))
|
|
322
|
+
if (CSS_PHYSICAL_PROPERTY.test(property) && !sided) {
|
|
323
|
+
found.push({ rule: 'physical-properties', match: property, line })
|
|
324
|
+
}
|
|
325
|
+
if (property === 'text-align' && /^(?:left|right)\b/.test(value) && !sided) {
|
|
326
|
+
found.push({ rule: 'physical-properties', match: `text-align: ${value}`, line })
|
|
327
|
+
}
|
|
328
|
+
if (property === 'box-shadow') {
|
|
329
|
+
const ring = [...value.matchAll(CSS_VAR_NAME)].find(([, name]) => isRingToken(name))
|
|
330
|
+
if (ring) {
|
|
331
|
+
found.push({ rule: 'focus-ring-outline', match: `box-shadow: var(${ring[1]})`, line })
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const single = value.match(SINGLE_TOKEN_VALUE)?.[1]
|
|
335
|
+
const kind = TEXT_PROPERTY.test(property) ? 'text' : FILL_PROPERTY.test(property) ? 'bg' : null
|
|
336
|
+
if (single && kind && misusesRole(kind, single)) {
|
|
337
|
+
found.push({ rule: 'token-role', match: `${property}: var(${single})`, line })
|
|
338
|
+
} else if (kind === 'text' || EDGE_PROPERTY.test(property)) {
|
|
339
|
+
const danger = value.match(DANGER_FILL_READ)?.[1]
|
|
340
|
+
if (danger) found.push({ rule: 'token-role', match: `${property}: var(${danger})`, line })
|
|
341
|
+
}
|
|
342
|
+
if (CSS_MASK_PROPERTY.test(property)) continue
|
|
343
|
+
for (const color of value.match(CSS_LITERAL_COLOR) ?? []) {
|
|
344
|
+
if (color === '#0000') continue
|
|
345
|
+
found.push({ rule: 'raw-color', match: `${property}: ${color}`, line })
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return allowances(css)(found)
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Scan TS/TSX source for class-name utilities. Every whitespace-, quote-,
|
|
353
|
+
* backtick- or brace-delimited token is a candidate, so class names in `cn()`,
|
|
354
|
+
* `cva()` and template strings are all covered, and arbitrary values keep
|
|
355
|
+
* their parentheses.
|
|
356
|
+
* @param {string} source
|
|
357
|
+
* @param {{ knownTokens?: Iterable<string>, roles?: Record<string, string>, tiers?: Map<string, { tier: string, readOnly?: boolean }> }} [options]
|
|
358
|
+
* `roles` maps a Tailwind color role (`primary`) to the token it reads;
|
|
359
|
+
* `tiers` turns on `internal-token`.
|
|
360
|
+
* @returns {{ rule: string, match: string, line: number }[]}
|
|
361
|
+
*/
|
|
362
|
+
export function scanSource(source, { knownTokens, roles = {}, tiers } = {}) {
|
|
363
|
+
const src = blank(source, JS_COMMENT)
|
|
364
|
+
const found = [...unknownTokens(src, knownTokens), ...internalTokens(src, tiers)]
|
|
365
|
+
const token = /[^\s"'`{}]+/g
|
|
366
|
+
let m
|
|
367
|
+
while ((m = token.exec(src))) {
|
|
368
|
+
const raw = m[0]
|
|
369
|
+
// Strip variants (`md:`, `hover:`, `[&_p]:`) and the important modifier.
|
|
370
|
+
const utility = raw.slice(raw.lastIndexOf(':') + 1).replace(/^!|!$/g, '')
|
|
371
|
+
const line = () => lineAt(src, m.index)
|
|
372
|
+
if (PALETTE_UTILITY.test(utility) || ARBITRARY_COLOR_UTILITY.test(utility)) {
|
|
373
|
+
found.push({ rule: 'raw-color', match: raw, line: line() })
|
|
374
|
+
}
|
|
375
|
+
if (PHYSICAL_UTILITY.test(utility) && !SAFE_AREA.test(raw)) {
|
|
376
|
+
found.push({ rule: 'physical-properties', match: raw, line: line() })
|
|
377
|
+
}
|
|
378
|
+
if (FOCUS_VARIANT.test(raw) && !FOCUS_RESET_UTILITY.test(utility)) {
|
|
379
|
+
found.push({ rule: 'focus-visible', match: raw, line: line() })
|
|
380
|
+
}
|
|
381
|
+
const variants = raw.slice(0, raw.lastIndexOf(':') + 1)
|
|
382
|
+
// `dark:` with nothing after it is an object key (`{ dark: … }`), not a variant.
|
|
383
|
+
if (MODE_VARIANT.test(variants) && utility) {
|
|
384
|
+
found.push({ rule: 'mode-branch', match: raw, line: line() })
|
|
385
|
+
}
|
|
386
|
+
const role = ROLE_UTILITY.exec(utility)
|
|
387
|
+
if (role) {
|
|
388
|
+
const arbitrary = ARBITRARY_TOKEN.exec(role[2])
|
|
389
|
+
const token = arbitrary
|
|
390
|
+
? (arbitrary[1] ?? arbitrary[2])
|
|
391
|
+
: Object.hasOwn(roles, role[2])
|
|
392
|
+
? roles[role[2]]
|
|
393
|
+
: null
|
|
394
|
+
if (token && misusesRole(role[1], token)) {
|
|
395
|
+
found.push({ rule: 'token-role', match: raw, line: line() })
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
if (
|
|
399
|
+
FOCUS_RING_VARIANT.test(variants) &&
|
|
400
|
+
RING_UTILITY.test(utility) &&
|
|
401
|
+
!FOCUS_RESET_UTILITY.test(utility)
|
|
402
|
+
) {
|
|
403
|
+
found.push({ rule: 'focus-ring-outline', match: raw, line: line() })
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
return allowances(source)(found)
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* The Tailwind color roles from styles' `tailwind/roles.json`, as role -> token.
|
|
411
|
+
* @param {{ groups: { roles: Record<string, string> }[] }} rolesJson
|
|
412
|
+
* @returns {Record<string, string>}
|
|
413
|
+
*/
|
|
414
|
+
export const roleTokens = rolesJson =>
|
|
415
|
+
Object.assign({}, ...rolesJson.groups.map(group => group.roles))
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Count violations per `rule | file | match`. Line numbers drift with every
|
|
419
|
+
* edit, so the baseline keys on what was written, not where.
|
|
420
|
+
* @param {{ file: string, rule: string, match: string }[]} violations
|
|
421
|
+
* @returns {Record<string, number>}
|
|
422
|
+
*/
|
|
423
|
+
export function countViolations(violations) {
|
|
424
|
+
const counts = {}
|
|
425
|
+
for (const { file, rule, match } of violations) {
|
|
426
|
+
const key = `${rule} | ${file} | ${match}`
|
|
427
|
+
counts[key] = (counts[key] ?? 0) + 1
|
|
428
|
+
}
|
|
429
|
+
return Object.fromEntries(Object.entries(counts).sort(([a], [b]) => a.localeCompare(b)))
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Compare current counts to the baseline. `added` fails the check; `resolved`
|
|
434
|
+
* means the baseline is stale and must shrink with the fix.
|
|
435
|
+
* @param {Record<string, number>} current
|
|
436
|
+
* @param {Record<string, number>} baseline
|
|
437
|
+
*/
|
|
438
|
+
export function compareToBaseline(current, baseline) {
|
|
439
|
+
const added = []
|
|
440
|
+
const resolved = []
|
|
441
|
+
for (const [key, count] of Object.entries(current)) {
|
|
442
|
+
const allowed = baseline[key] ?? 0
|
|
443
|
+
if (count > allowed) added.push({ key, count: count - allowed })
|
|
444
|
+
}
|
|
445
|
+
for (const [key, allowed] of Object.entries(baseline)) {
|
|
446
|
+
const count = current[key] ?? 0
|
|
447
|
+
if (count < allowed) resolved.push({ key, count: allowed - count })
|
|
448
|
+
}
|
|
449
|
+
return { added, resolved }
|
|
450
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Escapes: places where screen code steps outside the design system, found in
|
|
3
|
+
* the syntax tree of one TSX file. The replication benchmark counts them, and
|
|
4
|
+
* the plugin's rules report them. Pure functions over file contents.
|
|
5
|
+
*
|
|
6
|
+
* - `raw-control`: an interactive HTML element (`button`, `a`, `input`, …)
|
|
7
|
+
* that is not the `render` element of a design-system component.
|
|
8
|
+
* - `inline-style`: a `style` prop.
|
|
9
|
+
* - `arbitrary-value`: a Tailwind arbitrary value (`w-[37px]`) that reads no
|
|
10
|
+
* token, safe-area inset or spacing step.
|
|
11
|
+
* - `arbitrary-selector`: a Tailwind arbitrary variant (`[&>svg]:size-6`),
|
|
12
|
+
* which reaches into markup the screen does not own.
|
|
13
|
+
* - `component-override`: a color, type, border, radius or shadow utility in
|
|
14
|
+
* the `className` of a design-system component, which repaints it.
|
|
15
|
+
* - `off-system-import`: an import from anything other than the published
|
|
16
|
+
* design-system entry points, React and the icon set.
|
|
17
|
+
*/
|
|
18
|
+
import ts from 'typescript'
|
|
19
|
+
|
|
20
|
+
/** HTML elements a person operates. Layout and text elements do not count. */
|
|
21
|
+
export const interactiveHtml = new Set([
|
|
22
|
+
'a',
|
|
23
|
+
'button',
|
|
24
|
+
'details',
|
|
25
|
+
'dialog',
|
|
26
|
+
'form',
|
|
27
|
+
'input',
|
|
28
|
+
'label',
|
|
29
|
+
'option',
|
|
30
|
+
'select',
|
|
31
|
+
'summary',
|
|
32
|
+
'textarea',
|
|
33
|
+
])
|
|
34
|
+
|
|
35
|
+
const allowedImport =
|
|
36
|
+
/^(?:react|react-dom(?:\/client)?|lucide-react|@atom63\/ui-react(?:\/(?:calendar|chart|layout|media|media\/lightbox|preview|theme))?|@atom63\/styles(?:\/.*)?)$/
|
|
37
|
+
|
|
38
|
+
/* A token read, a safe-area inset, a spacing step or a theme function: still the system's values. */
|
|
39
|
+
const tokenValue = /var\(--|env\(|--spacing\(|theme\(/
|
|
40
|
+
|
|
41
|
+
/* Utilities that repaint a component rather than place it. */
|
|
42
|
+
const paintUtility =
|
|
43
|
+
/^(?:text-(?!(?:start|end|center|left|right|justify|wrap|nowrap|balance|pretty|ellipsis|clip)$)|bg-|border|rounded|shadow|font-|leading-|tracking-|ring|outline|opacity-|fill-|stroke-)/
|
|
44
|
+
|
|
45
|
+
/** Class tokens in a className string, with their variants. */
|
|
46
|
+
function classTokens(value) {
|
|
47
|
+
return value.split(/\s+/).filter(Boolean)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Escapes in one TSX file that need its syntax tree: raw controls, inline
|
|
52
|
+
* styles, component overrides, arbitrary values and selectors, imports.
|
|
53
|
+
*/
|
|
54
|
+
export function findSyntaxEscapes(source, fileName = 'file.tsx') {
|
|
55
|
+
const file = ts.createSourceFile(
|
|
56
|
+
fileName,
|
|
57
|
+
source,
|
|
58
|
+
ts.ScriptTarget.Latest,
|
|
59
|
+
true,
|
|
60
|
+
ts.ScriptKind.TSX
|
|
61
|
+
)
|
|
62
|
+
const escapes = []
|
|
63
|
+
const at = node => file.getLineAndCharacterOfPosition(node.getStart(file)).line + 1
|
|
64
|
+
const systemNames = new Set()
|
|
65
|
+
|
|
66
|
+
for (const statement of file.statements) {
|
|
67
|
+
if (!ts.isImportDeclaration(statement)) continue
|
|
68
|
+
const from = /** @type {import('typescript').StringLiteral} */ (statement.moduleSpecifier).text
|
|
69
|
+
if (from.startsWith('.')) continue
|
|
70
|
+
if (!allowedImport.test(from)) {
|
|
71
|
+
escapes.push({ rule: 'off-system-import', line: at(statement), match: from })
|
|
72
|
+
}
|
|
73
|
+
const bindings = statement.importClause?.namedBindings
|
|
74
|
+
if (from.startsWith('@atom63/') && bindings && ts.isNamedImports(bindings)) {
|
|
75
|
+
for (const element of bindings.elements) systemNames.add(element.name.text)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const isRenderProp = node => {
|
|
80
|
+
// <Item render={<a … />}>: the element is the component's own root.
|
|
81
|
+
let parent = node.parent
|
|
82
|
+
if (ts.isJsxElement(parent)) parent = parent.parent
|
|
83
|
+
if (parent && ts.isParenthesizedExpression(parent)) parent = parent.parent
|
|
84
|
+
return (
|
|
85
|
+
parent &&
|
|
86
|
+
ts.isJsxExpression(parent) &&
|
|
87
|
+
ts.isJsxAttribute(parent.parent) &&
|
|
88
|
+
parent.parent.name.getText(file) === 'render'
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const classValues = attribute => {
|
|
93
|
+
const init = attribute.initializer
|
|
94
|
+
if (!init) return []
|
|
95
|
+
if (ts.isStringLiteral(init)) return [init.text]
|
|
96
|
+
const values = []
|
|
97
|
+
const collect = node => {
|
|
98
|
+
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
|
|
99
|
+
values.push(node.text)
|
|
100
|
+
else if (ts.isTemplateExpression(node)) {
|
|
101
|
+
values.push(node.head.text)
|
|
102
|
+
for (const span of node.templateSpans) values.push(span.literal.text)
|
|
103
|
+
}
|
|
104
|
+
ts.forEachChild(node, collect)
|
|
105
|
+
}
|
|
106
|
+
collect(init)
|
|
107
|
+
return values
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const visit = node => {
|
|
111
|
+
if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
|
|
112
|
+
const tag = node.tagName.getText(file)
|
|
113
|
+
const element = ts.isJsxOpeningElement(node) ? node.parent : node
|
|
114
|
+
if (interactiveHtml.has(tag) && tag !== 'form' && !isRenderProp(element)) {
|
|
115
|
+
escapes.push({ rule: 'raw-control', line: at(node), match: `<${tag}>` })
|
|
116
|
+
}
|
|
117
|
+
for (const attribute of node.attributes.properties) {
|
|
118
|
+
if (!ts.isJsxAttribute(attribute)) continue
|
|
119
|
+
const name = attribute.name.getText(file)
|
|
120
|
+
if (name === 'style')
|
|
121
|
+
escapes.push({ rule: 'inline-style', line: at(attribute), match: 'style' })
|
|
122
|
+
if (name !== 'className') continue
|
|
123
|
+
for (const value of classValues(attribute)) {
|
|
124
|
+
for (const token of classTokens(value)) {
|
|
125
|
+
const utility = token.slice(token.lastIndexOf(':') + 1).replace(/^!|!$/g, '')
|
|
126
|
+
const variants = token.slice(0, token.lastIndexOf(':') + 1)
|
|
127
|
+
if (/\[[^\]]*\]:?/.test(variants)) {
|
|
128
|
+
escapes.push({ rule: 'arbitrary-selector', line: at(attribute), match: token })
|
|
129
|
+
}
|
|
130
|
+
const arbitrary = /\[([^\]]+)\]/.exec(utility)
|
|
131
|
+
if (arbitrary && !tokenValue.test(arbitrary[1])) {
|
|
132
|
+
escapes.push({ rule: 'arbitrary-value', line: at(attribute), match: token })
|
|
133
|
+
}
|
|
134
|
+
if (systemNames.has(tag.split('.')[0]) && paintUtility.test(utility)) {
|
|
135
|
+
escapes.push({
|
|
136
|
+
rule: 'component-override',
|
|
137
|
+
line: at(attribute),
|
|
138
|
+
match: `${tag} ${token}`,
|
|
139
|
+
})
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
ts.forEachChild(node, visit)
|
|
146
|
+
}
|
|
147
|
+
visit(file)
|
|
148
|
+
return escapes
|
|
149
|
+
}
|