stylelint-plugin-rhythmguard 3.13.0 → 3.15.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/CHANGELOG.md +38 -0
- package/CONTRIBUTING.md +26 -5
- package/README.md +25 -4
- package/package.json +3 -2
- package/src/audit/args.js +2 -0
- package/src/audit/codemod.js +11 -3
- package/src/audit/config.js +1 -0
- package/src/audit/contract.js +28 -1
- package/src/audit/non-authored.js +77 -0
- package/src/audit/render-markdown.js +1 -0
- package/src/audit/render-text.js +4 -0
- package/src/audit/report.js +41 -7
- package/src/audit/shared.js +1 -0
- package/src/cli/doctor.js +30 -3
- package/src/cli/fix.js +27 -14
- package/src/cli/quickstart.js +2 -1
- package/src/core/tailwind-class-analysis.js +8 -0
- package/src/core/token-sources.js +141 -13
- package/src/eslint/rules/tailwind-class-use-scale.js +1 -0
- package/types/__checks__/consumer.ts +6 -0
- package/types/__checks__/eslint-config.ts +12 -0
- package/types/audit.d.ts +18 -0
- package/types/eslint.d.ts +1 -1
- package/types/index.d.ts +2 -0
- package/types/shared.d.ts +18 -0
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,44 @@ The format follows Keep a Changelog principles and semantic versioning.
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [3.15.0] - 2026-10-30
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- `--include-non-authored` (`includeNonAuthored` in `createAuditReport`, `audit.includeNonAuthored` in `.rhythmguardrc.json`) audits vendored and built stylesheets again; see Changed. ([#161](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues/161))
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
|
|
17
|
+
- **`rhythmguard audit` reports change by default: it no longer audits vendored, test and built stylesheets.** A vendored Cropper.js or jQuery UI theme, a `font-awesome/` copy or a compiled bundle was audited as authored CSS and often led the report. A stylesheet is now left out when a path segment relative to the audited directory is `vendor`, `vendors`, `third-party` (`third_party`, `thirdparty`), `jquery-ui`, `font-awesome`, `fontawesome`, `generated`, `test`, `tests`, `__tests__`, `spec`, `specs`, `fixture`, `fixtures`, `__fixtures__`, `__snapshots__`, `e2e`, `storybook-static` or `.storybook`; when it is a `*.min.css`; or when its code, comments aside, is one line over 5 KB (a built bundle, caught even when the audited directory is `dist` itself). `lib` and `libs` stay audited, since projects keep their own code there. Skipped files add no findings, are not counted in `scanned.cssFiles` or scale cleanliness, and a baseline finding in one is neither resolved nor new, so `--since-baseline` does not count them as fixed. The report counts them in `scanned.nonAuthoredSkipped` and lists them, each with a reason (`path`, `minified` or `bundle`), in `scanned.nonAuthoredFiles`; the text and Markdown summaries and the quickstart print the count. Scale inference and token chains use the same definition, so tokens declared under `generated/`, `e2e/`, `.storybook/`, `jquery-ui/` or `font-awesome/`, in a `*.min.css` or in a bundle no longer shape a `--scale auto` scale, and the path is now judged relative to the audited directory rather than the working directory. The Stylelint and ESLint rules and `rhythmguard fix` are unchanged. In the quiet benchmark 58 findings leave 8 of the 57 repositories, every one from a test, vendor, fixture, Storybook or font-awesome stylesheet: all 53 `noise:non-authored`, PatternFly's 4 `noise:vendored` (its font-awesome copy) and 1 Salesforce Lightning `drift` in `__fixtures__/`, which the benchmark's own path rule missed. No authored finding moves and no inferred scale changes; see `docs/QUIET_BENCHMARK.md`. ([#161](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues/161))
|
|
18
|
+
- `rhythmguard fix` skips the vendored, test, minified and built stylesheets the audit skips, so a decision from `--plan` never rewrites a file the plan did not show; `--include-non-authored` and `audit.includeNonAuthored` rewrite them as before. ([#331](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues/331))
|
|
19
|
+
- `tailwind-class-use-scale` exempts hairlines by default, as `use-scale` does. A non-zero length that resolves to one CSS pixel or less (`translate-y-[0.5px]`, `-mt-[1px]`, `m-[-1px]`, `p-[0.0625rem]`) is not reported, so the `0.5px` that is quiet in CSS is quiet in a class string too. The definition is the one the Stylelint rules use: by resolved size through `baseFontSize`, `0` and unitless values never reported, and the exemption applies before `allowNegative`. Set the new `allowHairlines: false` to report them as before. `rhythmguard audit` applies the same default to the class strings it scans, and `RhythmguardTailwindClassOptions` types the rule's options. The motion rule is unchanged, and so are messages and fixes. Only class strings with hairlines report less. ([#159](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues/159))
|
|
20
|
+
- Tested on Node 24 and 26 (with Stylelint 17) in addition to Node 20 and 22, and the ESLint companion rules on ESLint 9 as well as 10. A weekly job runs the full suite against Stylelint `next`; 18.0.0-next.0 passes. Peer ranges are unchanged.
|
|
21
|
+
- A release run now fails unless all three packages (`stylelint-plugin-rhythmguard`, `rhythmguard`, `eslint-plugin-rhythmguard`) are on npm at the release version.
|
|
22
|
+
- Feature freeze until 4.0, recorded in `CONTRIBUTING.md` and `ROADMAP.md`; the 2026-10-18 council report is in `docs/COUNCIL_2027-2028.md`. Contributors get `npm run check`, an `.nvmrc`, a dev container for Codespaces, and Discussions for questions.
|
|
23
|
+
- Ionic Framework is no longer in the quiet benchmark or the State of Spacing 2026-09 edition, at the maintainers' request (ionic-team/ionic-framework#31430). The edition now covers 57 repositories: 7972 off-scale values in 8362 CSS files.
|
|
24
|
+
|
|
25
|
+
### Messages
|
|
26
|
+
|
|
27
|
+
- `rhythmguard fix` prints `N non-authored files left alone (vendored, minified or built CSS; --include-non-authored rewrites them)` when it skipped any.
|
|
28
|
+
- New audit summary line in text output, `Non-authored skipped N (vendored, minified or built CSS; --include-non-authored audits them)`, and Markdown row, `| Non-authored stylesheets skipped (vendored, minified or built; --include-non-authored audits them) | N |`, shown when any stylesheet was skipped. The quickstart's `Skipped` line adds `N vendored, minified or built` to its reasons.
|
|
29
|
+
|
|
30
|
+
## [3.14.0] - 2026-10-19
|
|
31
|
+
|
|
32
|
+
### Added
|
|
33
|
+
|
|
34
|
+
- A configured token source that yields no spacing tokens is a warning, whatever its format. A DTCG file holding only colors, a stylesheet with no custom properties, or a design-tool export whose group is called `dimension` gave `0` tokens and a silent fallback scale. Each `--token-source` and `audit.tokenSources` file that parses but yields nothing now carries `Token source <file> (<format>) yielded no spacing tokens; ...` in the audit's token source report (`contracts.tokens.sources[].warnings` in JSON, the Markdown Token Sources table, and a `!` line under the source in the text output, which now prints every token source warning there), and `rhythmguard doctor` prints the same as a `!` warning line that does not fail the run, along with any parse or skip warning the audit would give for that file. With `--token-kind` the warning names that kind. Stylesheets found by the scan and installed token packages are not configured sources and get no such warning. `parseTokenSources` takes `warnWhenEmpty: true` for the same check; it is off by default. ([#163](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues/163))
|
|
35
|
+
- The DTCG group's 2025.10 conformance fixtures for dimensions and dimension references run in the unit tests, vendored under `test/fixtures/dtcg-test-suite/` from design-tokens/community-group at `8e43819` (W3C 3-clause BSD License). They are not part of the npm package. ([#163](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues/163))
|
|
36
|
+
|
|
37
|
+
### Fixed
|
|
38
|
+
|
|
39
|
+
- DTCG token sources read the rest of the 2025.10 dimension forms the conformance suite covers. A `$ref` token (`"$ref": "#/base/$value/fontSize"`) was dropped without a word; it is now read through its JSON Pointer within the file, so a pointer to a `{ value, unit }` dimension gives that length. A `$ref` that names nothing, or a `dimension` token pointing at a bare number, is skipped with a warning; one pointing at a color or a composite is not a length and is left out as a color `$value` is. A dimension object without a number `value` and a `unit` (`{ "value": "16", "unit": "px" }`, `{ "unit": "px" }`) was dropped silently and is now skipped with a warning naming the token. Only files with such tokens read differently: a `$ref` spacing token can now move an inferred scale. ([#163](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues/163))
|
|
40
|
+
|
|
41
|
+
### Messages
|
|
42
|
+
|
|
43
|
+
- New token source warning (audit and `rhythmguard doctor`): `Token source <file> (<format>) yielded no spacing tokens; spacing tokens are read by name (space, spacing or spacer), so set a tokenPattern on this source if its tokens are named otherwise.`; with another `--token-kind`, `Token source <file> (<format>) yielded no <kind> tokens.`; with `--token-kind all`, `... yielded no tokens.`; for a source with its own `tokenPattern`, `... yielded no tokens matching tokenPattern "<pattern>".`
|
|
44
|
+
- New skip reasons in `Token source <file>: skipped <token> (<reason>).`: `dimension needs a number "value" and a "unit"`, `reference "<pointer>" does not resolve`, `reference "<pointer>" is a number, not a dimension`, `reference cycle through "<pointer>"`.
|
|
45
|
+
- `rhythmguard doctor` prints warnings as `! <warning>` lines, and its summary reads `All checks passed (N warnings).` or `N issues found (N warnings).` when there are any; without warnings it is unchanged.
|
|
46
|
+
|
|
9
47
|
## [3.13.0] - 2026-10-18
|
|
10
48
|
|
|
11
49
|
### Fixed
|
package/CONTRIBUTING.md
CHANGED
|
@@ -2,6 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
Thank you for being here. Rhythmguard is a small, opinionated tool with one job: keep spacing on a scale. Most of the useful work on it is small too, and a first contribution can land in an afternoon. This page tells you where the useful work is, how the checks run, and what to expect from review.
|
|
4
4
|
|
|
5
|
+
## Your first contribution
|
|
6
|
+
|
|
7
|
+
1. Pick an issue labelled [`good first issue`](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/labels/good%20first%20issue) and say in a comment that you are taking it, so nobody duplicates the work. Each one names the files to touch and how to know you are done.
|
|
8
|
+
2. Open the repository in a [Codespace](https://codespaces.new/PetriLahdelma/stylelint-plugin-rhythmguard) (dependencies install themselves), or clone it locally as in [Getting set up](#getting-set-up).
|
|
9
|
+
3. Write the failing test, make the change, run `npm run check`.
|
|
10
|
+
4. Open a pull request. CI runs on it, and the maintainer replies within a week.
|
|
11
|
+
|
|
12
|
+
Questions, ideas and "is this a bug?" belong in [Discussions](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/discussions); issues are for work with a clear "done when".
|
|
13
|
+
|
|
5
14
|
## Ways to contribute
|
|
6
15
|
|
|
7
16
|
**Report a false positive.** A finding your team considers wrong is the most valuable report we get. It is how percentages and hairlines stopped being findings. Open a [false-positive report](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues/new?template=false-positive.yml) with the CSS or class string and your config. No fix required.
|
|
@@ -29,7 +38,7 @@ npm ci
|
|
|
29
38
|
npm test
|
|
30
39
|
```
|
|
31
40
|
|
|
32
|
-
Node 20.19 or newer. No build step; the source runs as is. Tests use `node --test` through `scripts/test.mjs` and take about fifteen seconds. They are grouped by what they prove:
|
|
41
|
+
Node 20.19 or newer; `.nvmrc` pins 22 for development, so `nvm use` picks it up. A [dev container](./.devcontainer/devcontainer.json) gives the same setup in Codespaces or VS Code. No build step; the source runs as is. Tests use `node --test` through `scripts/test.mjs` and take about fifteen seconds. They are grouped by what they prove:
|
|
33
42
|
|
|
34
43
|
| Folder | Proves | Run one |
|
|
35
44
|
| --- | --- | --- |
|
|
@@ -45,12 +54,12 @@ Put a new test where its subject lives. If it needs the real linter, it is a rul
|
|
|
45
54
|
|
|
46
55
|
## The local gate
|
|
47
56
|
|
|
48
|
-
Run these before you push. They are what CI runs, so a green local run means a green PR.
|
|
57
|
+
Run these before you push. They are what CI runs, so a green local run means a green PR. `npm run check` runs all three in order.
|
|
49
58
|
|
|
50
59
|
```bash
|
|
51
60
|
npm run lint # eslint
|
|
52
61
|
npm run typecheck # the published TypeScript declarations against a consumer file and the examples
|
|
53
|
-
npm test #
|
|
62
|
+
npm test # 600+ tests, on the Stylelint in the lockfile (17)
|
|
54
63
|
```
|
|
55
64
|
|
|
56
65
|
Optional, depending on what you touched:
|
|
@@ -65,7 +74,7 @@ npm run build:playground # after changing anything under src/ the rules us
|
|
|
65
74
|
npm run bench:agents -- --dry-run --limit 4 # the agent eval pipeline, no API key needed
|
|
66
75
|
```
|
|
67
76
|
|
|
68
|
-
The local gate runs on whatever Node you have installed; CI runs Node 20 and 22. Node 20.19 is the floor, so avoid features that arrived in Node 21 or later. Glob patterns for `node --test` were one such feature, and they took a release run down.
|
|
77
|
+
The local gate runs on whatever Node you have installed; CI runs Node 20 and 22 against Stylelint 16.0.0, 16 and 17, Node 24 and 26 against Stylelint 17, the ESLint companion rules on ESLint 9, and once a week the full suite against Stylelint `next`. Node 20.19 is the floor, so avoid features that arrived in Node 21 or later. Glob patterns for `node --test` were one such feature, and they took a release run down.
|
|
69
78
|
|
|
70
79
|
If your shell's npm registry is overridden by a corporate `.npmrc`, add `--registry https://registry.npmjs.org` to `npm ci` and prefix `test:pack-smoke` with `npm_config_registry=https://registry.npmjs.org`.
|
|
71
80
|
|
|
@@ -73,6 +82,17 @@ If your shell's npm registry is overridden by a corporate `.npmrc`, add `--regis
|
|
|
73
82
|
|
|
74
83
|
CI for this repository runs on self-hosted runners for pushes and same-repo branches. For pull requests from forks a separate job runs on GitHub-hosted runners with Node 22 and the Stylelint in the lockfile (17), covering lint, typecheck and the test suite. You will see its result on your PR. The full matrix and the benchmark run after merge.
|
|
75
84
|
|
|
85
|
+
## What is frozen until 4.0
|
|
86
|
+
|
|
87
|
+
Rhythmguard is in a feature freeze until 4.0, which ships the week Stylelint 18.0.0 is released (plan: [`docs/COUNCIL_2027-2028.md`](./docs/COUNCIL_2027-2028.md)). Please do not start work on these without an issue where the maintainer has agreed to an exception:
|
|
88
|
+
|
|
89
|
+
- new rule options, property groups, presets, or default scales;
|
|
90
|
+
- motion features and Tailwind class-name features beyond bug fixes;
|
|
91
|
+
- Less support, an MCP server, or a port to `@eslint/css` (#173, #175, #176 say what would reopen them);
|
|
92
|
+
- any change to message text in a patch release.
|
|
93
|
+
|
|
94
|
+
Always welcome: bug fixes with a failing test, false-positive reports, token-source fixes (Style Dictionary, DTCG, Sass maps, token packages), docs, benchmark rows and drift labels, and compatibility work for new Node, Stylelint and ESLint versions.
|
|
95
|
+
|
|
76
96
|
## Where things live
|
|
77
97
|
|
|
78
98
|
[`docs/ARCHITECTURE.md`](./docs/ARCHITECTURE.md) is the map: the layers under `src/`, which may depend on which, the primitives a rule is assembled from, and the invariants with the test that enforces each. Read it before a change that adds a module, and run `node --test test/contracts/architecture.test.js` after; it fails when a dependency crosses a layer line.
|
|
@@ -101,7 +121,8 @@ CI for this repository runs on self-hosted runners for pushes and same-repo bran
|
|
|
101
121
|
|
|
102
122
|
- Stylelint `^16.0.0 || ^17.0.0`. The 16.0.0 floor has known autofix differences; CI runs the floor suite against it.
|
|
103
123
|
- Node `>=20.19.0` until 4.0, which raises it to 22.22 ([#172](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues/172)).
|
|
104
|
-
- ESLint `>=8.0.0` for the companion rules; tested on 9.
|
|
124
|
+
- ESLint `>=8.0.0` for the companion rules; tested on 9 and 10.
|
|
125
|
+
- Stylelint 18: the full suite passes on 18.0.0-next.0 and runs weekly against `next`; the peer range widens in the week 18.0.0 ships.
|
|
105
126
|
- CommonJS and ESM entry points; every export has a declaration under `types/`.
|
|
106
127
|
- Three runtime dependencies: `known-css-properties`, `postcss` and `postcss-value-parser`. `postcss-scss`, `stylelint-config-tailwindcss` and `stylelint-plugin-logical-css` are optional peers and dev dependencies here. `test/contracts/architecture.test.js` fails if a runtime import is not declared.
|
|
107
128
|
|
package/README.md
CHANGED
|
@@ -7,13 +7,13 @@
|
|
|
7
7
|
Nobody chose 13px. Rhythmguard catches off-scale spacing in CSS and Tailwind class strings, tells you the nearest steps on your scale, and snaps to them or to your tokens when you ask.
|
|
8
8
|
|
|
9
9
|
[](https://github.com/petrilahdelma/stylelint-plugin-rhythmguard/actions/workflows/ci.yml)
|
|
10
|
-
[](https://www.npmjs.com/package/stylelint-plugin-rhythmguard)
|
|
11
11
|
[](https://www.npmjs.com/package/stylelint-plugin-rhythmguard)
|
|
12
12
|
[](./LICENSE)
|
|
13
13
|
|
|
14
14
|
Rhythmguard is scale-aware rather than a blanket ban: values on your scale pass, values off it are reported with the two nearest steps, and tokens are only ever suggested from a map you control. It works on CSS and SCSS declarations through Stylelint and on Tailwind class strings through an ESLint companion, and it ships an audit CLI so you can measure drift and ratchet it down before enforcing anything.
|
|
15
15
|
|
|
16
|
-
What it is not: it does not check colors or hex values, and the Stylelint rules do not see Tailwind class strings (that is the separate ESLint companion below). It reads CSS and SCSS; Less and CSS-in-JS are not read. Pair it with a color linter if you need one; do not expect one tool to do both.
|
|
16
|
+
What it is not: it does not check colors or hex values, and the Stylelint rules do not see Tailwind class strings (that is the separate ESLint companion below). It reads CSS and SCSS; Less and CSS-in-JS are not read. Pair it with a color linter if you need one; do not expect one tool to do both. Nor does it judge type for reading: whether a measure, a fluid heading or a number column works for the reader is the job of [Measured Type](#type-pair-it-with-measured-type).
|
|
17
17
|
|
|
18
18
|
## Start here
|
|
19
19
|
|
|
@@ -117,13 +117,34 @@ The audit scans CSS declarations, Tailwind class strings and your token contract
|
|
|
117
117
|
- [Product analysis, September 2026](docs/STRATEGY_2026-09.md): the market data behind the roadmap
|
|
118
118
|
- Browser playground: [petrilahdelma.github.io/stylelint-plugin-rhythmguard](https://petrilahdelma.github.io/stylelint-plugin-rhythmguard/) runs the real rules, bundled for the browser, on CSS or SCSS you paste; `scale: "auto"`, tokens and fixes included, and a test proves it reports what Stylelint reports
|
|
119
119
|
|
|
120
|
+
## Type: pair it with Measured Type
|
|
121
|
+
|
|
122
|
+
Rhythmguard keeps every value on the scale; it does not decide whether the scale reads well. [Measured Type](https://github.com/PetriLahdelma/measured-type), a coding-agent skill by the same author, does that part: Bringhurst's rules applied to CSS, with line length, zoom, contrast, tabular figures and font features measured in a real browser. Let it build the type scale and Rhythmguard hold everyone to it:
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
node scripts/type-scale.js --base 1rem:1.125rem --ratio 1.2:1.25 --steps 5 --fluid-from 4 --prefix font-size
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
That writes `--font-size-*` tokens, which the `typography` group reads with `"auto"`. Add your label and caption sizes to the same file, then list it next to your spacing tokens:
|
|
129
|
+
|
|
130
|
+
```json
|
|
131
|
+
"rhythmguard/use-scale": [true, {
|
|
132
|
+
"propertyGroups": ["spacing", "typography"],
|
|
133
|
+
"scale": "auto",
|
|
134
|
+
"scaleSources": ["src/space.css", "src/type.css"],
|
|
135
|
+
"scales": { "typography": "auto" }
|
|
136
|
+
}]
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
The two do not overlap. Rhythmguard reports the `13px` padding and the `17px` heading nobody chose; Measured Type reports the `3vw` size that cannot grow with zoom (Rhythmguard skips viewport units by design) and the `66ch` measure that sets 81 characters per line in Verdana. The worked example, run with Stylelint 17.16 and Rhythmguard 3.14.0, is in [Measured Type's README](https://github.com/PetriLahdelma/measured-type#pairs-with-rhythmguard).
|
|
140
|
+
|
|
120
141
|
## Compatibility
|
|
121
142
|
|
|
122
|
-
Stylelint 16 and 17. Node 20.19 or newer; Node 20 itself is end of life, and 4.0 raises the floor to 22.22 ([#172](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues/172)). The ESLint companion needs ESLint 8 or newer, is tested on ESLint 9, and has been checked by hand on
|
|
143
|
+
Stylelint 16 and 17. Node 20.19 or newer; Node 20 itself is end of life, and 4.0 raises the floor to 22.22 ([#172](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues/172)). The ESLint companion needs ESLint 8 or newer, is tested on ESLint 9 and 10, and has been checked by hand on Oxlint 1.85. Three runtime dependencies (`known-css-properties`, `postcss`, `postcss-value-parser`); `postcss-scss`, `stylelint-config-tailwindcss` and `stylelint-plugin-logical-css` are optional peers. CommonJS and ESM entry points, TypeScript declarations for every export. The CI matrix runs Node 20 and 22 against Stylelint 16.0.0, 16.x and 17.x, and Node 24 and 26 against 17.x; a weekly job runs the suite against Stylelint `next` (18.0.0-next.0 passes). Upgrading from 2.x: [docs/MIGRATING_TO_3.md](docs/MIGRATING_TO_3.md).
|
|
123
144
|
|
|
124
145
|
## Contributing and support
|
|
125
146
|
|
|
126
|
-
|
|
147
|
+
Questions and ideas: [Discussions](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/discussions). Bugs and false positives: [GitHub issues](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues). Want to help? Issues labelled [good first issue](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/labels/good%20first%20issue) name the files to touch and how to know you are done, and [CONTRIBUTING.md](CONTRIBUTING.md) gets you from clone (or a [Codespace](https://codespaces.new/PetriLahdelma/stylelint-plugin-rhythmguard)) to a passing `npm run check`. Development setup, semver policy, the feature freeze until 4.0 and the release process are there too. Security: see [SECURITY.md](SECURITY.md).
|
|
127
148
|
|
|
128
149
|
## License
|
|
129
150
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stylelint-plugin-rhythmguard",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.15.0",
|
|
4
4
|
"description": "Nobody chose 13px. Catches off-scale spacing in CSS and Tailwind class strings and snaps it to your scale or tokens. Stylelint rules, an ESLint companion, and an audit CLI.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"rhythmguard": "src/cli/index.js"
|
|
@@ -132,6 +132,7 @@
|
|
|
132
132
|
"bench:perf": "node scripts/bench/compare.mjs",
|
|
133
133
|
"bench:perf:fix": "node scripts/bench/compare.mjs --fix",
|
|
134
134
|
"bench:quiet": "node scripts/bench/quiet.mjs",
|
|
135
|
+
"check": "npm run lint && npm run typecheck && npm test",
|
|
135
136
|
"lint": "eslint .",
|
|
136
137
|
"scales:add": "node scripts/scales/add-scale.mjs",
|
|
137
138
|
"scales:validate": "node scripts/scales/validate-community-scales.mjs",
|
|
@@ -180,7 +181,7 @@
|
|
|
180
181
|
"postcss-value-parser": "^4.2.0"
|
|
181
182
|
},
|
|
182
183
|
"devDependencies": {
|
|
183
|
-
"@anthropic-ai/sdk": "^0.
|
|
184
|
+
"@anthropic-ai/sdk": "^0.137.0",
|
|
184
185
|
"@eslint/js": "^10.0.0",
|
|
185
186
|
"@types/node": "^22.20.1",
|
|
186
187
|
"c8": "^12.0.0",
|
package/src/audit/args.js
CHANGED
|
@@ -59,6 +59,8 @@ const OPTIONS = [
|
|
|
59
59
|
apply: (p) => { p.checkMathBounds = true; setFrom(p, 'checkMathBounds'); } },
|
|
60
60
|
{ flag: '--include-motion', kind: 'flag', help: 'Include opt-in motion duration/easing drift',
|
|
61
61
|
apply: (p) => { p.includeMotion = true; setFrom(p, 'includeMotion'); } },
|
|
62
|
+
{ flag: '--include-non-authored', kind: 'flag', help: ['Audit vendored, test, generated, minified and built stylesheets', '(skipped by default: vendor/, tests/, generated/, *.min.css, one-line CSS over 5 KB)'],
|
|
63
|
+
apply: (p) => { p.includeNonAuthored = true; setFrom(p, 'includeNonAuthored'); } },
|
|
62
64
|
{ flag: '--token-source', kind: 'value', value: '<file>', help: 'External token source (repeatable, comma-separated)',
|
|
63
65
|
apply: (p, raw) => { p.tokenSources.push(...parseTokenSourcePaths(raw)); setFrom(p, 'tokenSources'); } },
|
|
64
66
|
{ flag: '--token-source-format', kind: 'value', value: '<format>', help: 'Token source format: auto, css, flat-json, style-dictionary, dtcg (default: auto)',
|
package/src/audit/codemod.js
CHANGED
|
@@ -8,8 +8,9 @@ const { PROPERTY_GROUP_PATTERNS } = require('../core/css-vocabulary');
|
|
|
8
8
|
const { numbersEqual, parseLengthToken, toPx } = require('../core/length');
|
|
9
9
|
const { negateReplacement } = require('../core/token-index');
|
|
10
10
|
const { isTokenFunction, propertyMatches, walkRootValueNodes } = require('../core/value-nodes');
|
|
11
|
+
const { nonAuthoredReason } = require('./non-authored');
|
|
11
12
|
const { formatPath } = require('./shared');
|
|
12
|
-
const { isCssFile, isPathInside, isScssFile, isTemplateFile, walkFiles } = require('./scan/files');
|
|
13
|
+
const { isCssFile, isPathInside, isScssFile, isTemplateFile, toPosixRelativePath, walkFiles } = require('./scan/files');
|
|
13
14
|
const { resolveScssSyntax } = require('./scan/stylesheets');
|
|
14
15
|
|
|
15
16
|
/**
|
|
@@ -134,7 +135,7 @@ function parseStylesheet(filePath, source) {
|
|
|
134
135
|
* as the audit takes them; the audit's generated and vendored directories
|
|
135
136
|
* (node_modules, dist, build and the rest of SKIP_DIRS) are always skipped.
|
|
136
137
|
*/
|
|
137
|
-
function runCodemod({ baseFontSize = 16, dir, ignorePatterns = [], properties = null, px, replacement, replacements, write = false }) {
|
|
138
|
+
function runCodemod({ baseFontSize = 16, dir, ignorePatterns = [], includeNonAuthored = false, properties = null, px, replacement, replacements, write = false }) {
|
|
138
139
|
const rootDir = path.resolve(process.cwd(), dir);
|
|
139
140
|
const walked = walkFiles(rootDir, ignorePatterns);
|
|
140
141
|
const files = walked.cssFiles.filter(isCssFile).sort();
|
|
@@ -144,7 +145,14 @@ function runCodemod({ baseFontSize = 16, dir, ignorePatterns = [], properties =
|
|
|
144
145
|
.map((link) => ({ file: formatPath(path.join(rootDir, link)), reason: 'symbolic link to a path outside the directory; not followed' }));
|
|
145
146
|
const realRoot = fs.realpathSync(rootDir);
|
|
146
147
|
const rewritten = new Set();
|
|
148
|
+
let nonAuthoredSkipped = 0;
|
|
147
149
|
for (const filePath of files) {
|
|
150
|
+
// The audit's non-authored check, judged relative to the same root, so a
|
|
151
|
+
// decision from --plan never rewrites a file the plan did not show (#331).
|
|
152
|
+
if (!includeNonAuthored && nonAuthoredReason(toPosixRelativePath(rootDir, filePath), () => fs.readFileSync(filePath, 'utf8'))) {
|
|
153
|
+
nonAuthoredSkipped += 1;
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
148
156
|
// Never write through a symbolic link: a file is rewritten only at its own
|
|
149
157
|
// path inside the directory, and only once (#289).
|
|
150
158
|
const realPath = writableRealPath(filePath, rootDir, realRoot);
|
|
@@ -178,7 +186,7 @@ function runCodemod({ baseFontSize = 16, dir, ignorePatterns = [], properties =
|
|
|
178
186
|
}
|
|
179
187
|
results.push({ changes, file: formatPath(filePath) });
|
|
180
188
|
}
|
|
181
|
-
return { results, skipped };
|
|
189
|
+
return { nonAuthoredSkipped, results, skipped };
|
|
182
190
|
}
|
|
183
191
|
|
|
184
192
|
/**
|
package/src/audit/config.js
CHANGED
|
@@ -110,6 +110,7 @@ function applyAuditConfig(parsed, configResult) {
|
|
|
110
110
|
applyConfigScalar(next, audit, cliOptions, 'tokenKind', 'tokenKind', normalizeTokenKind);
|
|
111
111
|
applyConfigScalar(next, audit, cliOptions, 'baseFontSize', 'baseFontSize', parseBaseFontSize);
|
|
112
112
|
applyConfigScalar(next, audit, cliOptions, 'includeMotion', 'includeMotion', parseBooleanOption);
|
|
113
|
+
applyConfigScalar(next, audit, cliOptions, 'includeNonAuthored', 'includeNonAuthored', parseBooleanOption);
|
|
113
114
|
applyConfigScalar(next, audit, cliOptions, 'checkMathBounds', 'checkMathBounds', parseBooleanOption);
|
|
114
115
|
applyConfigScalar(next, audit, cliOptions, 'scales', 'scales', parseGroupScales);
|
|
115
116
|
if (audit.ladders !== undefined) {
|
package/src/audit/contract.js
CHANGED
|
@@ -234,6 +234,7 @@ function buildReport({
|
|
|
234
234
|
includeMotion,
|
|
235
235
|
linksOutsideRoot = [],
|
|
236
236
|
motionFindings,
|
|
237
|
+
nonAuthoredFiles = [],
|
|
237
238
|
parseErrorFindings = [],
|
|
238
239
|
readSource,
|
|
239
240
|
scale,
|
|
@@ -322,6 +323,9 @@ function buildReport({
|
|
|
322
323
|
scssFiles,
|
|
323
324
|
scssSkipped,
|
|
324
325
|
stylelintIgnored,
|
|
326
|
+
// Vendored, minified or built stylesheets left out of the audit (#161).
|
|
327
|
+
nonAuthoredSkipped: nonAuthoredFiles.length,
|
|
328
|
+
nonAuthoredFiles,
|
|
325
329
|
templateFiles: templateFiles.length,
|
|
326
330
|
totalFiles,
|
|
327
331
|
// Symbolic links that resolve outside the scanned directory: not followed (#289).
|
|
@@ -466,7 +470,30 @@ const AUDIT_JSON_SCHEMA = Object.freeze({
|
|
|
466
470
|
},
|
|
467
471
|
type: 'object',
|
|
468
472
|
},
|
|
469
|
-
scanned: {
|
|
473
|
+
scanned: {
|
|
474
|
+
additionalProperties: true,
|
|
475
|
+
properties: {
|
|
476
|
+
nonAuthoredFiles: {
|
|
477
|
+
description: 'Stylesheets not audited because they look vendored, generated, test-only, minified or built. Empty with --include-non-authored.',
|
|
478
|
+
items: {
|
|
479
|
+
additionalProperties: false,
|
|
480
|
+
properties: {
|
|
481
|
+
file: { type: 'string' },
|
|
482
|
+
reason: { enum: ['path', 'minified', 'bundle'] },
|
|
483
|
+
},
|
|
484
|
+
required: ['file', 'reason'],
|
|
485
|
+
type: 'object',
|
|
486
|
+
},
|
|
487
|
+
type: 'array',
|
|
488
|
+
},
|
|
489
|
+
nonAuthoredSkipped: {
|
|
490
|
+
description: 'Number of stylesheets in nonAuthoredFiles.',
|
|
491
|
+
minimum: 0,
|
|
492
|
+
type: 'integer',
|
|
493
|
+
},
|
|
494
|
+
},
|
|
495
|
+
type: 'object',
|
|
496
|
+
},
|
|
470
497
|
schemaVersion: { const: '2.0' },
|
|
471
498
|
summary: {
|
|
472
499
|
additionalProperties: true,
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* What the audit counts as non-authored CSS (#161): vendored, test, generated
|
|
5
|
+
* and built stylesheets. One definition for every part of the audit: scale
|
|
6
|
+
* inference and token chains never read these files, and the findings side
|
|
7
|
+
* skips them unless `--include-non-authored` is passed. The quiet benchmark's
|
|
8
|
+
* `noise:non-authored` path rule covers the same segments.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A path segment that marks a directory as not written by the project: tests
|
|
13
|
+
* and fixtures, vendored and third-party code, generated output and Storybook
|
|
14
|
+
* builds. Matched against the root-relative path, whole segments only, so
|
|
15
|
+
* `src/vendorize.css` stays authored. `lib` and `libs` are not on the list:
|
|
16
|
+
* Discourse's `stylesheets/lib/`, SvelteKit's `src/lib/` and Nx's `libs/`
|
|
17
|
+
* hold the project's own code.
|
|
18
|
+
*/
|
|
19
|
+
const NON_AUTHORED_SEGMENT = /(^|\/)(test|tests|__tests__|spec|specs|fixtures?|__fixtures__|__snapshots__|e2e|vendors?|third[-_]?party|jquery-ui|font-?awesome|generated|node_modules|dist|build|storybook-static|\.storybook)(\/|$)/i;
|
|
20
|
+
|
|
21
|
+
const MINIFIED_FILE = /\.min\.css$/i;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* A built bundle: its code, comments aside, is one line longer than this many
|
|
25
|
+
* bytes. 5 KB is well past any hand-written one-line stylesheet (a reset or a
|
|
26
|
+
* single component) and well under a framework or app bundle, which run from
|
|
27
|
+
* tens of KB up. A license banner or a trailing source map comment on lines of
|
|
28
|
+
* their own does not make a bundle multi-line.
|
|
29
|
+
*/
|
|
30
|
+
const BUNDLE_MIN_BYTES = 5 * 1024;
|
|
31
|
+
|
|
32
|
+
const COMMENT = /\/\*[\s\S]*?\*\//g;
|
|
33
|
+
|
|
34
|
+
function isNonAuthoredPath(relativePath) {
|
|
35
|
+
const file = String(relativePath).replace(/\\/g, '/');
|
|
36
|
+
return NON_AUTHORED_SEGMENT.test(file) || MINIFIED_FILE.test(file);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function isBuiltBundle(source) {
|
|
40
|
+
const text = String(source);
|
|
41
|
+
if (Buffer.byteLength(text, 'utf8') <= BUNDLE_MIN_BYTES) {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
const code = (text.includes('/*') ? text.replace(COMMENT, '') : text).trim();
|
|
45
|
+
return !code.includes('\n') && Buffer.byteLength(code, 'utf8') > BUNDLE_MIN_BYTES;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Why a stylesheet is not authored, or null when it is: `path` for a
|
|
50
|
+
* non-authored directory, `minified` for `*.min.css`, `bundle` for a one-line
|
|
51
|
+
* stylesheet over 5 KB. The file is read only when its path does not decide;
|
|
52
|
+
* one that cannot be read is left to the audit, which reports it.
|
|
53
|
+
*/
|
|
54
|
+
function nonAuthoredReason(relativePath, readSource) {
|
|
55
|
+
const file = String(relativePath).replace(/\\/g, '/');
|
|
56
|
+
if (NON_AUTHORED_SEGMENT.test(file)) {
|
|
57
|
+
return 'path';
|
|
58
|
+
}
|
|
59
|
+
if (MINIFIED_FILE.test(file)) {
|
|
60
|
+
return 'minified';
|
|
61
|
+
}
|
|
62
|
+
let source;
|
|
63
|
+
try {
|
|
64
|
+
source = readSource();
|
|
65
|
+
} catch {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
return isBuiltBundle(source) ? 'bundle' : null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
module.exports = {
|
|
72
|
+
BUNDLE_MIN_BYTES,
|
|
73
|
+
NON_AUTHORED_SEGMENT,
|
|
74
|
+
isBuiltBundle,
|
|
75
|
+
isNonAuthoredPath,
|
|
76
|
+
nonAuthoredReason,
|
|
77
|
+
};
|
|
@@ -28,6 +28,7 @@ function renderMarkdown(report) {
|
|
|
28
28
|
...(report.scanned && report.scanned.scssFiles > 0 ? [`| SCSS files scanned | ${report.scanned.scssFiles - report.scanned.scssSkipped} |`] : []),
|
|
29
29
|
...(report.scanned && report.scanned.scssSkipped > 0 ? [`| SCSS files skipped (install postcss-scss) | ${report.scanned.scssSkipped} |`] : []),
|
|
30
30
|
...(report.scanned && report.scanned.stylelintIgnored > 0 ? [`| Stylesheets ignored by .stylelintignore (not audited) | ${report.scanned.stylelintIgnored} |`] : []),
|
|
31
|
+
...(report.scanned && report.scanned.nonAuthoredSkipped > 0 ? [`| Non-authored stylesheets skipped (vendored, minified or built; --include-non-authored audits them) | ${report.scanned.nonAuthoredSkipped} |`] : []),
|
|
31
32
|
...(report.scanned && report.scanned.linksOutsideRoot > 0 ? [`| Symbolic links not followed (they point outside the scanned directory) | ${report.scanned.linksOutsideRoot} |`] : []),
|
|
32
33
|
...(parseErrors(report).length > 0 ? [`| Stylesheets that failed to parse (not audited) | ${parseErrors(report).length} |`] : []),
|
|
33
34
|
`| Files with issues | ${report.filesWithIssues} |`,
|
package/src/audit/render-text.js
CHANGED
|
@@ -22,6 +22,7 @@ function renderText(report) {
|
|
|
22
22
|
...(report.scanned && report.scanned.scssFiles > 0 ? [` SCSS files scanned ${String(report.scanned.scssFiles - report.scanned.scssSkipped).padStart(4)}`] : []),
|
|
23
23
|
...(report.scanned && report.scanned.scssSkipped > 0 ? [` SCSS files skipped ${String(report.scanned.scssSkipped).padStart(4)} (install postcss-scss to audit them)`] : []),
|
|
24
24
|
...(report.scanned && report.scanned.stylelintIgnored > 0 ? [` Ignored by .stylelintignore ${String(report.scanned.stylelintIgnored).padStart(4)} (not audited)`] : []),
|
|
25
|
+
...(report.scanned && report.scanned.nonAuthoredSkipped > 0 ? [` Non-authored skipped ${String(report.scanned.nonAuthoredSkipped).padStart(4)} (vendored, minified or built CSS; --include-non-authored audits them)`] : []),
|
|
25
26
|
...(report.scanned && report.scanned.linksOutsideRoot > 0 ? [` Links not followed ${String(report.scanned.linksOutsideRoot).padStart(4)} (they point outside the scanned directory)`] : []),
|
|
26
27
|
...(parseErrors(report).length > 0 ? [` Parse errors ${String(parseErrors(report).length).padStart(4)} (not audited)`] : []),
|
|
27
28
|
` Files with issues ${String(report.filesWithIssues).padStart(4)}`,
|
|
@@ -129,6 +130,9 @@ function appendTokenContractText(lines, tokenContract) {
|
|
|
129
130
|
for (const source of sources.slice(0, 5)) {
|
|
130
131
|
const warningSuffix = source.warnings.length > 0 ? ' (warning)' : '';
|
|
131
132
|
lines.push(` ${truncate(source.file, 42)} ${source.tokenCount}${warningSuffix}`);
|
|
133
|
+
for (const warning of source.warnings) {
|
|
134
|
+
lines.push(` ! ${warning}`);
|
|
135
|
+
}
|
|
132
136
|
}
|
|
133
137
|
}
|
|
134
138
|
|
package/src/audit/report.js
CHANGED
|
@@ -28,7 +28,8 @@ const { buildGroupScales } = require('../core/options');
|
|
|
28
28
|
const { applyDecisions, buildDecisionPlan } = require('./decisions');
|
|
29
29
|
const { collectDeclarations, resolveTokenChains, toChainsContract } = require('./token-chains');
|
|
30
30
|
const { resolveTokenLadders, toLaddersContract } = require('./token-ladders');
|
|
31
|
-
const { assertDirectory, getScanFiles, readSourceFromDisk } = require('./scan/files');
|
|
31
|
+
const { assertDirectory, getScanFiles, readSourceFromDisk, toPosixRelativePath } = require('./scan/files');
|
|
32
|
+
const { nonAuthoredReason } = require('./non-authored');
|
|
32
33
|
const { collectCssFindings, runStylelintAudit } = require('./scan/stylesheets');
|
|
33
34
|
const { collectTailwindFindings, collectTailwindMotionFindings } = require('./scan/templates');
|
|
34
35
|
|
|
@@ -39,14 +40,27 @@ async function createAuditReport(options) {
|
|
|
39
40
|
|
|
40
41
|
const scanFiles = getScanFiles(resolvedDir, ignorePatterns, parsed);
|
|
41
42
|
|
|
42
|
-
const {
|
|
43
|
+
const { scanScope, templateFiles } = scanFiles;
|
|
43
44
|
// A --staged run reads each changed file as the index holds it.
|
|
44
45
|
const readSource = scanFiles.readSource || readSourceFromDisk;
|
|
45
46
|
|
|
47
|
+
// Vendored, test, generated and built stylesheets (#161). They never shape
|
|
48
|
+
// the scale or the token chains; unless --include-non-authored, they are
|
|
49
|
+
// not audited either, like a file in a skipped directory.
|
|
50
|
+
const nonAuthored = classifyNonAuthored(scanFiles.cssFiles, resolvedDir, readSource);
|
|
51
|
+
const nonAuthoredSkipped = parsed.includeNonAuthored
|
|
52
|
+
? []
|
|
53
|
+
: scanFiles.cssFiles.filter((file) => nonAuthored.has(file));
|
|
54
|
+
const cssFiles = parsed.includeNonAuthored
|
|
55
|
+
? scanFiles.cssFiles
|
|
56
|
+
: scanFiles.cssFiles.filter((file) => !nonAuthored.has(file));
|
|
57
|
+
|
|
58
|
+
// A configured source that gives nothing is a warning, not a silent fallback (issue #163).
|
|
46
59
|
const tokenSourceResult = parseTokenSources({
|
|
47
60
|
baseFontSize: parsed.baseFontSize,
|
|
48
61
|
sources: parsed.tokenSources,
|
|
49
62
|
tokenKind: parsed.tokenKind,
|
|
63
|
+
warnWhenEmpty: true,
|
|
50
64
|
});
|
|
51
65
|
|
|
52
66
|
// The spacing scale always reads spacing tokens; --token-kind shapes the token contract only (issue #260).
|
|
@@ -61,6 +75,7 @@ async function createAuditReport(options) {
|
|
|
61
75
|
const scale = resolveAuditScale({
|
|
62
76
|
baseFontSize: parsed.baseFontSize,
|
|
63
77
|
cssFiles,
|
|
78
|
+
isNonAuthored: (file) => nonAuthored.has(file),
|
|
64
79
|
readSource,
|
|
65
80
|
requested: spacingOverride || parsed.scale,
|
|
66
81
|
tokenSourceResult: spacingSourceResult,
|
|
@@ -103,6 +118,7 @@ async function createAuditReport(options) {
|
|
|
103
118
|
includeMotion: parsed.includeMotion,
|
|
104
119
|
linksOutsideRoot: scanFiles.linksOutsideRoot || [],
|
|
105
120
|
motionFindings,
|
|
121
|
+
nonAuthoredFiles: nonAuthoredSkipped.map((file) => ({ file: formatPath(file), reason: nonAuthored.get(file) })),
|
|
106
122
|
parseErrorFindings,
|
|
107
123
|
readSource,
|
|
108
124
|
scale,
|
|
@@ -122,7 +138,7 @@ async function createAuditReport(options) {
|
|
|
122
138
|
cssFiles,
|
|
123
139
|
externalDefinitions: tokenSourceResult.definitions,
|
|
124
140
|
readSource,
|
|
125
|
-
skipFile: (file) =>
|
|
141
|
+
skipFile: (file) => nonAuthored.has(path.resolve(file)),
|
|
126
142
|
});
|
|
127
143
|
report.tokenContract.chains = toChainsContract(resolveTokenChains({
|
|
128
144
|
baseFontSize: parsed.baseFontSize,
|
|
@@ -150,6 +166,8 @@ async function createAuditReport(options) {
|
|
|
150
166
|
if (parsed.sinceBaseline || parsed.writeBaseline) {
|
|
151
167
|
const unauditedFiles = [
|
|
152
168
|
...(cssResults.unauditedFiles || []),
|
|
169
|
+
// A skipped non-authored stylesheet was not audited: its baseline findings are neither resolved nor new.
|
|
170
|
+
...nonAuthoredSkipped,
|
|
153
171
|
...parseErrorFindings.map((finding) => path.resolve(process.cwd(), finding.file)),
|
|
154
172
|
];
|
|
155
173
|
const unaudited = new Set(unauditedFiles);
|
|
@@ -188,14 +206,30 @@ function chainDefinitions(parsed) {
|
|
|
188
206
|
}).definitions;
|
|
189
207
|
}
|
|
190
208
|
|
|
191
|
-
|
|
209
|
+
/**
|
|
210
|
+
* The non-authored stylesheets among `cssFiles` (absolute paths), each with
|
|
211
|
+
* its reason (`path`, `minified` or `bundle`), judged by the path relative to
|
|
212
|
+
* the audited directory: auditing `dist` itself still skips the built bundles
|
|
213
|
+
* in it, by name or by shape, and a project checked out under a `vendor`
|
|
214
|
+
* directory is not skipped as a whole.
|
|
215
|
+
*/
|
|
216
|
+
function classifyNonAuthored(cssFiles, rootDir, readSource) {
|
|
217
|
+
const classified = new Map();
|
|
218
|
+
for (const file of cssFiles) {
|
|
219
|
+
const reason = nonAuthoredReason(toPosixRelativePath(rootDir, file), () => readSource(file));
|
|
220
|
+
if (reason) {
|
|
221
|
+
classified.set(file, reason);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return classified;
|
|
225
|
+
}
|
|
192
226
|
|
|
193
227
|
/**
|
|
194
228
|
* One project-level scale for the whole audit, with provenance.
|
|
195
229
|
* "auto": external token sources, then spacing custom properties across the scanned
|
|
196
230
|
* CSS, then the default scale. First source that yields values wins.
|
|
197
231
|
*/
|
|
198
|
-
function resolveAuditScale({ baseFontSize, cssFiles, readSource = readSourceFromDisk, requested, tokenSourceResult }) {
|
|
232
|
+
function resolveAuditScale({ baseFontSize, cssFiles, isNonAuthored = () => false, readSource = readSourceFromDisk, requested, tokenSourceResult }) {
|
|
199
233
|
if (Array.isArray(requested)) {
|
|
200
234
|
return {
|
|
201
235
|
files: [],
|
|
@@ -222,8 +256,8 @@ function resolveAuditScale({ baseFontSize, cssFiles, readSource = readSourceFrom
|
|
|
222
256
|
const matchesKind = createTokenKindMatcher('spacing');
|
|
223
257
|
for (const filePath of cssFiles) {
|
|
224
258
|
// Test, fixture and vendored stylesheets often redefine tokens to exercise
|
|
225
|
-
// overrides; they
|
|
226
|
-
if (
|
|
259
|
+
// overrides; they must not shape the inferred scale, even when audited.
|
|
260
|
+
if (isNonAuthored(filePath)) {
|
|
227
261
|
continue;
|
|
228
262
|
}
|
|
229
263
|
let text;
|
package/src/audit/shared.js
CHANGED
package/src/cli/doctor.js
CHANGED
|
@@ -6,7 +6,8 @@ const { applyAuditConfig, loadAuditConfig, resolveIgnorePatterns } = require('..
|
|
|
6
6
|
const { createDefaultAuditOptions } = require('../audit/shared');
|
|
7
7
|
const { normalizeDecisions } = require('../core/decisions');
|
|
8
8
|
const { readJsonFile } = require('../core/json');
|
|
9
|
-
const {
|
|
9
|
+
const { normalizeTokenSourceEntry } = require('../core/token-source-entries');
|
|
10
|
+
const { normalizeTokenSourceFormat, parseTokenSources } = require('../core/token-sources');
|
|
10
11
|
|
|
11
12
|
const HELP = `Usage: rhythmguard doctor
|
|
12
13
|
|
|
@@ -37,6 +38,14 @@ function skip(msg) {
|
|
|
37
38
|
process.stdout.write(`- ${msg}\n`);
|
|
38
39
|
}
|
|
39
40
|
|
|
41
|
+
let warnings = 0;
|
|
42
|
+
|
|
43
|
+
// Worth knowing, but not a failure: the exit code does not change.
|
|
44
|
+
function warn(msg) {
|
|
45
|
+
warnings++;
|
|
46
|
+
process.stdout.write(`! ${msg}\n`);
|
|
47
|
+
}
|
|
48
|
+
|
|
40
49
|
// Check 1: Stylelint installed
|
|
41
50
|
function checkStylelint() {
|
|
42
51
|
try {
|
|
@@ -313,12 +322,29 @@ function checkRhythmguardTokenSources(audit, baseDir) {
|
|
|
313
322
|
|
|
314
323
|
if (fs.existsSync(path.resolve(baseDir, sourcePath))) {
|
|
315
324
|
pass(`token source found (${sourcePath})`);
|
|
325
|
+
warnAboutTokenSource(source, baseDir);
|
|
316
326
|
} else {
|
|
317
327
|
fail(`token source not found (${sourcePath})`, 'Update audit.tokenSources or create the token file');
|
|
318
328
|
}
|
|
319
329
|
}
|
|
320
330
|
}
|
|
321
331
|
|
|
332
|
+
/**
|
|
333
|
+
* Read a token source the way the audit reads it for the spacing scale, and
|
|
334
|
+
* pass on what the audit would warn about: a file that does not parse, skipped
|
|
335
|
+
* tokens, or no spacing tokens at all (issue #163). Warnings, not failures.
|
|
336
|
+
*/
|
|
337
|
+
function warnAboutTokenSource(entry, baseDir) {
|
|
338
|
+
const { source } = normalizeTokenSourceEntry(entry, baseDir);
|
|
339
|
+
if (!source) {
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
const parsed = parseTokenSources({ sources: [source], tokenKind: 'spacing', warnWhenEmpty: true });
|
|
343
|
+
for (const message of parsed.warnings) {
|
|
344
|
+
warn(message);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
322
348
|
function checkRhythmguardMotionConfig(audit) {
|
|
323
349
|
if (audit.includeMotion === undefined) {
|
|
324
350
|
skip('motion audit check skipped (not configured)');
|
|
@@ -374,11 +400,12 @@ function run() {
|
|
|
374
400
|
|
|
375
401
|
process.stdout.write('\n');
|
|
376
402
|
|
|
403
|
+
const warningNote = warnings > 0 ? ` (${warnings} warning${warnings === 1 ? '' : 's'})` : '';
|
|
377
404
|
if (issues === 0) {
|
|
378
|
-
process.stdout.write(
|
|
405
|
+
process.stdout.write(`All checks passed${warningNote}.\n\n`);
|
|
379
406
|
} else {
|
|
380
407
|
process.stdout.write(
|
|
381
|
-
`${issues} issue${issues === 1 ? '' : 's'} found.\n\n`,
|
|
408
|
+
`${issues} issue${issues === 1 ? '' : 's'} found${warningNote}.\n\n`,
|
|
382
409
|
);
|
|
383
410
|
}
|
|
384
411
|
|
package/src/cli/fix.js
CHANGED
|
@@ -9,8 +9,10 @@ const { normalizeCreateAuditOptions } = require('../audit/report');
|
|
|
9
9
|
const { assertDirectory } = require('../audit/scan/files');
|
|
10
10
|
const { DEFAULT_IGNORE_PATH } = require('../audit/shared');
|
|
11
11
|
|
|
12
|
-
// --ignore
|
|
13
|
-
|
|
12
|
+
// --ignore, --ignore-path and --include-non-authored are the audit's own flags,
|
|
13
|
+
// parsed by the audit's table, so fix skips exactly what the audit skips (#331).
|
|
14
|
+
const SHARED_FLAGS = new Set(['--ignore', '--ignore-path', '--include-non-authored']);
|
|
15
|
+
const IGNORE_OPTIONS = AUDIT_OPTIONS.filter((option) => SHARED_FLAGS.has(option.flag));
|
|
14
16
|
|
|
15
17
|
const HELP = `Usage: rhythmguard fix <dir> --value <length> --to <replacement> [options]
|
|
16
18
|
rhythmguard fix <dir> --decided [options]
|
|
@@ -20,8 +22,8 @@ execute the snap decisions in .rhythmguardrc.json that name a "to". Matching is
|
|
|
20
22
|
by px, so --value 10px also rewrites 0.625rem. Token definitions, values inside
|
|
21
23
|
var()/theme()/token(), and non-spacing properties are never touched. Dry run by
|
|
22
24
|
default. Files the audit skips are skipped too: .rhythmguardignore, audit.ignore
|
|
23
|
-
in .rhythmguardrc.json, --ignore,
|
|
24
|
-
|
|
25
|
+
in .rhythmguardrc.json, --ignore, generated directories such as node_modules
|
|
26
|
+
and dist, and vendored, test, minified and built stylesheets.
|
|
25
27
|
|
|
26
28
|
Options:
|
|
27
29
|
--value <length> The literal to replace, for example 10px or 0.625rem
|
|
@@ -31,6 +33,7 @@ Options:
|
|
|
31
33
|
--base-font-size <px> Base for rem/em conversion (default: 16)
|
|
32
34
|
--ignore <pattern> Exclude a root-relative path or glob (repeatable, comma-separated)
|
|
33
35
|
--ignore-path <file> Load ignore patterns from file (default: .rhythmguardignore when present)
|
|
36
|
+
--include-non-authored Rewrite vendored, test, minified and built stylesheets too
|
|
34
37
|
--write Apply the changes; without it, only list them
|
|
35
38
|
--help Show this help message
|
|
36
39
|
`;
|
|
@@ -44,6 +47,7 @@ function parseArgs(argv) {
|
|
|
44
47
|
help: false,
|
|
45
48
|
ignorePath: DEFAULT_IGNORE_PATH,
|
|
46
49
|
ignorePatterns: [],
|
|
50
|
+
includeNonAuthored: false,
|
|
47
51
|
properties: null,
|
|
48
52
|
replacement: null,
|
|
49
53
|
value: null,
|
|
@@ -53,7 +57,8 @@ function parseArgs(argv) {
|
|
|
53
57
|
const arg = argv[index];
|
|
54
58
|
const next = () => argv[++index];
|
|
55
59
|
const ignoreOption = IGNORE_OPTIONS.find((option) => arg === option.flag || arg.startsWith(`${option.flag}=`));
|
|
56
|
-
if (ignoreOption
|
|
60
|
+
if (ignoreOption && ignoreOption.kind === 'flag' && arg === ignoreOption.flag) ignoreOption.apply(parsed);
|
|
61
|
+
else if (ignoreOption && ignoreOption.kind !== 'flag') ignoreOption.apply(parsed, arg === ignoreOption.flag ? next() : arg.slice(ignoreOption.flag.length + 1));
|
|
57
62
|
else if (arg === '--help' || arg === '-h') parsed.help = true;
|
|
58
63
|
else if (arg === '--write') parsed.write = true;
|
|
59
64
|
else if (arg === '--decided') parsed.decided = true;
|
|
@@ -85,16 +90,19 @@ function lengthToPx(value, baseFontSize) {
|
|
|
85
90
|
}
|
|
86
91
|
|
|
87
92
|
/**
|
|
88
|
-
*
|
|
89
|
-
* audit.ignore and audit.
|
|
93
|
+
* What to skip, loaded exactly as the audit loads it: .rhythmguardrc.json's
|
|
94
|
+
* audit.ignore, audit.ignorePath and audit.includeNonAuthored, the ignore file,
|
|
95
|
+
* then --ignore and --include-non-authored.
|
|
90
96
|
*/
|
|
91
|
-
function
|
|
92
|
-
|
|
97
|
+
function auditSkipOptions(parsed) {
|
|
98
|
+
const options = normalizeCreateAuditOptions({
|
|
93
99
|
cliOptions: parsed.cliOptions,
|
|
94
100
|
dir: parsed.dir,
|
|
95
101
|
ignorePath: parsed.ignorePath,
|
|
96
102
|
ignorePatterns: parsed.ignorePatterns,
|
|
97
|
-
|
|
103
|
+
includeNonAuthored: parsed.includeNonAuthored,
|
|
104
|
+
});
|
|
105
|
+
return { ignorePatterns: resolveIgnorePatterns(options), includeNonAuthored: options.includeNonAuthored === true };
|
|
98
106
|
}
|
|
99
107
|
|
|
100
108
|
/** The replacements to run: one from --value/--to, or every snap decision with a "to". */
|
|
@@ -134,13 +142,13 @@ function run() {
|
|
|
134
142
|
}
|
|
135
143
|
|
|
136
144
|
let plan;
|
|
137
|
-
let
|
|
145
|
+
let skipOptions;
|
|
138
146
|
try {
|
|
139
147
|
// The same check, and the same message, as the audit: a missing path or a
|
|
140
148
|
// file reads "Directory not found" or "Not a directory", not a stack trace (#288).
|
|
141
149
|
assertDirectory(parsed.dir);
|
|
142
150
|
plan = plannedReplacements(parsed);
|
|
143
|
-
|
|
151
|
+
skipOptions = auditSkipOptions(parsed);
|
|
144
152
|
} catch (error) {
|
|
145
153
|
process.stderr.write(`${error.message}\n`);
|
|
146
154
|
process.exit(1);
|
|
@@ -152,11 +160,12 @@ function run() {
|
|
|
152
160
|
// Every replacement in one pass over the original values: a value one snap
|
|
153
161
|
// writes is never snapped again, and the dry run lists exactly what --write writes.
|
|
154
162
|
const outcome = plan.replacements.length === 0
|
|
155
|
-
? { results: [], skipped: [] }
|
|
163
|
+
? { nonAuthoredSkipped: 0, results: [], skipped: [] }
|
|
156
164
|
: runCodemod({
|
|
157
165
|
baseFontSize: parsed.baseFontSize,
|
|
158
166
|
dir: parsed.dir,
|
|
159
|
-
ignorePatterns,
|
|
167
|
+
ignorePatterns: skipOptions.ignorePatterns,
|
|
168
|
+
includeNonAuthored: skipOptions.includeNonAuthored,
|
|
160
169
|
properties: parsed.properties,
|
|
161
170
|
replacements: plan.replacements,
|
|
162
171
|
write: parsed.write,
|
|
@@ -180,6 +189,10 @@ function run() {
|
|
|
180
189
|
const noun2 = plan.skippedSnaps.length === 1 ? 'snap decision has' : 'snap decisions have';
|
|
181
190
|
lines.push(`${plan.skippedSnaps.length} ${noun2} no "to" and ${plan.skippedSnaps.length === 1 ? 'was' : 'were'} skipped: ${plan.skippedSnaps.join(', ')}`);
|
|
182
191
|
}
|
|
192
|
+
if (outcome.nonAuthoredSkipped > 0) {
|
|
193
|
+
const noun3 = outcome.nonAuthoredSkipped === 1 ? 'file' : 'files';
|
|
194
|
+
lines.push(`${outcome.nonAuthoredSkipped} non-authored ${noun3} left alone (vendored, minified or built CSS; --include-non-authored rewrites them)`);
|
|
195
|
+
}
|
|
183
196
|
for (const entry of skipped) {
|
|
184
197
|
lines.push(`skipped ${entry.file}: ${entry.reason}`);
|
|
185
198
|
}
|
package/src/cli/quickstart.js
CHANGED
|
@@ -201,7 +201,7 @@ async function run() {
|
|
|
201
201
|
}
|
|
202
202
|
|
|
203
203
|
const scanned = report.scanned || {};
|
|
204
|
-
const skippedStylesheets = (scanned.scssSkipped || 0) + (scanned.stylelintIgnored || 0);
|
|
204
|
+
const skippedStylesheets = (scanned.scssSkipped || 0) + (scanned.stylelintIgnored || 0) + (scanned.nonAuthoredSkipped || 0);
|
|
205
205
|
if (report.cssFilesScanned === 0 && report.templateFilesScanned === 0 && skippedStylesheets === 0) {
|
|
206
206
|
out.push(' No CSS files found here. Run from your project root, or audit a directory directly:');
|
|
207
207
|
out.push(' npx rhythmguard audit ./src', '');
|
|
@@ -230,6 +230,7 @@ async function run() {
|
|
|
230
230
|
const reasons = [
|
|
231
231
|
...(scanned.scssSkipped > 0 ? [`${scanned.scssSkipped} SCSS without postcss-scss`] : []),
|
|
232
232
|
...(scanned.stylelintIgnored > 0 ? [`${scanned.stylelintIgnored} in .stylelintignore`] : []),
|
|
233
|
+
...(scanned.nonAuthoredSkipped > 0 ? [`${scanned.nonAuthoredSkipped} vendored, minified or built`] : []),
|
|
233
234
|
];
|
|
234
235
|
out.push(` Skipped ${skippedStylesheets} not audited (${reasons.join(', ')})`);
|
|
235
236
|
}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const {
|
|
4
4
|
formatLength,
|
|
5
5
|
formatNumber,
|
|
6
|
+
isHairlineLength,
|
|
6
7
|
nearestScaleValues,
|
|
7
8
|
nearestText,
|
|
8
9
|
normalizeScale,
|
|
@@ -31,6 +32,7 @@ function normalizeTailwindClassOptions(option = {}) {
|
|
|
31
32
|
? option.baseFontSize
|
|
32
33
|
: 16;
|
|
33
34
|
return {
|
|
35
|
+
allowHairlines: option.allowHairlines !== false,
|
|
34
36
|
allowNegative: option.allowNegative !== false,
|
|
35
37
|
baseFontSize,
|
|
36
38
|
scale: Array.isArray(option.scale) ? option.scale : DEFAULT_SCALE,
|
|
@@ -172,6 +174,12 @@ function analyzeClassToken(token, options, scalePx) {
|
|
|
172
174
|
return null;
|
|
173
175
|
}
|
|
174
176
|
|
|
177
|
+
// The same exemption as use-scale, and in the same order: a hairline is not
|
|
178
|
+
// reported, not even as a negative value (#159).
|
|
179
|
+
if (options.allowHairlines && isHairlineLength(parsedLength, options.baseFontSize)) {
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
|
|
175
183
|
// `-m-[16px]` and `m-[-16px]` are both negative margins (#241); in
|
|
176
184
|
// `-m-[-16px]` the two signs cancel and Tailwind writes a positive margin (#277).
|
|
177
185
|
const negative = match.groups.utility.startsWith('-') !== parsedLength.number < 0;
|
|
@@ -87,15 +87,41 @@ function createTokenKindMatcher(kind) {
|
|
|
87
87
|
return (token) => pattern.test(token);
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
+
/**
|
|
91
|
+
* Why a source that parsed gave nothing: what was looked for, and for spacing
|
|
92
|
+
* the naming rule a design-tool export most often misses (issue #163).
|
|
93
|
+
*/
|
|
94
|
+
function emptySourceWarning(source, format, tokenKind) {
|
|
95
|
+
const prefix = `Token source ${source.displayPath} (${format}) yielded no`;
|
|
96
|
+
if (source.tokenPattern) {
|
|
97
|
+
return `${prefix} tokens matching tokenPattern "${source.tokenPattern}".`;
|
|
98
|
+
}
|
|
99
|
+
if (tokenKind === 'all') {
|
|
100
|
+
return `${prefix} tokens.`;
|
|
101
|
+
}
|
|
102
|
+
if (tokenKind === 'spacing') {
|
|
103
|
+
return `${prefix} spacing tokens; spacing tokens are read by name (space, spacing or spacer), so set a tokenPattern on this source if its tokens are named otherwise.`;
|
|
104
|
+
}
|
|
105
|
+
return `${prefix} ${tokenKind} tokens.`;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Read token sources into definitions, with one report per source. With
|
|
110
|
+
* `warnWhenEmpty`, a source that parses but yields no token of the kind read
|
|
111
|
+
* gets a warning too; the audit and `rhythmguard doctor` ask for that for the
|
|
112
|
+
* token sources a project configures.
|
|
113
|
+
*/
|
|
90
114
|
function parseTokenSources({
|
|
91
115
|
baseFontSize = 16,
|
|
92
116
|
sources = [],
|
|
93
117
|
tokenKind = 'spacing',
|
|
118
|
+
warnWhenEmpty = false,
|
|
94
119
|
} = {}) {
|
|
95
120
|
const definitions = new Map();
|
|
96
121
|
const sourceReports = [];
|
|
97
122
|
const warnings = [];
|
|
98
123
|
const matchesKind = createTokenKindMatcher(tokenKind);
|
|
124
|
+
const kind = normalizeTokenKind(tokenKind);
|
|
99
125
|
|
|
100
126
|
for (const source of sources) {
|
|
101
127
|
const normalizedSource = normalizeTokenSource(source);
|
|
@@ -156,6 +182,12 @@ function parseTokenSources({
|
|
|
156
182
|
warnings.push(warning);
|
|
157
183
|
}
|
|
158
184
|
|
|
185
|
+
if (warnWhenEmpty && tokens.length === 0) {
|
|
186
|
+
const warning = emptySourceWarning(normalizedSource, sourceReport.format, kind);
|
|
187
|
+
sourceReport.warnings.push(warning);
|
|
188
|
+
warnings.push(warning);
|
|
189
|
+
}
|
|
190
|
+
|
|
159
191
|
for (const token of tokens) {
|
|
160
192
|
addDefinition(definitions, {
|
|
161
193
|
baseFontSize,
|
|
@@ -972,7 +1004,7 @@ function collectJsonTokens(parsed, matchesKind, onSkip = () => {}) {
|
|
|
972
1004
|
return tokens;
|
|
973
1005
|
}
|
|
974
1006
|
|
|
975
|
-
function walkJsonTokenGroup(group, segments, tokens, context) {
|
|
1007
|
+
function walkJsonTokenGroup(group, segments, tokens, context, inheritedType = null) {
|
|
976
1008
|
const { matchesKind, onSkip } = context;
|
|
977
1009
|
for (const [key, value] of Object.entries(group)) {
|
|
978
1010
|
if (isMetadataKey(key)) {
|
|
@@ -991,7 +1023,9 @@ function walkJsonTokenGroup(group, segments, tokens, context) {
|
|
|
991
1023
|
continue;
|
|
992
1024
|
}
|
|
993
1025
|
|
|
994
|
-
|
|
1026
|
+
// DTCG `$type` applies to the node and, on a group, to every token below it.
|
|
1027
|
+
const type = typeof value.$type === 'string' ? value.$type : inheritedType;
|
|
1028
|
+
const leaf = leafTokenValue(value, context.root, type);
|
|
995
1029
|
if (leaf !== null) {
|
|
996
1030
|
const token = key.startsWith('--')
|
|
997
1031
|
? key
|
|
@@ -1006,7 +1040,7 @@ function walkJsonTokenGroup(group, segments, tokens, context) {
|
|
|
1006
1040
|
continue;
|
|
1007
1041
|
}
|
|
1008
1042
|
|
|
1009
|
-
walkJsonTokenGroup(value, [...segments, key], tokens, context);
|
|
1043
|
+
walkJsonTokenGroup(value, [...segments, key], tokens, context, type);
|
|
1010
1044
|
}
|
|
1011
1045
|
}
|
|
1012
1046
|
|
|
@@ -1046,6 +1080,9 @@ function tokenFromPrimitive(key, value, segments) {
|
|
|
1046
1080
|
const DTCG_DIMENSION_UNITS = new Set(['px', 'rem']);
|
|
1047
1081
|
const JSON_REFERENCE = /^\{([^{}]+)\}$/;
|
|
1048
1082
|
const MAX_JSON_REFERENCE_DEPTH = 32;
|
|
1083
|
+
// Raw values that are not plain JSON: a `$ref` token and a malformed dimension.
|
|
1084
|
+
const JSON_POINTER_REF = Symbol('json pointer reference');
|
|
1085
|
+
const INVALID_DIMENSION = Symbol('invalid dimension');
|
|
1049
1086
|
|
|
1050
1087
|
function isDimensionObject(value) {
|
|
1051
1088
|
return isPlainObject(value)
|
|
@@ -1053,9 +1090,30 @@ function isDimensionObject(value) {
|
|
|
1053
1090
|
&& typeof value.unit === 'string';
|
|
1054
1091
|
}
|
|
1055
1092
|
|
|
1093
|
+
/** `{ "value": "16", "unit": "px" }` or `{ "unit": "px" }`: shaped like a dimension, not one. */
|
|
1094
|
+
function isMalformedDimension(value) {
|
|
1095
|
+
return isPlainObject(value)
|
|
1096
|
+
&& !isDimensionObject(value)
|
|
1097
|
+
&& (Object.prototype.hasOwnProperty.call(value, 'value') || Object.prototype.hasOwnProperty.call(value, 'unit'));
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
/**
|
|
1101
|
+
* A DTCG 2025.10 `$ref` token: a JSON Pointer into the same file
|
|
1102
|
+
* (`"$ref": "#/base/$value/fontSize"`) in place of `$value`. Only a node with
|
|
1103
|
+
* nothing but `$` keys is one, so a group that happens to carry `$ref` is
|
|
1104
|
+
* still walked as a group.
|
|
1105
|
+
*/
|
|
1106
|
+
function jsonPointerOf(node) {
|
|
1107
|
+
if (typeof node.$ref !== 'string' || Object.prototype.hasOwnProperty.call(node, '$value')) {
|
|
1108
|
+
return null;
|
|
1109
|
+
}
|
|
1110
|
+
return Object.keys(node).every((key) => key.startsWith('$')) ? node.$ref : null;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1056
1113
|
/**
|
|
1057
|
-
* The raw value a token node holds: `$value` (DTCG, any shape)
|
|
1058
|
-
* number `value` (Style Dictionary). Undefined when
|
|
1114
|
+
* The raw value a token node holds: `$value` (DTCG, any shape), a `$ref`
|
|
1115
|
+
* pointer, or a string or number `value` (Style Dictionary). Undefined when
|
|
1116
|
+
* the node is a group or holds something other than a length (a color).
|
|
1059
1117
|
*/
|
|
1060
1118
|
function rawTokenValue(node) {
|
|
1061
1119
|
if (!isPlainObject(node)) {
|
|
@@ -1066,7 +1124,11 @@ function rawTokenValue(node) {
|
|
|
1066
1124
|
if (typeof raw === 'string' || typeof raw === 'number' || isDimensionObject(raw)) {
|
|
1067
1125
|
return raw;
|
|
1068
1126
|
}
|
|
1069
|
-
return undefined;
|
|
1127
|
+
return isMalformedDimension(raw) ? { [INVALID_DIMENSION]: true } : undefined;
|
|
1128
|
+
}
|
|
1129
|
+
const pointer = jsonPointerOf(node);
|
|
1130
|
+
if (pointer !== null) {
|
|
1131
|
+
return { [JSON_POINTER_REF]: pointer };
|
|
1070
1132
|
}
|
|
1071
1133
|
if (isDimensionObject(node)) {
|
|
1072
1134
|
// `{ "value": 4, "unit": "rem" }` is one dimension, not a number with metadata.
|
|
@@ -1093,16 +1155,82 @@ function lookupJsonReference(root, reference) {
|
|
|
1093
1155
|
return isPlainObject(node) ? rawTokenValue(node) : node;
|
|
1094
1156
|
}
|
|
1095
1157
|
|
|
1158
|
+
/** The value a same-file JSON Pointer (`#/a/b/0`, RFC 6901) names, or undefined. */
|
|
1159
|
+
function lookupJsonPointer(root, pointer) {
|
|
1160
|
+
if (pointer === '#') {
|
|
1161
|
+
return root;
|
|
1162
|
+
}
|
|
1163
|
+
if (!pointer.startsWith('#/')) {
|
|
1164
|
+
return undefined;
|
|
1165
|
+
}
|
|
1166
|
+
let node = root;
|
|
1167
|
+
for (const encoded of pointer.slice(2).split('/')) {
|
|
1168
|
+
let segment;
|
|
1169
|
+
try {
|
|
1170
|
+
segment = decodeURIComponent(encoded).replace(/~1/g, '/').replace(/~0/g, '~');
|
|
1171
|
+
} catch {
|
|
1172
|
+
return undefined;
|
|
1173
|
+
}
|
|
1174
|
+
if (Array.isArray(node)) {
|
|
1175
|
+
if (!/^(?:0|[1-9]\d*)$/.test(segment) || Number(segment) >= node.length) {
|
|
1176
|
+
return undefined;
|
|
1177
|
+
}
|
|
1178
|
+
node = node[Number(segment)];
|
|
1179
|
+
} else if (isPlainObject(node) && Object.prototype.hasOwnProperty.call(node, segment)) {
|
|
1180
|
+
node = node[segment];
|
|
1181
|
+
} else {
|
|
1182
|
+
return undefined;
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
return node;
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
/**
|
|
1189
|
+
* A `$ref` token's value. The pointer names a value inside the file, usually a
|
|
1190
|
+
* `$value` or a part of one. A dimension object or a string is read as any
|
|
1191
|
+
* `$value` is; a number is read too, except for a `dimension` token, which
|
|
1192
|
+
* needs the whole `{ value, unit }` object. A pointer to a color or a
|
|
1193
|
+
* composite is not a length and is left out quietly; one that names nothing is
|
|
1194
|
+
* skipped with a warning.
|
|
1195
|
+
*/
|
|
1196
|
+
function resolveJsonPointer(pointer, root, stack, type) {
|
|
1197
|
+
if (stack.has(pointer)) {
|
|
1198
|
+
return { skipped: `reference cycle through "${pointer}"`, value: null };
|
|
1199
|
+
}
|
|
1200
|
+
const target = lookupJsonPointer(root, pointer);
|
|
1201
|
+
if (target === undefined) {
|
|
1202
|
+
return { skipped: `reference "${pointer}" does not resolve`, value: null };
|
|
1203
|
+
}
|
|
1204
|
+
if (typeof target === 'number' && type === 'dimension') {
|
|
1205
|
+
return { skipped: `reference "${pointer}" is a number, not a dimension`, value: null };
|
|
1206
|
+
}
|
|
1207
|
+
if (typeof target === 'string' || typeof target === 'number' || isDimensionObject(target) || isMalformedDimension(target)) {
|
|
1208
|
+
stack.add(pointer);
|
|
1209
|
+
const resolved = resolveJsonValue(isMalformedDimension(target) ? { [INVALID_DIMENSION]: true } : target, root, stack, type);
|
|
1210
|
+
stack.delete(pointer);
|
|
1211
|
+
return resolved;
|
|
1212
|
+
}
|
|
1213
|
+
return { value: null };
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1096
1216
|
/**
|
|
1097
1217
|
* A raw token value as a string: a number as written, a dimension object as
|
|
1098
|
-
* `4px` or `0.75rem`, a
|
|
1099
|
-
* reference that cannot be followed (a
|
|
1100
|
-
*
|
|
1218
|
+
* `4px` or `0.75rem`, a reference (`{spacing.2}` or a `$ref` pointer)
|
|
1219
|
+
* followed through the file. A `{}` reference that cannot be followed (a
|
|
1220
|
+
* missing target, a cycle) keeps its text, as before, and reads as a
|
|
1221
|
+
* non-length; a `$ref` that cannot be followed, a dimension in another unit
|
|
1222
|
+
* and a malformed dimension are skipped.
|
|
1101
1223
|
*/
|
|
1102
|
-
function resolveJsonValue(raw, root, stack = new Set()) {
|
|
1224
|
+
function resolveJsonValue(raw, root, stack = new Set(), type = null) {
|
|
1103
1225
|
if (typeof raw === 'number') {
|
|
1104
1226
|
return { value: String(raw) };
|
|
1105
1227
|
}
|
|
1228
|
+
if (isPlainObject(raw) && raw[INVALID_DIMENSION]) {
|
|
1229
|
+
return { skipped: 'dimension needs a number "value" and a "unit"', value: null };
|
|
1230
|
+
}
|
|
1231
|
+
if (isPlainObject(raw) && typeof raw[JSON_POINTER_REF] === 'string') {
|
|
1232
|
+
return resolveJsonPointer(raw[JSON_POINTER_REF], root, stack, type);
|
|
1233
|
+
}
|
|
1106
1234
|
if (isDimensionObject(raw)) {
|
|
1107
1235
|
const unit = raw.unit.trim().toLowerCase();
|
|
1108
1236
|
if (!Number.isFinite(raw.value) || !DTCG_DIMENSION_UNITS.has(unit)) {
|
|
@@ -1126,7 +1254,7 @@ function resolveJsonValue(raw, root, stack = new Set()) {
|
|
|
1126
1254
|
return { value: raw };
|
|
1127
1255
|
}
|
|
1128
1256
|
stack.add(target);
|
|
1129
|
-
const resolved = resolveJsonValue(next, root, stack);
|
|
1257
|
+
const resolved = resolveJsonValue(next, root, stack, type);
|
|
1130
1258
|
stack.delete(target);
|
|
1131
1259
|
if (resolved.value === null && !resolved.skipped) {
|
|
1132
1260
|
return { value: raw };
|
|
@@ -1135,12 +1263,12 @@ function resolveJsonValue(raw, root, stack = new Set()) {
|
|
|
1135
1263
|
}
|
|
1136
1264
|
|
|
1137
1265
|
/** The value of a token node, resolved; null when the node is a group, not a token. */
|
|
1138
|
-
function leafTokenValue(node, root = node) {
|
|
1266
|
+
function leafTokenValue(node, root = node, type = null) {
|
|
1139
1267
|
const raw = rawTokenValue(node);
|
|
1140
1268
|
if (raw === undefined) {
|
|
1141
1269
|
return null;
|
|
1142
1270
|
}
|
|
1143
|
-
return resolveJsonValue(raw, root);
|
|
1271
|
+
return resolveJsonValue(raw, root, new Set(), type);
|
|
1144
1272
|
}
|
|
1145
1273
|
|
|
1146
1274
|
function isMetadataKey(key) {
|
|
@@ -68,12 +68,18 @@ async function runAudit(): Promise<AuditContractReport> {
|
|
|
68
68
|
const firstText: string | undefined = report.findings.css[0]?.text;
|
|
69
69
|
const resolved: number | undefined = report.baseline?.resolvedFindingsCount;
|
|
70
70
|
const contractConfig: { file: string } | null = toAuditContractReport(report).command.config;
|
|
71
|
+
// Non-authored stylesheets: skipped by default, listed with a reason (#161).
|
|
72
|
+
const withVendored: AuditReport = await createAuditReport({ dir: './src', includeNonAuthored: true });
|
|
73
|
+
const skippedFiles: string[] = (report.scanned.nonAuthoredFiles ?? []).map((entry) => `${entry.file} (${entry.reason})`);
|
|
74
|
+
const skippedCount: number | undefined = withVendored.scanned.nonAuthoredSkipped;
|
|
71
75
|
void cleanliness;
|
|
72
76
|
void counts;
|
|
73
77
|
void configFile;
|
|
74
78
|
void firstText;
|
|
75
79
|
void resolved;
|
|
76
80
|
void contractConfig;
|
|
81
|
+
void skippedFiles;
|
|
82
|
+
void skippedCount;
|
|
77
83
|
return toAuditContractReport(report);
|
|
78
84
|
}
|
|
79
85
|
|
|
@@ -7,6 +7,13 @@ import type { ESLint, Linter } from 'eslint';
|
|
|
7
7
|
import { defineConfig } from 'eslint/config';
|
|
8
8
|
import rhythmguard from 'eslint-plugin-rhythmguard';
|
|
9
9
|
import companion from 'stylelint-plugin-rhythmguard/eslint';
|
|
10
|
+
import type { RhythmguardTailwindClassOptions } from 'stylelint-plugin-rhythmguard/eslint';
|
|
11
|
+
|
|
12
|
+
const classOptions: RhythmguardTailwindClassOptions = {
|
|
13
|
+
allowHairlines: false,
|
|
14
|
+
scale: [0, 4, 8, 12, 16, 24, 32],
|
|
15
|
+
spacingUnit: false,
|
|
16
|
+
};
|
|
10
17
|
|
|
11
18
|
const config = defineConfig([
|
|
12
19
|
{
|
|
@@ -17,6 +24,11 @@ const config = defineConfig([
|
|
|
17
24
|
'rhythmguard-tailwind/tailwind-class-use-scale': ['error', { scale: [0, 4, 8, 12, 16, 24, 32] }],
|
|
18
25
|
},
|
|
19
26
|
},
|
|
27
|
+
{
|
|
28
|
+
files: ['**/*.tsx'],
|
|
29
|
+
plugins: { 'rhythmguard-tailwind': rhythmguard },
|
|
30
|
+
rules: { 'rhythmguard-tailwind/tailwind-class-use-scale': ['error', classOptions] },
|
|
31
|
+
},
|
|
20
32
|
{
|
|
21
33
|
files: ['**/*.jsx'],
|
|
22
34
|
plugins: { 'rhythmguard-tailwind': companion },
|
package/types/audit.d.ts
CHANGED
|
@@ -48,6 +48,11 @@ export interface AuditOptions {
|
|
|
48
48
|
/** Check clamp() bounds and min()/max() arguments against the scale (equivalent to `--check-math-bounds`). */
|
|
49
49
|
checkMathBounds?: boolean;
|
|
50
50
|
includeMotion?: boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Audit vendored, test, generated, minified and built stylesheets too (equivalent to `--include-non-authored`).
|
|
53
|
+
* Off by default: they are listed in `scanned.nonAuthoredFiles` and not audited.
|
|
54
|
+
*/
|
|
55
|
+
includeNonAuthored?: boolean;
|
|
51
56
|
/** Smallest gap in px between neighbouring steps of a token ladder (`audit.ladders.minStepPx`). Default 2. */
|
|
52
57
|
ladderMinStepPx?: number;
|
|
53
58
|
/** A scale per property group (`spacing`, `radius`, `size`, `typography`): values, a preset name or "auto". Each group named is also checked. */
|
|
@@ -109,12 +114,23 @@ export interface AuditScanned {
|
|
|
109
114
|
scssSkipped?: number;
|
|
110
115
|
/** Stylesheets Stylelint skipped because the project's own .stylelintignore excludes them. */
|
|
111
116
|
stylelintIgnored?: number;
|
|
117
|
+
/** Stylesheets not audited because they look vendored, generated, test-only, minified or built. 0 with `includeNonAuthored`. */
|
|
118
|
+
nonAuthoredSkipped?: number;
|
|
119
|
+
/** The stylesheets counted in `nonAuthoredSkipped`, with why each was skipped. */
|
|
120
|
+
nonAuthoredFiles?: AuditNonAuthoredFile[];
|
|
112
121
|
templateFiles: number;
|
|
113
122
|
/** Audited stylesheets plus template files. Stylesheets that failed to parse are taken out of this for cleanliness. */
|
|
114
123
|
totalFiles?: number;
|
|
115
124
|
[key: string]: unknown;
|
|
116
125
|
}
|
|
117
126
|
|
|
127
|
+
export interface AuditNonAuthoredFile {
|
|
128
|
+
/** Path as findings name files. */
|
|
129
|
+
file: string;
|
|
130
|
+
/** `path`: a vendor, lib, test, fixture or generated directory; `minified`: `*.min.css`; `bundle`: one line of CSS over 5 KB. */
|
|
131
|
+
reason: "bundle" | "minified" | "path";
|
|
132
|
+
}
|
|
133
|
+
|
|
118
134
|
export interface AuditFinding {
|
|
119
135
|
column?: number;
|
|
120
136
|
file: string;
|
|
@@ -316,6 +332,8 @@ export function parseTokenSources(options?: {
|
|
|
316
332
|
baseFontSize?: number;
|
|
317
333
|
sources?: AuditTokenSource[];
|
|
318
334
|
tokenKind?: AuditTokenKind;
|
|
335
|
+
/** Warn about a source that parses but yields no token of `tokenKind`, as the audit does. Default false. */
|
|
336
|
+
warnWhenEmpty?: boolean;
|
|
319
337
|
}): ParsedTokenSources;
|
|
320
338
|
|
|
321
339
|
export function toAuditContractReport(report: AuditReport): AuditContractReport;
|
package/types/eslint.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { RhythmguardEslintPlugin } from "./shared";
|
|
2
2
|
|
|
3
|
-
export type { EslintRuleModule, RhythmguardEslintPlugin } from "./shared";
|
|
3
|
+
export type { EslintRuleModule, RhythmguardEslintPlugin, RhythmguardTailwindClassOptions } from "./shared";
|
|
4
4
|
|
|
5
5
|
export const configs: RhythmguardEslintPlugin["configs"];
|
|
6
6
|
export const rules: RhythmguardEslintPlugin["rules"];
|
package/types/index.d.ts
CHANGED
|
@@ -21,6 +21,7 @@ export type {
|
|
|
21
21
|
RhythmguardRuleOptions,
|
|
22
22
|
RhythmguardStylelintConfig,
|
|
23
23
|
RhythmguardStylelintRules,
|
|
24
|
+
RhythmguardTailwindClassOptions,
|
|
24
25
|
RhythmguardTransformRuleOptions,
|
|
25
26
|
RhythmguardUseScaleOptions,
|
|
26
27
|
ScaleOverride,
|
|
@@ -35,6 +36,7 @@ export type {
|
|
|
35
36
|
AuditConfigReference,
|
|
36
37
|
AuditContractReport,
|
|
37
38
|
AuditFinding,
|
|
39
|
+
AuditNonAuthoredFile,
|
|
38
40
|
AuditOptions,
|
|
39
41
|
AuditReport,
|
|
40
42
|
AuditScale,
|
package/types/shared.d.ts
CHANGED
|
@@ -211,6 +211,24 @@ export interface EslintRuleModule {
|
|
|
211
211
|
create(context: any): EslintRuleVisitor;
|
|
212
212
|
}
|
|
213
213
|
|
|
214
|
+
/** Options for `rhythmguard-tailwind/tailwind-class-use-scale`. */
|
|
215
|
+
export interface RhythmguardTailwindClassOptions {
|
|
216
|
+
/** Exempt non-zero lengths of one CSS pixel or less (`translate-y-[0.5px]`, `-mt-[1px]`, `p-[0.0625rem]`), as `use-scale` does. Default true. */
|
|
217
|
+
allowHairlines?: boolean;
|
|
218
|
+
/** Allow negative values (`-m-[16px]`, `m-[-16px]`). Default true. */
|
|
219
|
+
allowNegative?: boolean;
|
|
220
|
+
/** Base for converting `rem` and `em`. Default 16. */
|
|
221
|
+
baseFontSize?: number;
|
|
222
|
+
/** A sentence of up to 200 characters appended to every finding, after the built-in text. */
|
|
223
|
+
note?: string;
|
|
224
|
+
/** Allowed values. Default `[0, 4, 8, 12, 16, 24, 32]`. */
|
|
225
|
+
scale?: ScaleValue[];
|
|
226
|
+
/** px per Tailwind spacing step, used to write utility classes in messages and fixes. Default a quarter of `baseFontSize`; `false` keeps arbitrary values. */
|
|
227
|
+
spacingUnit?: number | false;
|
|
228
|
+
/** Units checked. Default `["px", "rem", "em"]`. */
|
|
229
|
+
units?: string[];
|
|
230
|
+
}
|
|
231
|
+
|
|
214
232
|
export interface RhythmguardEslintPlugin {
|
|
215
233
|
configs: {
|
|
216
234
|
/** A flat config that registers the plugin itself, so it can stand alone in a config array. */
|