stylelint-plugin-rhythmguard 3.19.0 → 3.20.1
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 +43 -0
- package/README.md +3 -3
- package/SECURITY.md +2 -1
- package/agents/claude-code/SKILL.md +1 -1
- package/package.json +1 -1
- package/src/audit/args.js +30 -8
- package/src/audit/baseline.js +38 -4
- package/src/audit/codemod.js +4 -2
- package/src/audit/config.js +7 -0
- package/src/audit/contract.js +124 -14
- package/src/audit/next-steps.js +3 -1
- package/src/audit/non-authored.js +1 -0
- package/src/audit/render-github.js +16 -11
- package/src/audit/render-markdown.js +8 -2
- package/src/audit/render-text.js +41 -2
- package/src/audit/render-utils.js +14 -0
- package/src/audit/report.js +230 -10
- package/src/audit/scan/files.js +14 -5
- package/src/audit/scan/stylesheets.js +48 -53
- package/src/audit/scan/templates.js +2 -0
- package/src/audit/shared.js +7 -1
- package/src/audit/token-chains.js +1 -0
- package/src/cli/audit.js +2 -2
- package/src/cli/doctor.js +853 -237
- package/src/cli/first-run.js +210 -0
- package/src/cli/index.js +25 -1
- package/src/cli/index.mjs +3 -0
- package/src/cli/init.js +42 -13
- package/src/cli/quickstart.js +53 -102
- package/src/cli/scale.js +223 -0
- package/src/configs/recommended.js +3 -1
- package/src/configs/strict.js +3 -1
- package/src/configs/tailwind.js +15 -0
- package/src/core/decisions.js +18 -5
- package/src/core/fs-cache.js +1 -0
- package/src/core/options.js +2 -1
- package/src/core/scale-inference.js +72 -52
- package/src/core/tailwind-class-analysis.js +56 -13
- package/src/core/token-index.js +55 -14
- package/src/core/token-map.js +138 -29
- package/src/core/token-sources.js +461 -40
- package/src/core/value-nodes.js +4 -2
- package/src/eslint/class-context.js +330 -0
- package/src/eslint/literal-spans.js +5 -4
- package/src/eslint/rules/tailwind-class-use-scale.js +30 -9
- package/src/presets/default-scale.js +42 -0
- package/src/presets/scales.js +6 -1
- package/src/rules/no-offscale-transform/index.js +17 -5
- package/src/rules/prefer-token/index.js +51 -15
- package/src/rules/use-scale/index.js +7 -4
- package/types/__checks__/consumer.ts +17 -0
- package/types/__checks__/eslint-config.ts +5 -0
- package/types/audit.d.ts +40 -3
- package/types/cli.d.ts +77 -1
- package/types/shared.d.ts +10 -0
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,49 @@ The format follows Keep a Changelog principles and semantic versioning.
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [3.20.1] - 2026-11-16
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- Windows: `rhythmguard audit --staged` and `--since` found no files when the project path held an 8.3 short name (`C:\Users\RUNNER~1\...`, the form Windows gives temporary directories), because git prints the long form; baseline keys from such a path climbed out of the repository. Paths are now compared after `fs.realpathSync.native`. `prefer-token` names a token's file with `/` (`src/tokens.css`), and `init --agents` prints the files it wrote with `/`. The suite now passes on Windows: 777 tests, none failing (#174).
|
|
14
|
+
|
|
15
|
+
## [3.20.0] - 2026-11-11
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
|
|
19
|
+
- The quickstart's pasted config reproduces its report. When the audit took the scale from tokens in a stylesheet, the config points `scaleSources` at that stylesheet; before, `scale: "auto"` read only the file being linted, so every other file fell back and 40px passed in the editor and failed in the audit. On a Tailwind v3 project with a config file the paste sets `tailwindConfigPath` and the next commands pass `--tailwind-config` (the quickstart itself does not load the config). It also prints the `.rhythmguardrc.json` that makes a bare `npx rhythmguard audit .` use the same scale. A contract test lints five first-run stacks with the pasted config and checks the problem count equals the audit's (dx-02, ai-01, tf-06).
|
|
20
|
+
- `init` writes exactly the config the quickstart pastes, from the same inference, shows a line diff of what it replaces before asking to overwrite, and offers to write the `.rhythmguardrc.json`. Before, it wrote `extends` alone, so `init`, the quickstart and the audit judged one project by three scales, and overwriting a quickstart config lost its `scaleSources` without showing it (dx-06).
|
|
21
|
+
- `--scale auto` in a Tailwind project with no tokens falls back to Tailwind's default ladder, the fallback `configs/tailwind` uses, instead of the default scale; `contracts.scale.preset` names the fallback. Findings only go away (css-01).
|
|
22
|
+
- One default scale. The audit without `--scale`, the audit's `--scale auto` fallback, `use-scale` with no `scale`, `configs/recommended`, `configs/strict` and the `rhythmic-4` preset now read one list, `0, 4, 8, 12, 16, 24, 32, 40, 48, 64`, exported once. Before, the audit stopped at 32, so 40, 48 and 64px were findings in the audit and not in Stylelint, and `init`, the quickstart and the audit judged one project by three scales. Audit findings only go away: on the quiet benchmark, 31 rows that fall back to the default lose 40, 48 and 64px findings and none gains one (dx-06, ai-01).
|
|
23
|
+
- `tailwind-class-use-scale` with no `scale` checks Tailwind's default spacing ladder on `spacingUnit` (`0, 2, 4, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, ... 384` on a 16px root) instead of `[0, 4, 8, 12, 16, 24, 32]`, and its messages end with `Scale: Tailwind default spacing.` `p-[20px]`, `p-[40px]` and `p-[2px]` are standard `p-5`, `p-10` and `p-0.5`, not findings. A value past the top step is still reported but no longer fixed: `p-[64px]` on a scale that ends at 32 was rewritten to `p-8`, halving the padding. With `scale` set, messages are unchanged (cs-01).
|
|
24
|
+
- The audit checks class strings against the same Tailwind ladder when the stylesheet scale is the default or the fallback, so it agrees with the ESLint rule; `contracts.scale.classStrings` and a "Class-string scale" line say so (cs-05).
|
|
25
|
+
- `configs/tailwind` sets `scale: "auto"` on `use-scale` and `no-offscale-transform`, falling back to Tailwind's default ladder instead of `rhythmic-4`. `padding: 20px`, `margin: 28px` and `inset: 44px` are Tailwind steps and no longer reported or rewritten to 16, 24 and 40px (css-01).
|
|
26
|
+
- The ESLint rule `tailwind-class-use-scale` checks class strings, not every string in a JS or TS file. Class contexts are always checked: the `className`, `class` and `*ClassName` JSX attributes and object properties; the arguments of `cn`, `clsx`, `classnames`, `cx`, `cva`, `tv`, `twMerge` and `twJoin`, with nested arrays, object keys, conditionals and `cva`/`tv` config objects; `tw` tagged templates. Any other string is checked only when it holds two or more utility-shaped tokens. Type positions (literal types, template literal types, enum members, interface and type alias members) and every other JSX, Vue or Svelte attribute (`aria-*`, `title`, `id`, `data-*`, `alt`, `placeholder`, component props) are never checked. Before, `eslint --fix` rewrote `type Size = 'p-[13px]'`, enum members, `aria-label` and `title` values, `Object.freeze({ Tight: 'p-[13px]' })` and prose. Findings outside class contexts go away, which is the intended decrease; a lone class in a plain variable (`const pad = 'p-[13px]'`) is one of them. New options `classFunctions` and `classContexts` add helper names and attribute names to the built-in lists. Vue and Svelte templates keep their `class` gate. `rhythmguard audit` still reads every string literal in a template file: its scan has no parser, and giving it one per template language is a larger change. (cs-04, fix-09, cs-08)
|
|
27
|
+
- Tailwind has no negative padding, scroll padding or gap, so the ESLint rule and the audit no longer suggest or write `-p-3` or `-gap-3`. An off-scale `-p-[13px]`, `p-[-13px]`, `-gap-[13px]` or `gap-[-13px]` is still reported, with no fix and the message `Unexpected Tailwind arbitrary spacing value "-p-[13px]". Padding and gap cannot be negative, so this class has no effect.` The first sentence is unchanged; the advice after it named a class that does not exist. Margin, inset, `top`/`right`/`bottom`/`left`, translate, `scroll-m*` and `space-*` keep their negative forms. (cs-04, fix-09, cs-08)
|
|
28
|
+
- Token sources whose names give no spacing length are read again instead of falling back. Names count in any case and with a camelCase or digit boundary (`--spacingXs` from `@tokens-studio/sd-transforms`, `--Space-1`, Style Dictionary's `Space1`), and in JSON a token typed as a dimension counts whatever its name (DTCG `$type: "dimension"`, or a `type` of `spacing`, `sizing` or `dimension`), unless its name says radius, font, border or another kind. A file whose names already gave a scale keeps exactly that scale. Tokens Studio exports are detected (`format: "tokens-studio"`) and read set by set in `tokenSetOrder` without the set name, with unitless spacing values as px and `+ - * /` over references evaluated. A DTCG 2025.10 `$root` token is read as its group's token (`space.$root` is `--space`), and a `$deprecated` token is listed as deprecated and never written by a fix or offered in a message; in 3.x its value stays on the scale, so no finding is added, and it leaves the scale in 4.0. Each entry in `contracts.tokens.sources` gains `selectedBy` (`name`, `type` or `tokenPattern`) and, when any, `deprecated`. Role-named DTCG, camelCase and Tokens Studio files that fell back to the default scale now infer their own (tf-01, tf-08, tf-11)
|
|
29
|
+
- `rhythmguard doctor` loads the Stylelint config through the project's own Stylelint (`resolveConfig`) instead of searching the config text for "rhythmguard", so every `extends`, plugin and option is resolved as `npx stylelint` resolves it. It checks that `stylelint-plugin-rhythmguard` is installed and that the installed Stylelint is in the plugin's peer range (`^16.7.0 || ^17.0.0 || ^18.0.0`). Before, with Stylelint 18 and the `init` config present but the plugin absent, doctor printed "All checks passed" and exited 0 while `npx stylelint` exited 78; it now exits 1, names the plugin and prints `npm install --save-dev "stylelint@^16.7.0 || ^17.0.0 || ^18.0.0" stylelint-plugin-rhythmguard`. `tokenPattern`, `tailwindConfigPath`, `customSyntax` and `scaleSources` are read from the resolved rule options rather than matched in the config text, and an option Stylelint rejects fails the check (dx-07, cq-11).
|
|
30
|
+
- In an ESLint-only project (no Stylelint installed or configured), doctor loads the ESLint config through the project's ESLint and lints one class-string file instead of checking that the config text mentions "rhythmguard". A config that cannot load (for example `eslint-plugin-rhythmguard` missing) or that does not enable `tailwind-class-use-scale` exits 1 with the install command, where it printed "All checks passed"; the Stylelint checks are reported as skipped, never as a missing install (ai-02).
|
|
31
|
+
- Doctor's install commands come from the same builder as the quickstart's and `init`'s: `npm install --save-dev "stylelint@<peer range>" stylelint-plugin-rhythmguard` for the Stylelint path, `npm install --save-dev eslint eslint-plugin-rhythmguard` for the ESLint path (dx-07, ai-02).
|
|
32
|
+
- `--fail-on-new-drift` gates drift, not token debt. It counts new off-scale, class-string, motion and missing-token findings; a new `token-opportunity` finding from `prefer-token`, a raw value a token could replace, stays in the report and the baseline and fails only with the new `--fail-on-new-token-debt` (`"failOnNewTokenDebt": true` under `audit` in `.rhythmguardrc.json`). Before, snapping `padding: 13px` to `12px`, the step the finding names, failed `--since-baseline --fail-on-new-drift`: `prefer-token` reported the on-scale `12px` as a new raw value. The off-scale literal is still gated through its `use-scale` finding. `baseline.newDriftCount` and `baseline.newTokenDebtCount` split `newFindingsCount`, the text, Markdown and GitHub summaries say `1 new (0 drift, 1 token debt)` when there is token debt, and `--format github` annotates new token debt as warnings, new drift as errors. Gate failures only go away (dx-08, ci-01)
|
|
33
|
+
- In the audit, `prefer-token` reads the tokens the audit resolved: the `--token-source` and `audit.tokenSources` files and the scanned stylesheets that declare spacing tokens. Its message names the token and its file, `Use var(--space-3) (tokens/tokens.json).`, through the existing template, where it said `No known token holds this value` while `rawValueMatches` listed the token. A token declared in a component block or under a media query in another stylesheet is not offered outside it. A raw fallback such as `var(--space-3, 12px)` that restates a token now known is no longer reported, so findings only go away (dx-08, ci-01, ai-04)
|
|
34
|
+
- A Stylelint warning whose text the audit does not read is a finding of `type: "unclassified"` with `value: null`, listed under `UNCLASSIFIED WARNINGS` in the text report, instead of an off-scale finding with `value: null`. With the audit's rule options no rule emits one; a contract test calls every message template of every rule and checks that each is read or listed as deliberately unclassified. The patterns also read `no-offscale-transform`'s `clamp()`, `min()` and `max()` positions, and no longer read a forbidden negative translation as off-scale (cq-02)
|
|
35
|
+
|
|
36
|
+
### Added
|
|
37
|
+
|
|
38
|
+
- `rhythmguard audit --tailwind-config <file>`: with `--scale auto`, the audit reads a Tailwind v3 config's `theme.spacing` after the scanned stylesheets (`source: "tailwind"`), as the rules do with `tailwindConfigPath`. The config is loaded with `require()`, so only when the flag names it; `.rhythmguardrc.json` cannot, and an `audit.tailwindConfigPath` key there is refused, so a file in a repository (a fork's pull request, a cloned project) never makes the audit run code. A path that does not exist exits 2, like a missing token source (tf-06).
|
|
39
|
+
- The Claude Code skill pre-approves exactly `npx rhythmguard audit . --scale auto --format json`, the command it asks for, instead of any `npx rhythmguard audit` command, since `--tailwind-config` loads a file.
|
|
40
|
+
- A `tailwind` scale preset: Tailwind's default spacing theme on a 16px root. With `scale: "auto"`, a rule's `preset` is now the fallback when no tokens are found, as `configs/tailwind` uses it.
|
|
41
|
+
- `runDoctor({ cwd })`, `formatDoctorReport(result)` and `doctorSummary(resultOrChecks)` from `stylelint-plugin-rhythmguard/cli`, with types. `runDoctor` resolves to `{ ok, setup, issues, warnings, checks, scale, eslintScale }`; each check is `{ id, status, message, fix? }` with status `pass`, `fail`, `warn` or `skip`. It keeps no module state, prints nothing and never exits the process, so it can run after each edit or from another command; `doctorSummary` gives a few lines for another command to print (cq-11).
|
|
42
|
+
- `rhythmguard doctor` lints one stylesheet with the project's config and prints the spacing scale the rules check and where it comes from: the `scale` option, a preset, the default scale, or for `scale: "auto"` the token files, `.rhythmguardrc.json`, the stylesheet, the Tailwind config, a token package or the fallback preset, resolved as the rules resolve it. When the project has an ESLint config, doctor loads it through the project's ESLint, lints one class-string file, prints the scale `tailwind-class-use-scale` checks and warns when it is not the stylesheet scale, with the `scale` option that would make them agree. It warns when `.scss` files have no `customSyntax` (dx-07).
|
|
43
|
+
- `rhythmguard scale [dir]` prints the scale the audit checks against, its source and files, a rejected inference, the class-string scale, and the tokens that hold each step, without scanning for findings. It resolves the scale through the audit's own path: `--scale`, `--token-source`, `.rhythmguardrc.json` and `--scale auto`. `--format json` prints it for agents and scripts (`schemaVersion: "1.0"`). Like the audit, it exits 2 when a configured token source does not exist (ai-04)
|
|
44
|
+
- `--report-missing-tokens` (`"reportMissingTokens": true` under `audit`, `reportMissingTokens` in the API) reports each `var()` of a token that no scanned stylesheet, token source, installed token package or skipped vendored stylesheet defines as a `missing-token` finding, with its file, line, column, property and the token as `value`. It counts in totals, baselines and `--fail-on-new-drift`. Before, `var(--space-7)` with no `--space-7` anywhere appeared only in `contracts.tokens.missingTokens`, so an invented token passed every gate. Off by default in 3.x, so default findings do not grow (ai-03)
|
|
45
|
+
|
|
46
|
+
### Fixed
|
|
47
|
+
|
|
48
|
+
- Nothing falls back in silence any more. A token source whose tokens parse but carry no length (aliases into a file that is not configured, `var()` chains, unitless values) warns with the count, three examples and why each is not a length, and the audit sets `contracts.scale.rejected` with `source: "token-sources"` instead of `rejected: null` and no warning. A `.rhythmguardrc.json` that is not valid JSON (its adopt and allow decisions were lost), a Tailwind config that throws (it read as "No known token holds this value"), a token map file that is missing or not JSON, and an invalid `tokenPattern` on a token source now say so. The warnings reach every surface: the JSON report's new root `warnings` array, the text report, the first lint message in a file (once), `doctor` and the quickstart. A repository lint rule rejects a `catch` that drops its error without a comment saying why; the 49 that remain are commented and counted by a test (tf-02, cq-05).
|
|
49
|
+
- The quickstart prints every source warning under the scale, finds `tokens.css`, `*.tokens.css` and Style Dictionary's `build/css/variables.css` and `dist/css/variables.css` as well as JSON token files, and when the token files it found give no scale, the pasted config points `scaleSources` at them, so each lint names why they were not read, instead of pasting a literal default (tf-12).
|
|
50
|
+
- Token fixes never guess and never leave a token's scope. When two tokens hold one value, `prefer-token` names both (`Use one of the tokens that hold it: var(--space-gutter) or var(--space-layout).`) and writes neither on every map source: `tokenMapFromCssCustomProperties` (on in the `tailwind` config and the playground), `tokenMapFile` and `tokenMapFromTailwindSpacing`. Before, the map kept the last token declared, so `margin: 24px` became `var(--space-layout)` while the token index named both and wrote nothing, and a `use-scale` snap followed by `prefer-token` turned `23px` into the guessed token. A token declared only under `@media`, `@supports` or `@container`, or in a component block such as `.card`, is written by `use-scale` and `no-offscale-transform` with `fixWith: "token"` and by `prefer-token` only where it is defined: under the same conditions, or inside that block. Before, `padding: 13px` became `var(--space-3)` outside the media query that defines it, which computes to no padding below the breakpoint. No rule writes a token into a `var()` fallback any more, since the fallback is what renders when the tokens are missing; the literal is written, or the value is reported and left alone. A token that is not defined where a value sits is no longer named in that value's message either. The findings and the message templates are unchanged (css-08, fix-06, fix-02)
|
|
51
|
+
|
|
9
52
|
## [3.19.0] - 2026-11-09
|
|
10
53
|
|
|
11
54
|
### Changed
|
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
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
|
|
|
@@ -21,7 +21,7 @@ What it is not: it does not check colors or hex values, and the Stylelint rules
|
|
|
21
21
|
npx rhythmguard
|
|
22
22
|
```
|
|
23
23
|
|
|
24
|
-
No install, no config. It detects your stack and token files, infers your spacing scale from your own tokens, audits the current directory, and prints the exact `.stylelintrc.json` (and ESLint snippet for Tailwind) to paste. This is the whole run on Bootstrap's `v6-dev` branch, unedited:
|
|
24
|
+
No install, no config. It detects your stack and token files, infers your spacing scale from your own tokens, audits the current directory, and prints the exact `.stylelintrc.json` (and ESLint snippet for Tailwind) to paste, with the `.rhythmguardrc.json` that makes a bare `npx rhythmguard audit .` use the same scale. This is the whole run on Bootstrap's `v6-dev` branch, unedited:
|
|
25
25
|
|
|
26
26
|
<p align="center">
|
|
27
27
|
<img src="https://raw.githubusercontent.com/petrilahdelma/stylelint-plugin-rhythmguard/main/assets/quickstart.gif?v=1" width="100%" alt="Terminal recording: npx stylelint-plugin-rhythmguard on Bootstrap v6-dev detects the stack, infers the 13-step spacing scale from scss/_config.scss, reports 20 off-scale values in CSS and prints a .stylelintrc.json to paste" />
|
|
@@ -103,7 +103,7 @@ npx rhythmguard audit ./src --format github
|
|
|
103
103
|
|
|
104
104
|
The audit scans CSS declarations, Tailwind class strings and your token contract, prints a scale-cleanliness score, and supports baselines so legacy codebases can gate only new drift. Formats: text, Markdown, JSON 2.0, HTML, GitHub Actions annotations, and a shields.io badge document for your README. Full reference in [docs/AUDIT.md](docs/AUDIT.md), rollout recipe and the badge workflow in [docs/CI_ADOPTION.md](docs/CI_ADOPTION.md). In GitHub Actions, [`PetriLahdelma/rhythmguard-action@v1`](https://github.com/PetriLahdelma/rhythmguard-action) runs the audit, annotates the diff, comments on the pull request and fails on new drift in one step.
|
|
105
105
|
|
|
106
|
-
`npx rhythmguard audit ./src --plan` turns the report into a proposed `decisions` section (adopt a value, allow it, or snap it), and `npx rhythmguard fix ./src --value 10px --to "var(--space-sm)" --write` executes one decision as one reviewable change; see [decisions](docs/AUDIT.md#decisions). `npx rhythmguard init` writes a
|
|
106
|
+
`npx rhythmguard audit ./src --plan` turns the report into a proposed `decisions` section (adopt a value, allow it, or snap it), and `npx rhythmguard fix ./src --value 10px --to "var(--space-sm)" --write` executes one decision as one reviewable change; see [decisions](docs/AUDIT.md#decisions). `npx rhythmguard scale` prints the scale the audit checks against, where it came from and the token for each step. `npx rhythmguard init` writes the config the quickstart prints, showing a diff before it replaces one, and `init --agents all` installs the coding-agent instructions. `npx rhythmguard doctor` checks the setup: it loads your Stylelint and ESLint configs as the linters do, lints one file with each, prints the spacing scale and where it comes from, and gives the exact install command for anything missing.
|
|
107
107
|
|
|
108
108
|
## Guides
|
|
109
109
|
|
package/SECURITY.md
CHANGED
|
@@ -15,7 +15,8 @@ This applies to all three packages: `stylelint-plugin-rhythmguard`, `rhythmguard
|
|
|
15
15
|
- **No network requests and no telemetry.** Nothing in the packages opens a connection, and nothing is collected or sent. `test/contracts/no-network.test.js` fails the build if any source file imports a network module or calls `fetch`.
|
|
16
16
|
- **No install scripts.** None of the three packages runs code when it is installed.
|
|
17
17
|
- **It reads** the stylesheets and class-string files it lints or audits, the token files and packages you point it at (`scaleSources`, `tokenMapFile`, `--token-source`, `.rhythmguardrc.json`), and installed design-token packages that your `package.json` lists directly.
|
|
18
|
-
- **It runs one file of yours as code, and only when you ask.** With `tailwindConfigPath` set, the rules load that Tailwind config with `require()` to read `theme.spacing`. A config that uses top-level await is not loaded. To avoid running it at all, point `scaleSources` at the CSS it builds instead.
|
|
18
|
+
- **It runs one file of yours as code, and only when you ask.** With `tailwindConfigPath` set in a Stylelint config, the rules load that Tailwind config with `require()` to read `theme.spacing`; `rhythmguard audit` does the same only with `--tailwind-config <file>` on the command line, never from `.rhythmguardrc.json`, so a file in a repository cannot make the audit run code. A config that uses top-level await is not loaded. To avoid running it at all, point `scaleSources` at the CSS it builds instead.
|
|
19
|
+
- **`rhythmguard doctor` loads your linter configs as the linters do.** It resolves your Stylelint config through your installed Stylelint and, when there is one, your ESLint config through your installed ESLint, and lints one file with each, so any JavaScript config or plugin they name runs, as it does when you run `npx stylelint` or `npx eslint`. `rhythmguard audit` loads neither.
|
|
19
20
|
- **It starts one program: `git`,** and only for `rhythmguard audit --since` and `--staged`, to list changed files and read staged contents. The source test above allows no other process.
|
|
20
21
|
- **It writes files only when you ask:** `stylelint --fix` and `eslint --fix` through the host linter, `rhythmguard fix --write`, `audit --write-baseline` and `audit --output <file>`, and `rhythmguard init`, which asks before writing a config or agent files.
|
|
21
22
|
- **Provenance.** Every release is published from this repository's `release.yml` through npm trusted publishing, with no npm token anywhere, and carries an npm provenance attestation. Check it with `npm audit signatures` in a project that installs the package, or `npm view stylelint-plugin-rhythmguard dist.attestations`.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
name: rhythmguard
|
|
3
3
|
description: Keep CSS and Tailwind spacing on the project scale. Use when writing or changing CSS, SCSS, CSS Modules or Tailwind class strings, and before finishing any such change.
|
|
4
4
|
when_to_use: Adding or changing padding, margin, gap, inset or other spacing in a stylesheet or a class string; reviewing a diff that does.
|
|
5
|
-
allowed-tools: Bash(npx rhythmguard audit
|
|
5
|
+
allowed-tools: Bash(npx rhythmguard audit . --scale auto --format json)
|
|
6
6
|
paths:
|
|
7
7
|
- "**/*.css"
|
|
8
8
|
- "**/*.scss"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stylelint-plugin-rhythmguard",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.20.1",
|
|
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"
|
package/src/audit/args.js
CHANGED
|
@@ -46,8 +46,10 @@ const OPTIONS = [
|
|
|
46
46
|
apply: (p, raw) => { p.writeBaseline = true; setFrom(p, 'writeBaseline'); if (raw !== undefined) { p.baselinePath = parsePathOption(raw, '--write-baseline'); setFrom(p, 'baselinePath'); } } },
|
|
47
47
|
{ flag: '--since-baseline', kind: 'optional', value: '[file]', help: 'Compare current findings against a baseline',
|
|
48
48
|
apply: (p, raw) => { p.sinceBaseline = true; setFrom(p, 'sinceBaseline'); if (raw !== undefined) { p.baselinePath = parsePathOption(raw, '--since-baseline'); setFrom(p, 'baselinePath'); } } },
|
|
49
|
-
{ flag: '--fail-on-new-drift', kind: 'flag', help: 'Exit 1 when --since-baseline finds new drift',
|
|
49
|
+
{ flag: '--fail-on-new-drift', kind: 'flag', help: ['Exit 1 when --since-baseline finds new drift: off-scale, class-string,', 'motion and missing-token findings, not token debt'],
|
|
50
50
|
apply: (p) => { p.failOnNewDrift = true; setFrom(p, 'failOnNewDrift'); } },
|
|
51
|
+
{ flag: '--fail-on-new-token-debt', kind: 'flag', help: ['Exit 1 when --since-baseline finds new token debt: raw values', 'prefer-token says a token could replace'],
|
|
52
|
+
apply: (p) => { p.failOnNewTokenDebt = true; setFrom(p, 'failOnNewTokenDebt'); } },
|
|
51
53
|
{ flag: '--max-findings', kind: 'value', value: '<number>', help: 'Exit 1 when total findings exceed this count',
|
|
52
54
|
apply: (p, raw) => { p.maxFindings = parseNonNegativeInteger(raw, '--max-findings'); setFrom(p, 'maxFindings'); } },
|
|
53
55
|
{ flag: '--min-cleanliness', kind: 'value', value: '<percent>', help: 'Exit 1 when scale cleanliness is lower than this percent',
|
|
@@ -57,6 +59,8 @@ const OPTIONS = [
|
|
|
57
59
|
{ flag: '--staged', kind: 'flag', help: 'Scan only staged files', apply: (p) => { p.staged = true; setFrom(p, 'staged'); } },
|
|
58
60
|
{ flag: '--check-math-bounds', kind: 'flag', help: 'Check clamp() minimum and maximum and min()/max() arguments against the scale',
|
|
59
61
|
apply: (p) => { p.checkMathBounds = true; setFrom(p, 'checkMathBounds'); } },
|
|
62
|
+
{ flag: '--report-missing-tokens', kind: 'flag', help: ['Report each var() of a token nothing defines as a missing-token', 'finding (counted in totals, baselines and --fail-on-new-drift)'],
|
|
63
|
+
apply: (p) => { p.reportMissingTokens = true; setFrom(p, 'reportMissingTokens'); } },
|
|
60
64
|
{ flag: '--include-motion', kind: 'flag', help: 'Include opt-in motion duration/easing drift',
|
|
61
65
|
apply: (p) => { p.includeMotion = true; setFrom(p, 'includeMotion'); } },
|
|
62
66
|
{ 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)'],
|
|
@@ -69,8 +73,10 @@ const OPTIONS = [
|
|
|
69
73
|
apply: (p, raw) => { p.tokenKind = normalizeTokenKind(raw); setFrom(p, 'tokenKind'); } },
|
|
70
74
|
{ flag: '--token-candidate-min-count', kind: 'value', value: '<n>', help: 'Minimum repeated raw value count for token candidates (default: 2)',
|
|
71
75
|
apply: (p, raw) => { p.tokenCandidateMinCount = parsePositiveInteger(raw, '--token-candidate-min-count'); setFrom(p, 'tokenCandidateMinCount'); } },
|
|
72
|
-
{ flag: '--scale', kind: 'value', value: '<values|auto>', help: ['Comma-separated scale values (default: 0,4,8,12,16,24,32);', 'auto infers the scale from token sources, then --space-*/--spacing-*', 'custom properties and Sass variables in scanned CSS/SCSS, then', 'installed design-token packages, and reports where it came from'],
|
|
76
|
+
{ flag: '--scale', kind: 'value', value: '<values|auto>', help: ['Comma-separated scale values (default: 0,4,8,12,16,24,32,40,48,64);', 'auto infers the scale from token sources, then --space-*/--spacing-*', 'custom properties and Sass variables in scanned CSS/SCSS, then', '--tailwind-config, then installed design-token packages,', 'and reports where it came from'],
|
|
73
77
|
apply: (p, raw) => { p.scale = parseScale(raw); setFrom(p, 'scale'); } },
|
|
78
|
+
{ flag: '--tailwind-config', kind: 'value', value: '<file>', help: ['Tailwind v3 config whose theme.spacing --scale auto reads', '(loaded with require(), so it runs as code; only when given)'],
|
|
79
|
+
apply: (p, raw) => { p.tailwindConfigPath = parsePathOption(raw, '--tailwind-config'); setFrom(p, 'tailwindConfigPath'); } },
|
|
74
80
|
{ flag: '--base-font-size', kind: 'value', value: '<number>', help: 'px base for rem/em conversion (default: 16)',
|
|
75
81
|
apply: (p, raw) => { p.baseFontSize = parseBaseFontSize(raw); setFrom(p, 'baseFontSize'); } },
|
|
76
82
|
{ flag: '--help', alias: '-h', kind: 'flag', help: 'Show this help message', apply: (p) => { p.help = true; } },
|
|
@@ -78,9 +84,9 @@ const OPTIONS = [
|
|
|
78
84
|
|
|
79
85
|
const HELP_COLUMN = 33;
|
|
80
86
|
|
|
81
|
-
function
|
|
82
|
-
const lines = [
|
|
83
|
-
for (const option of
|
|
87
|
+
function renderOptionLines(options) {
|
|
88
|
+
const lines = [];
|
|
89
|
+
for (const option of options) {
|
|
84
90
|
const label = ` ${option.flag}${option.value ? ` ${option.value}` : ''}`;
|
|
85
91
|
const help = Array.isArray(option.help) ? option.help : [option.help];
|
|
86
92
|
lines.push(`${label.padEnd(HELP_COLUMN)}${label.length >= HELP_COLUMN ? ' ' : ''}${help[0]}`);
|
|
@@ -88,6 +94,11 @@ function renderHelp() {
|
|
|
88
94
|
lines.push(`${''.padEnd(HELP_COLUMN)}${extra}`);
|
|
89
95
|
}
|
|
90
96
|
}
|
|
97
|
+
return lines;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function renderHelp() {
|
|
101
|
+
const lines = ['Usage: rhythmguard audit <dir> [options]', '', 'Options:', ...renderOptionLines(OPTIONS)];
|
|
91
102
|
lines.push(
|
|
92
103
|
'',
|
|
93
104
|
'Scans .css files, and .scss files when postcss-scss is installed. Reports drift by',
|
|
@@ -100,12 +111,18 @@ function renderHelp() {
|
|
|
100
111
|
|
|
101
112
|
const HELP = renderHelp();
|
|
102
113
|
|
|
103
|
-
function
|
|
104
|
-
return
|
|
114
|
+
function findOptionIn(arg, options = OPTIONS) {
|
|
115
|
+
return options.find((option) => option.flag === arg || option.alias === arg) || null;
|
|
105
116
|
}
|
|
106
117
|
|
|
107
|
-
|
|
118
|
+
/**
|
|
119
|
+
* Parse audit arguments. `options` narrows the accepted flags to a subset of
|
|
120
|
+
* OPTIONS, for a command such as `rhythmguard scale` that resolves the scale
|
|
121
|
+
* the way the audit does and takes the audit's flags for it.
|
|
122
|
+
*/
|
|
123
|
+
function parseArgs(argv, options = OPTIONS) {
|
|
108
124
|
const parsed = createDefaultAuditOptions();
|
|
125
|
+
const findOption = (arg) => findOptionIn(arg, options);
|
|
109
126
|
|
|
110
127
|
for (let index = 0; index < argv.length; index++) {
|
|
111
128
|
const arg = argv[index];
|
|
@@ -155,6 +172,10 @@ function parseArgs(argv) {
|
|
|
155
172
|
throw new Error('--fail-on-new-drift requires --since-baseline.');
|
|
156
173
|
}
|
|
157
174
|
|
|
175
|
+
if (parsed.failOnNewTokenDebt && !parsed.sinceBaseline) {
|
|
176
|
+
throw new Error('--fail-on-new-token-debt requires --since-baseline.');
|
|
177
|
+
}
|
|
178
|
+
|
|
158
179
|
return parsed;
|
|
159
180
|
}
|
|
160
181
|
|
|
@@ -299,6 +320,7 @@ function parseBaseFontSize(raw) {
|
|
|
299
320
|
module.exports = {
|
|
300
321
|
OPTIONS,
|
|
301
322
|
HELP,
|
|
323
|
+
renderOptionLines,
|
|
302
324
|
parseArgs,
|
|
303
325
|
parseBaseFontSize,
|
|
304
326
|
parseIgnorePatterns,
|
package/src/audit/baseline.js
CHANGED
|
@@ -34,7 +34,7 @@ function createBaselineScope(report, scope = {}) {
|
|
|
34
34
|
const scanRoot = path.resolve(scope.scanRoot || report.directory || '.');
|
|
35
35
|
let realScanRoot = scanRoot;
|
|
36
36
|
try {
|
|
37
|
-
realScanRoot = fs.realpathSync(scanRoot);
|
|
37
|
+
realScanRoot = fs.realpathSync.native(scanRoot);
|
|
38
38
|
} catch {
|
|
39
39
|
// The directory was audited, so it exists; keep the given form if not.
|
|
40
40
|
}
|
|
@@ -103,11 +103,16 @@ function applyBaselineComparison(report, baselinePath, scopeInput) {
|
|
|
103
103
|
const newFindings = currentFindings.filter((finding) => !baselineKeys.has(currentKeys.get(finding)));
|
|
104
104
|
const resolvedFindings = entries.filter((entry) => !currentKeySet.has(entry.key) && countsAsResolved(scope, entry.file));
|
|
105
105
|
|
|
106
|
+
const newTokenDebtCount = newFindings.filter(isTokenDebtFinding).length;
|
|
106
107
|
report.baseline = {
|
|
107
108
|
baselineFindings: baselineFindings.length,
|
|
108
109
|
file: formatPath(resolvedPath),
|
|
110
|
+
// What --fail-on-new-drift counts: every new finding but token debt.
|
|
111
|
+
newDriftCount: newFindings.length - newTokenDebtCount,
|
|
109
112
|
newFindings,
|
|
110
113
|
newFindingsCount: newFindings.length,
|
|
114
|
+
// What --fail-on-new-token-debt counts.
|
|
115
|
+
newTokenDebtCount,
|
|
111
116
|
resolvedFindingsCount: resolvedFindings.length,
|
|
112
117
|
};
|
|
113
118
|
report.summary.newFindings = newFindings.length;
|
|
@@ -230,6 +235,18 @@ function legacyWriterDirectory(directory, scanRoot) {
|
|
|
230
235
|
return path.resolve(scanRoot, ...segments.map(() => '..'));
|
|
231
236
|
}
|
|
232
237
|
|
|
238
|
+
/**
|
|
239
|
+
* Token debt: a raw value prefer-token says could be a token. It is not
|
|
240
|
+
* drift. On a scale value it is what the off-scale finding asked for: 13px
|
|
241
|
+
* snapped to 12px is a fix, and a gate that failed it rejected the fix the
|
|
242
|
+
* audit recommended (dx-08, ci-01). On an off-scale value it sits at the same
|
|
243
|
+
* position as the use-scale finding, which the drift gate already counts.
|
|
244
|
+
* --fail-on-new-drift leaves it out; --fail-on-new-token-debt gates it.
|
|
245
|
+
*/
|
|
246
|
+
function isTokenDebtFinding(finding) {
|
|
247
|
+
return Boolean(finding) && finding.type === 'token-opportunity';
|
|
248
|
+
}
|
|
249
|
+
|
|
233
250
|
function getAllFindings(report) {
|
|
234
251
|
return [
|
|
235
252
|
...report.findings.css,
|
|
@@ -297,7 +314,7 @@ function createLegacyFindingKey(finding) {
|
|
|
297
314
|
|
|
298
315
|
function getAuditFailures(report, parsed) {
|
|
299
316
|
const failures = [];
|
|
300
|
-
const gated = parsed.maxFindings !== null || parsed.minCleanliness !== null || parsed.failOnNewDrift;
|
|
317
|
+
const gated = parsed.maxFindings !== null || parsed.minCleanliness !== null || parsed.failOnNewDrift || parsed.failOnNewTokenDebt === true;
|
|
301
318
|
const missing = (report.scanned && report.scanned.stylelintMissing) || 0;
|
|
302
319
|
|
|
303
320
|
// Without Stylelint the stylesheets were not audited, so no gate can pass on
|
|
@@ -316,13 +333,29 @@ function getAuditFailures(report, parsed) {
|
|
|
316
333
|
failures.push(`scale cleanliness ${report.scaleCleanliness}% is below --min-cleanliness ${parsed.minCleanliness}%`);
|
|
317
334
|
}
|
|
318
335
|
|
|
319
|
-
|
|
320
|
-
|
|
336
|
+
// Token debt is not drift (see isTokenDebtFinding); it fails only with --fail-on-new-token-debt.
|
|
337
|
+
const comparison = report.baseline || null;
|
|
338
|
+
const newDrift = comparison ? countNew(comparison, 'newDriftCount', (finding) => !isTokenDebtFinding(finding)) : 0;
|
|
339
|
+
if (parsed.failOnNewDrift && newDrift > 0) {
|
|
340
|
+
failures.push(`new drift found: ${newDrift} finding(s) not present in baseline`);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const newTokenDebt = comparison ? countNew(comparison, 'newTokenDebtCount', isTokenDebtFinding) : 0;
|
|
344
|
+
if (parsed.failOnNewTokenDebt === true && newTokenDebt > 0) {
|
|
345
|
+
failures.push(`new token debt found: ${newTokenDebt} raw value(s) a token could replace, not present in baseline`);
|
|
321
346
|
}
|
|
322
347
|
|
|
323
348
|
return failures;
|
|
324
349
|
}
|
|
325
350
|
|
|
351
|
+
/** A count from the comparison, or worked out from its new findings when an older caller built it without one. */
|
|
352
|
+
function countNew(comparison, key, predicate) {
|
|
353
|
+
if (Number.isInteger(comparison[key])) {
|
|
354
|
+
return comparison[key];
|
|
355
|
+
}
|
|
356
|
+
return (comparison.newFindings || []).filter(predicate).length;
|
|
357
|
+
}
|
|
358
|
+
|
|
326
359
|
module.exports = {
|
|
327
360
|
BASELINE_FORMAT_VERSION,
|
|
328
361
|
applyBaselineComparison,
|
|
@@ -331,6 +364,7 @@ module.exports = {
|
|
|
331
364
|
createLegacyFindingKey,
|
|
332
365
|
getAllFindings,
|
|
333
366
|
getAuditFailures,
|
|
367
|
+
isTokenDebtFinding,
|
|
334
368
|
legacyWriterDirectory,
|
|
335
369
|
writeBaseline,
|
|
336
370
|
};
|
package/src/audit/codemod.js
CHANGED
|
@@ -143,7 +143,7 @@ function runCodemod({ baseFontSize = 16, dir, ignorePatterns = [], includeNonAut
|
|
|
143
143
|
const skipped = walked.linksOutsideRoot
|
|
144
144
|
.filter((link) => !isTemplateFile(link))
|
|
145
145
|
.map((link) => ({ file: formatPath(path.join(rootDir, link)), reason: 'symbolic link to a path outside the directory; not followed' }));
|
|
146
|
-
const realRoot = fs.realpathSync(rootDir);
|
|
146
|
+
const realRoot = fs.realpathSync.native(rootDir);
|
|
147
147
|
const rewritten = new Set();
|
|
148
148
|
let nonAuthoredSkipped = 0;
|
|
149
149
|
for (const filePath of files) {
|
|
@@ -169,6 +169,7 @@ function runCodemod({ baseFontSize = 16, dir, ignorePatterns = [], includeNonAut
|
|
|
169
169
|
try {
|
|
170
170
|
parsed = parseStylesheet(filePath, source);
|
|
171
171
|
} catch {
|
|
172
|
+
// Not parseable: listed in `skipped` with the reason.
|
|
172
173
|
skipped.push({ file: formatPath(filePath), reason: 'could not parse' });
|
|
173
174
|
continue;
|
|
174
175
|
}
|
|
@@ -199,8 +200,9 @@ function writableRealPath(filePath, rootDir, realRoot) {
|
|
|
199
200
|
if (fs.lstatSync(filePath).isSymbolicLink()) {
|
|
200
201
|
return null;
|
|
201
202
|
}
|
|
202
|
-
realPath = fs.realpathSync(filePath);
|
|
203
|
+
realPath = fs.realpathSync.native(filePath);
|
|
203
204
|
} catch {
|
|
205
|
+
// A path that cannot be resolved is not a file to rewrite.
|
|
204
206
|
return null;
|
|
205
207
|
}
|
|
206
208
|
const expected = path.join(realRoot, path.relative(rootDir, filePath));
|
package/src/audit/config.js
CHANGED
|
@@ -57,6 +57,11 @@ function loadAuditConfig(parsed) {
|
|
|
57
57
|
if (!audit || typeof audit !== 'object' || Array.isArray(audit)) {
|
|
58
58
|
throw new Error(`Invalid Rhythmguard config ${parsed.configPath}: "audit" must be an object.`);
|
|
59
59
|
}
|
|
60
|
+
// A file in the repository must never make the audit run code: a Tailwind
|
|
61
|
+
// config is loaded with require(), so only --tailwind-config names one.
|
|
62
|
+
if (audit.tailwindConfigPath !== undefined) {
|
|
63
|
+
throw new Error(`Invalid Rhythmguard config ${parsed.configPath}: audit.tailwindConfigPath is not read from a config file, because loading a Tailwind config runs it. Pass --tailwind-config on the command line.`);
|
|
64
|
+
}
|
|
60
65
|
|
|
61
66
|
return {
|
|
62
67
|
audit,
|
|
@@ -112,6 +117,8 @@ function applyAuditConfig(parsed, configResult) {
|
|
|
112
117
|
applyConfigScalar(next, audit, cliOptions, 'includeMotion', 'includeMotion', parseBooleanOption);
|
|
113
118
|
applyConfigScalar(next, audit, cliOptions, 'includeNonAuthored', 'includeNonAuthored', parseBooleanOption);
|
|
114
119
|
applyConfigScalar(next, audit, cliOptions, 'checkMathBounds', 'checkMathBounds', parseBooleanOption);
|
|
120
|
+
applyConfigScalar(next, audit, cliOptions, 'failOnNewTokenDebt', 'failOnNewTokenDebt', parseBooleanOption);
|
|
121
|
+
applyConfigScalar(next, audit, cliOptions, 'reportMissingTokens', 'reportMissingTokens', parseBooleanOption);
|
|
115
122
|
applyConfigScalar(next, audit, cliOptions, 'scales', 'scales', parseGroupScales);
|
|
116
123
|
if (audit.ladders !== undefined) {
|
|
117
124
|
next.ladderMinStepPx = parseLadderOptions(audit.ladders);
|
package/src/audit/contract.js
CHANGED
|
@@ -8,6 +8,7 @@ const {
|
|
|
8
8
|
getNormalizedValueKeys,
|
|
9
9
|
hasLineComments,
|
|
10
10
|
} = require('../core/token-sources');
|
|
11
|
+
const { findDeclarationProperty } = require('./scan/stylesheets');
|
|
11
12
|
const { formatPath } = require('./shared');
|
|
12
13
|
|
|
13
14
|
function collectTokenContract({
|
|
@@ -32,12 +33,14 @@ function collectTokenContract({
|
|
|
32
33
|
try {
|
|
33
34
|
source = readSource(filePath);
|
|
34
35
|
} catch {
|
|
36
|
+
// Unreadable since the scan (deleted, permissions): this pass reads only what it can.
|
|
35
37
|
continue;
|
|
36
38
|
}
|
|
37
39
|
|
|
38
40
|
const file = formatPath(filePath);
|
|
39
41
|
collectTokenDefinitions(source, file, definitions, matchesKind, baseFontSize);
|
|
40
|
-
|
|
42
|
+
// A token source token read for its `$type` or a camelCase name (`--gap-sm`, `--spacingXs`) counts as used too.
|
|
43
|
+
collectTokenUses(source, file, uses, (token) => matchesKind(token) || externalTokenDefinitions.has(token));
|
|
41
44
|
}
|
|
42
45
|
|
|
43
46
|
for (const entry of externalTokenDefinitions.values()) {
|
|
@@ -53,7 +56,10 @@ function collectTokenContract({
|
|
|
53
56
|
}
|
|
54
57
|
|
|
55
58
|
for (const finding of cssFindings) {
|
|
56
|
-
|
|
59
|
+
// A missing-token finding's value is a token name, not a raw value.
|
|
60
|
+
if (finding.type !== 'missing-token') {
|
|
61
|
+
addRawValue(rawValues, rawValueLocations, finding.value, finding);
|
|
62
|
+
}
|
|
57
63
|
}
|
|
58
64
|
|
|
59
65
|
for (const finding of tailwindFindings) {
|
|
@@ -62,7 +68,9 @@ function collectTokenContract({
|
|
|
62
68
|
|
|
63
69
|
const definedTokens = mapTokenEntries(definitions);
|
|
64
70
|
const usedTokens = mapTokenEntries(uses);
|
|
65
|
-
|
|
71
|
+
// A DTCG `$deprecated` token is not a scale step, but it is declared: using it is not a missing token.
|
|
72
|
+
const deprecatedTokens = new Set((tokenSourceReports || []).flatMap((source) => source.deprecated || []));
|
|
73
|
+
const missingTokens = usedTokens.filter(({ token }) => !definitions.has(token) && !deprecatedTokens.has(token));
|
|
66
74
|
const unusedTokens = definedTokens.filter(({ token }) => !uses.has(token));
|
|
67
75
|
const rawValueMatches = collectRawValueMatches(rawValues, definitions, baseFontSize);
|
|
68
76
|
const conflictingTokens = collectConflictingTokens(definitions);
|
|
@@ -123,6 +131,79 @@ function collectTokenUses(source, file, uses, matchesKind) {
|
|
|
123
131
|
}
|
|
124
132
|
}
|
|
125
133
|
|
|
134
|
+
const MISSING_TOKEN_RULE = 'rhythmguard/missing-token';
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* One finding per `var()` of a missing token: a token the scanned
|
|
138
|
+
* stylesheets use and nothing defines. `missingTokens` is the token
|
|
139
|
+
* contract's list; a token an installed token package or a token source of
|
|
140
|
+
* another kind defines (`knownTokens`) is not missing. Comments are blanked
|
|
141
|
+
* first, so a commented-out declaration is not a finding.
|
|
142
|
+
*/
|
|
143
|
+
function collectMissingTokenFindings({
|
|
144
|
+
cssFiles,
|
|
145
|
+
knownTokens = new Set(),
|
|
146
|
+
missingTokens,
|
|
147
|
+
readSource = (filePath) => fs.readFileSync(filePath, 'utf8'),
|
|
148
|
+
tokenKind,
|
|
149
|
+
}) {
|
|
150
|
+
const missing = new Set(missingTokens
|
|
151
|
+
.map(({ token }) => token)
|
|
152
|
+
.filter((token) => !knownTokens.has(token)));
|
|
153
|
+
if (missing.size === 0) {
|
|
154
|
+
return [];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const matchesKind = createTokenKindMatcher(tokenKind);
|
|
158
|
+
const findings = [];
|
|
159
|
+
for (const filePath of cssFiles) {
|
|
160
|
+
let source;
|
|
161
|
+
try {
|
|
162
|
+
source = readSource(filePath);
|
|
163
|
+
} catch {
|
|
164
|
+
// Unreadable since the scan (deleted, permissions): this pass reads only what it can.
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
const file = formatPath(filePath);
|
|
168
|
+
const text = blankComments(source, hasLineComments(file));
|
|
169
|
+
const varPattern = /var\(\s*(--[\w-]+)/g;
|
|
170
|
+
let match;
|
|
171
|
+
while ((match = varPattern.exec(text)) !== null) {
|
|
172
|
+
const token = match[1];
|
|
173
|
+
if (!missing.has(token) || !matchesKind(token)) {
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
const { column, line } = offsetToPosition(text, match.index);
|
|
177
|
+
findings.push({
|
|
178
|
+
column,
|
|
179
|
+
file,
|
|
180
|
+
line,
|
|
181
|
+
property: findDeclarationProperty(source, line, column),
|
|
182
|
+
rule: MISSING_TOKEN_RULE,
|
|
183
|
+
text: `Token "${token}" is used but not defined in any scanned stylesheet, token source or installed token package.`,
|
|
184
|
+
type: 'missing-token',
|
|
185
|
+
value: token,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return findings;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** The source with block comments, and `//` line comments where the syntax has them, replaced by spaces of the same length. */
|
|
193
|
+
function blankComments(source, lineComments) {
|
|
194
|
+
const blank = (match) => match.replace(/[^\n]/g, ' ');
|
|
195
|
+
const blocked = source.replace(/\/\*[\s\S]*?\*\//g, blank);
|
|
196
|
+
// `//` after a colon is a URL (`https://`), not a comment.
|
|
197
|
+
return lineComments ? blocked.replace(/(^|[^:])\/\/[^\n]*/g, (match, lead) => `${lead}${blank(match.slice(lead.length))}`) : blocked;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** 1-based line and column of a character offset. */
|
|
201
|
+
function offsetToPosition(text, offset) {
|
|
202
|
+
const before = text.slice(0, offset);
|
|
203
|
+
const line = before.split('\n').length;
|
|
204
|
+
return { column: offset - before.lastIndexOf('\n'), line };
|
|
205
|
+
}
|
|
206
|
+
|
|
126
207
|
function addRawValue(rawValues, rawValueLocations, value, finding) {
|
|
127
208
|
if (!value) {
|
|
128
209
|
return;
|
|
@@ -232,11 +313,13 @@ function buildReport({
|
|
|
232
313
|
dir,
|
|
233
314
|
externalTokenDefinitions,
|
|
234
315
|
includeMotion,
|
|
316
|
+
knownTokens = new Set(),
|
|
235
317
|
linksOutsideRoot = [],
|
|
236
318
|
motionFindings,
|
|
237
319
|
nonAuthoredFiles = [],
|
|
238
320
|
parseErrorFindings = [],
|
|
239
321
|
readSource,
|
|
322
|
+
reportMissingTokens = false,
|
|
240
323
|
scale,
|
|
241
324
|
scanScope,
|
|
242
325
|
scssFiles = 0,
|
|
@@ -249,7 +332,36 @@ function buildReport({
|
|
|
249
332
|
tokenKind,
|
|
250
333
|
tokenSourceReports,
|
|
251
334
|
tokenSourceWarnings,
|
|
335
|
+
unauditedFiles = new Set(),
|
|
252
336
|
}) {
|
|
337
|
+
const tokenContract = collectTokenContract({
|
|
338
|
+
baseFontSize,
|
|
339
|
+
cssFiles,
|
|
340
|
+
cssFindings,
|
|
341
|
+
externalTokenDefinitions,
|
|
342
|
+
minCandidateCount: tokenCandidateMinCount,
|
|
343
|
+
readSource,
|
|
344
|
+
tailwindFindings,
|
|
345
|
+
tokenKind,
|
|
346
|
+
tokenSourceReports,
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
// With --report-missing-tokens, each var() of a token that no scanned
|
|
350
|
+
// stylesheet, token source or installed token package defines is a finding
|
|
351
|
+
// (ai-03). Off by default in 3.x, so the default findings do not grow.
|
|
352
|
+
if (reportMissingTokens) {
|
|
353
|
+
cssFindings = [
|
|
354
|
+
...cssFindings,
|
|
355
|
+
...collectMissingTokenFindings({
|
|
356
|
+
cssFiles: cssFiles.filter((file) => !unauditedFiles.has(file)),
|
|
357
|
+
knownTokens,
|
|
358
|
+
missingTokens: tokenContract.missingTokens,
|
|
359
|
+
readSource,
|
|
360
|
+
tokenKind,
|
|
361
|
+
}),
|
|
362
|
+
];
|
|
363
|
+
}
|
|
364
|
+
|
|
253
365
|
const offScaleValues = countByValue(cssFindings
|
|
254
366
|
.filter((finding) => finding.type === 'off-scale' && finding.value)
|
|
255
367
|
.map((finding) => finding.value));
|
|
@@ -286,17 +398,6 @@ function buildReport({
|
|
|
286
398
|
parseErrorFiles: countFiles(parseErrorFindings),
|
|
287
399
|
totalFiles,
|
|
288
400
|
}));
|
|
289
|
-
const tokenContract = collectTokenContract({
|
|
290
|
-
baseFontSize,
|
|
291
|
-
cssFiles,
|
|
292
|
-
cssFindings,
|
|
293
|
-
externalTokenDefinitions,
|
|
294
|
-
minCandidateCount: tokenCandidateMinCount,
|
|
295
|
-
readSource,
|
|
296
|
-
tailwindFindings,
|
|
297
|
-
tokenKind,
|
|
298
|
-
tokenSourceReports,
|
|
299
|
-
});
|
|
300
401
|
|
|
301
402
|
return {
|
|
302
403
|
config,
|
|
@@ -423,10 +524,15 @@ function toAuditContractReport(report) {
|
|
|
423
524
|
decisions: report.decisions || null,
|
|
424
525
|
motion: report.motion,
|
|
425
526
|
scale: {
|
|
527
|
+
// Set when class strings are checked against another scale than the
|
|
528
|
+
// stylesheets: Tailwind's default ladder when no project scale exists.
|
|
529
|
+
classStrings: report.scale && report.scale.classStrings ? report.scale.classStrings : null,
|
|
426
530
|
cleanliness: report.scaleCleanliness,
|
|
427
531
|
files: report.scale ? report.scale.files : [],
|
|
428
532
|
offScaleProperties: report.offScaleProperties || {},
|
|
429
533
|
offScaleValues: report.offScaleValues,
|
|
534
|
+
// The preset a fallback is: "tailwind" in a Tailwind project, else "rhythmic-4"; null otherwise.
|
|
535
|
+
preset: report.scale && report.scale.preset ? report.scale.preset : null,
|
|
430
536
|
rejected: report.scale && report.scale.rejected ? report.scale.rejected : null,
|
|
431
537
|
source: report.scale ? report.scale.source : 'default',
|
|
432
538
|
tokenOpportunities: report.tokenOpportunities,
|
|
@@ -438,6 +544,8 @@ function toAuditContractReport(report) {
|
|
|
438
544
|
scanned: report.scanned,
|
|
439
545
|
schemaVersion: '2.0',
|
|
440
546
|
summary: report.summary,
|
|
547
|
+
// Every loader warning of the run: token sources, the Tailwind config (cq-05, tf-02).
|
|
548
|
+
warnings: [...new Set(report.tokenSourceWarnings || [])],
|
|
441
549
|
};
|
|
442
550
|
}
|
|
443
551
|
|
|
@@ -527,7 +635,9 @@ module.exports = {
|
|
|
527
635
|
AUDIT_JSON_SCHEMA,
|
|
528
636
|
addRawValue,
|
|
529
637
|
buildReport,
|
|
638
|
+
MISSING_TOKEN_RULE,
|
|
530
639
|
collectConflictingTokens,
|
|
640
|
+
collectMissingTokenFindings,
|
|
531
641
|
collectRawValueMatches,
|
|
532
642
|
collectTokenContract,
|
|
533
643
|
collectTokenDefinitions,
|
package/src/audit/next-steps.js
CHANGED
|
@@ -51,13 +51,14 @@ function lintGlob(cwd, cssFiles) {
|
|
|
51
51
|
}
|
|
52
52
|
|
|
53
53
|
/** `npx rhythmguard audit <dir>` with the scale flags of the run it describes. */
|
|
54
|
-
function auditCommand({ dir = '.', scale = null, tokenSources = [] } = {}) {
|
|
54
|
+
function auditCommand({ dir = '.', scale = null, tailwindConfig = null, tokenSources = [] } = {}) {
|
|
55
55
|
const scaleArg = Array.isArray(scale) ? scale.join(',') : scale;
|
|
56
56
|
return [
|
|
57
57
|
'npx rhythmguard audit',
|
|
58
58
|
shellQuote(dir),
|
|
59
59
|
...(scaleArg ? [`--scale ${shellQuote(String(scaleArg))}`] : []),
|
|
60
60
|
...tokenSources.map((file) => `--token-source ${shellQuote(file)}`),
|
|
61
|
+
...(tailwindConfig ? [`--tailwind-config ${shellQuote(tailwindConfig)}`] : []),
|
|
61
62
|
].join(' ');
|
|
62
63
|
}
|
|
63
64
|
|
|
@@ -70,6 +71,7 @@ function auditCommandFromArgs(parsed) {
|
|
|
70
71
|
return auditCommand({
|
|
71
72
|
dir: parsed.dir || '.',
|
|
72
73
|
scale: passed.has('scale') ? parsed.scale : null,
|
|
74
|
+
tailwindConfig: passed.has('tailwindConfigPath') ? parsed.tailwindConfigPath : null,
|
|
73
75
|
tokenSources: passed.has('tokenSources') ? parsed.tokenSources.map((entry) => (typeof entry === 'string' ? entry : entry.path)) : [],
|
|
74
76
|
});
|
|
75
77
|
}
|