stylelint-plugin-rhythmguard 3.19.0 → 3.20.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +3 -3
  3. package/SECURITY.md +2 -1
  4. package/agents/claude-code/SKILL.md +1 -1
  5. package/package.json +1 -1
  6. package/src/audit/args.js +30 -8
  7. package/src/audit/baseline.js +37 -3
  8. package/src/audit/codemod.js +2 -0
  9. package/src/audit/config.js +7 -0
  10. package/src/audit/contract.js +124 -14
  11. package/src/audit/next-steps.js +3 -1
  12. package/src/audit/non-authored.js +1 -0
  13. package/src/audit/render-github.js +16 -11
  14. package/src/audit/render-markdown.js +8 -2
  15. package/src/audit/render-text.js +41 -2
  16. package/src/audit/render-utils.js +14 -0
  17. package/src/audit/report.js +230 -10
  18. package/src/audit/scan/files.js +5 -0
  19. package/src/audit/scan/stylesheets.js +48 -53
  20. package/src/audit/scan/templates.js +2 -0
  21. package/src/audit/shared.js +7 -1
  22. package/src/audit/token-chains.js +1 -0
  23. package/src/cli/audit.js +2 -2
  24. package/src/cli/doctor.js +853 -237
  25. package/src/cli/first-run.js +210 -0
  26. package/src/cli/index.js +25 -1
  27. package/src/cli/index.mjs +3 -0
  28. package/src/cli/init.js +39 -11
  29. package/src/cli/quickstart.js +53 -102
  30. package/src/cli/scale.js +223 -0
  31. package/src/configs/recommended.js +3 -1
  32. package/src/configs/strict.js +3 -1
  33. package/src/configs/tailwind.js +15 -0
  34. package/src/core/decisions.js +18 -5
  35. package/src/core/fs-cache.js +1 -0
  36. package/src/core/options.js +2 -1
  37. package/src/core/scale-inference.js +72 -52
  38. package/src/core/tailwind-class-analysis.js +56 -13
  39. package/src/core/token-index.js +55 -14
  40. package/src/core/token-map.js +136 -28
  41. package/src/core/token-sources.js +461 -40
  42. package/src/core/value-nodes.js +4 -2
  43. package/src/eslint/class-context.js +330 -0
  44. package/src/eslint/literal-spans.js +5 -4
  45. package/src/eslint/rules/tailwind-class-use-scale.js +30 -9
  46. package/src/presets/default-scale.js +42 -0
  47. package/src/presets/scales.js +6 -1
  48. package/src/rules/no-offscale-transform/index.js +17 -5
  49. package/src/rules/prefer-token/index.js +51 -15
  50. package/src/rules/use-scale/index.js +7 -4
  51. package/types/__checks__/consumer.ts +17 -0
  52. package/types/__checks__/eslint-config.ts +5 -0
  53. package/types/audit.d.ts +40 -3
  54. package/types/cli.d.ts +77 -1
  55. package/types/shared.d.ts +10 -0
@@ -11,16 +11,20 @@ const {
11
11
  pxOnScale,
12
12
  toPx,
13
13
  } = require('./length');
14
+ const { TAILWIND_SCALE_NAME, TAILWIND_SPACING_UNIT_REM, tailwindSpacingLadder } = require('../presets/default-scale');
14
15
 
15
- // The ESLint rule's and the audit's default scale. It is not the `rhythmic-4`
16
- // preset (which continues to 40, 48, 64); unifying the defaults changes
17
- // reports, so it waits for a major (#246).
18
- const DEFAULT_SCALE = [0, 4, 8, 12, 16, 24, 32];
19
16
  const DEFAULT_UNITS = ['px', 'rem', 'em'];
20
17
  // Tailwind's numeric spacing utilities are multiples of one unit: `--spacing`
21
18
  // (0.25rem) in v4, and the same 0.25rem step in the v3 default scale. In px
22
19
  // that is a quarter of the root font size: 4px at 16px, 2.5px at 10px (#247).
23
- const SPACING_UNIT_REM = 0.25;
20
+ const SPACING_UNIT_REM = TAILWIND_SPACING_UNIT_REM;
21
+
22
+ // Utilities Tailwind has no negative form for: padding, scroll padding and
23
+ // gap (padding and gap cannot be negative in CSS). `-p-3` and `-gap-3` are
24
+ // never generated, and `p-[-13px]` writes an invalid declaration (cs-08).
25
+ // The class regex still accepts the sign on them so a finding that was
26
+ // reported keeps being reported, now without a fix.
27
+ const NO_NEGATIVE_FORM = /^(?:p[trblxy]?|gap(?:-[xy])?|scroll-p[trblxy]?)$/;
24
28
 
25
29
  const ARBITRARY_SPACING_CLASS = /^(?<utility>-?(?:m(?:[trblxy])?|p(?:[trblxy])?|gap(?:-[xy])?|space-[xy]|inset(?:-[xy])?|top|right|bottom|left|translate-[xy]|scroll-(?:m|p)(?:[trblxy])?))-\[(?<rawValue>[^\]]+)\]$/;
26
30
 
@@ -31,16 +35,22 @@ function normalizeTailwindClassOptions(option = {}) {
31
35
  option.baseFontSize > 0
32
36
  ? option.baseFontSize
33
37
  : 16;
38
+ const spacingUnit = option.spacingUnit === false
39
+ ? null
40
+ : typeof option.spacingUnit === 'number' && Number.isFinite(option.spacingUnit) && option.spacingUnit > 0
41
+ ? option.spacingUnit
42
+ : baseFontSize * SPACING_UNIT_REM;
43
+ // No `scale`: Tailwind's default ladder on the spacing unit, so a standard
44
+ // step such as p-5 (20px) is on the scale (cs-01). Before 3.20 the default
45
+ // was 0 to 32px.
46
+ const defaultScale = !Array.isArray(option.scale);
34
47
  return {
35
48
  allowHairlines: option.allowHairlines !== false,
36
49
  allowNegative: option.allowNegative !== false,
37
50
  baseFontSize,
38
- scale: Array.isArray(option.scale) ? option.scale : DEFAULT_SCALE,
39
- spacingUnit: option.spacingUnit === false
40
- ? null
41
- : typeof option.spacingUnit === 'number' && Number.isFinite(option.spacingUnit) && option.spacingUnit > 0
42
- ? option.spacingUnit
43
- : baseFontSize * SPACING_UNIT_REM,
51
+ scale: defaultScale ? tailwindSpacingLadder(spacingUnit || baseFontSize * SPACING_UNIT_REM) : option.scale,
52
+ scaleName: defaultScale ? TAILWIND_SCALE_NAME : null,
53
+ spacingUnit,
44
54
  units: Array.isArray(option.units)
45
55
  ? option.units.map((unit) => String(unit).toLowerCase())
46
56
  : DEFAULT_UNITS,
@@ -154,6 +164,9 @@ function utilityClassFor(utility, px, negative, spacingUnit) {
154
164
  return null;
155
165
  }
156
166
  const name = utility.startsWith('-') ? utility.slice(1) : utility;
167
+ if (negative && steps !== 0 && NO_NEGATIVE_FORM.test(name)) {
168
+ return null;
169
+ }
157
170
  const sign = negative && steps !== 0 ? '-' : '';
158
171
  return `${sign}${name}-${formatNumber(Math.round(quarters) / 4)}`;
159
172
  }
@@ -213,6 +226,26 @@ function analyzeClassToken(token, options, scalePx) {
213
226
  if (!nearest) {
214
227
  return null;
215
228
  }
229
+ // Past the top step the nearest step is not a fix: 64px snapped to a 32px
230
+ // top step halves the padding (cs-01). Reported, with no fix.
231
+ const beyondScale = pxValue > scalePx[scalePx.length - 1];
232
+
233
+ // `-p-[13px]`, `p-[-13px]`, `-gap-[13px]`: still reported, as before, but
234
+ // with no fix and no suggested class, since `-p-3` and `-gap-3` do not
235
+ // exist. A double negative (`-p-[-13px]`) is no better: Tailwind has no
236
+ // `-p-*` utility at all. On-scale values were never reported and are not now.
237
+ const bareUtility = match.groups.utility.replace(/^-/, '');
238
+ if (NO_NEGATIVE_FORM.test(bareUtility) && (match.groups.utility.startsWith('-') || parsedLength.number < 0)) {
239
+ return {
240
+ fixedToken: null,
241
+ nearest,
242
+ nearestUtilities: null,
243
+ parsedLength,
244
+ reason: 'no-negative-form',
245
+ rawValue: match.groups.rawValue,
246
+ utility: match.groups.utility,
247
+ };
248
+ }
216
249
 
217
250
  const signedNearest = parsedLength.number < 0
218
251
  ? -Math.abs(nearest.nearest)
@@ -235,7 +268,7 @@ function analyzeClassToken(token, options, scalePx) {
235
268
  const fixedCandidate = utilityFix || parsedToken.candidate.replace(match.groups.rawValue, replacementValue);
236
269
 
237
270
  return {
238
- fixedToken: wrap(fixedCandidate),
271
+ fixedToken: beyondScale ? null : wrap(fixedCandidate),
239
272
  nearest,
240
273
  // The utility classes for the two nearest steps, when both are quarter
241
274
  // steps of the spacing unit; messages name these instead of px values.
@@ -276,10 +309,20 @@ function createTailwindClassAnalyzer(option = {}) {
276
309
  * The message text for an off-scale class: the two nearest utility classes
277
310
  * with their px values when the unit makes them, the px steps otherwise.
278
311
  */
279
- function offScaleClassMessage(token, analysis) {
312
+ function offScaleClassMessage(token, analysis, scaleName = null) {
313
+ const message = offScaleClassText(token, analysis);
314
+ // The ESLint rule names the scale it fell back to, so a reader knows the
315
+ // verdict is Tailwind's default ladder and not the project's tokens.
316
+ return scaleName && analysis.reason === 'off-scale' ? `${message} Scale: ${scaleName}.` : message;
317
+ }
318
+
319
+ function offScaleClassText(token, analysis) {
280
320
  if (analysis.reason === 'negative') {
281
321
  return `Unexpected Tailwind arbitrary spacing value "${token}". Negative values are disabled for this rule.`;
282
322
  }
323
+ if (analysis.reason === 'no-negative-form') {
324
+ return `Unexpected Tailwind arbitrary spacing value "${token}". Padding and gap cannot be negative, so this class has no effect.`;
325
+ }
283
326
  const lowerPx = analysis.nearest ? formatLength(analysis.nearest.lower, 'px') : 'n/a';
284
327
  const upperPx = analysis.nearest ? formatLength(analysis.nearest.upper, 'px') : 'n/a';
285
328
  if (analysis.nearestUtilities) {
@@ -2,7 +2,7 @@
2
2
 
3
3
  const { propertyKindOf } = require('./css-vocabulary');
4
4
  const { fixedLengthValue, numbersEqual, toPx } = require('./length');
5
- const { createTokenKindMatcher, parseTokenValueLength } = require('./token-sources');
5
+ const { conditionsOfNode, createTokenKindMatcher, parseTokenValueLength } = require('./token-sources');
6
6
 
7
7
  // Dedicated kinds first: a name like --radius-space-1 is a radius token.
8
8
  const TOKEN_KINDS = ['radius', 'typography', 'motion', 'size', 'spacing'].map((kind) => [kind, createTokenKindMatcher(kind)]);
@@ -70,26 +70,65 @@ function tokenIndexFromDefinitions(definitions, baseFontSize = 16) {
70
70
  for (const { px, raw, unit } of lengths || []) {
71
71
  if (px === 0) continue;
72
72
  const file = definition.files ? [...definition.files][0] : null;
73
- index.push({ file: file && file !== 'stylesheet' ? file : null, px, raw, token: definition.token, unit });
73
+ // A definition built without scopes (an older caller) counts as declared at the root.
74
+ const fixScopes = definition.fixScopes || [{ global: true }];
75
+ index.push({ file: file && file !== 'stylesheet' ? file : null, fixScopes, px, raw, token: definition.token, unit });
74
76
  }
75
77
  }
76
78
  return index;
77
79
  }
78
80
 
81
+ /** The conditions and ancestors of a declaration being fixed, computed once per declaration. */
82
+ const placeCache = new WeakMap();
83
+ function placeOf(decl) {
84
+ if (!placeCache.has(decl)) {
85
+ const ancestors = new Set();
86
+ for (let node = decl.parent; node; node = node.parent) ancestors.add(node);
87
+ placeCache.set(decl, { ancestors, conditions: new Set(conditionsOfNode(decl)) });
88
+ }
89
+ return placeCache.get(decl);
90
+ }
91
+
92
+ /**
93
+ * Whether a token is defined where a declaration sits (fix-02). A token
94
+ * declared at the root outside every conditional at-rule is defined
95
+ * everywhere. One declared at the root under `@media`, `@supports` or
96
+ * `@container` is defined only under the same conditions, and one declared in
97
+ * a component block only inside that block. Anywhere else the property would
98
+ * be invalid at computed-value time, so the token is never offered there.
99
+ * Without a declaration (`at` undefined) every token counts.
100
+ */
101
+ function tokenDefinedAt(entry, at) {
102
+ if (!at || !entry.fixScopes) {
103
+ return true;
104
+ }
105
+ return entry.fixScopes.some((scope) => {
106
+ if (scope.global) return true;
107
+ if (scope.anchor) return placeOf(at).ancestors.has(scope.anchor);
108
+ if (scope.conditions) {
109
+ const { conditions } = placeOf(at);
110
+ return scope.conditions.every((condition) => conditions.has(condition));
111
+ }
112
+ return false;
113
+ });
114
+ }
115
+
79
116
  /**
80
117
  * Every custom property that holds a length, for one property. The shared
81
118
  * resolver behind use-scale's `fixWith: "token"` and prefer-token, so the two
82
119
  * rules always know the same tokens. The px value is signed: 8 finds the
83
120
  * tokens that hold 8px, -8 the tokens that hold -8px. Same unit first; with
84
121
  * `anyUnit`, a token in another unit that holds the same px value counts when
85
- * none matches the unit. Sorted, so messages are stable.
122
+ * none matches the unit. With `at`, the declaration being fixed, only the
123
+ * tokens defined where it sits count (see tokenDefinedAt). Sorted, so
124
+ * messages are stable.
86
125
  */
87
- function tokensForLength(index, px, unit, { anyUnit = false, prop = null } = {}) {
126
+ function tokensForLength(index, px, unit, { anyUnit = false, at = null, prop = null } = {}) {
88
127
  const wanted = unit || 'px';
89
128
  const sameUnit = new Set();
90
129
  const otherUnit = new Set();
91
130
  for (const entry of index) {
92
- if (!entry.token.startsWith('--') || !numbersEqual(entry.px, px) || !tokenFitsProperty(entry.token, prop)) {
131
+ if (!entry.token.startsWith('--') || !numbersEqual(entry.px, px) || !tokenFitsProperty(entry.token, prop) || !tokenDefinedAt(entry, at)) {
93
132
  continue;
94
133
  }
95
134
  (entry.unit === wanted ? sameUnit : otherUnit).add(entry.token);
@@ -114,8 +153,8 @@ function signedTokensForLength(index, px, unit, options = {}) {
114
153
  return { negate: px < 0, tokens: tokensForLength(index, Math.abs(px), unit, options) };
115
154
  }
116
155
 
117
- function tokenForLength(index, px, unit, prop = null) {
118
- const candidates = tokensForLength(index, px, unit, { prop });
156
+ function tokenForLength(index, px, unit, prop = null, at = null) {
157
+ const candidates = tokensForLength(index, px, unit, { at, prop });
119
158
  return candidates.length === 1 ? `var(${candidates[0]})` : null;
120
159
  }
121
160
 
@@ -135,18 +174,19 @@ function negateReplacement(replacement) {
135
174
  * options ask for one and exactly one qualifies, otherwise the literal. The
136
175
  * nearest value is in px, or in the literal's unit with `unitStrategy:
137
176
  * "exact"`; tokens are indexed in px, so the lookup converts it (issue #223).
138
- * `avoidTokens` are the var() names a fallback literal falls back from; one
139
- * of them is never written, the literal is.
177
+ * `avoidTokens` are the var() names a fallback literal falls back from. A
178
+ * fallback is what renders when tokens are missing, so no token is written
179
+ * into one, the literal is (fix-02; issue #240). `at` is the declaration being
180
+ * fixed: a token not defined there is never written (see tokenDefinedAt).
140
181
  */
141
- function replacementFor(parsedLength, nearest, options, prop = null, avoidTokens = []) {
142
- if (options.fixWith === 'token' && options.tokenIndex) {
182
+ function replacementFor(parsedLength, nearest, options, prop = null, avoidTokens = [], at = null) {
183
+ if (options.fixWith === 'token' && options.tokenIndex && avoidTokens.length === 0) {
143
184
  const unit = parsedLength.unit || 'px';
144
185
  const nearestPx = options.unitStrategy === 'exact' ? toPx(Math.abs(nearest), unit, options.baseFontSize) : Math.abs(nearest);
145
186
  if (nearestPx !== null) {
146
187
  const signedPx = parsedLength.number < 0 ? -nearestPx : nearestPx;
147
- const { negate, tokens } = signedTokensForLength(options.tokenIndex, signedPx, unit, { prop });
148
- // A var() fallback never falls back to the token it is the fallback of (issue #240).
149
- if (tokens.length === 1 && !avoidTokens.includes(tokens[0])) {
188
+ const { negate, tokens } = signedTokensForLength(options.tokenIndex, signedPx, unit, { at, prop });
189
+ if (tokens.length === 1) {
150
190
  const token = `var(${tokens[0]})`;
151
191
  return negate ? negateReplacement(token) : token;
152
192
  }
@@ -173,6 +213,7 @@ module.exports = {
173
213
  negateReplacement,
174
214
  replacementFor,
175
215
  signedTokensForLength,
216
+ tokenDefinedAt,
176
217
  tokenFitsProperty,
177
218
  tokenHoldsNote,
178
219
  tokenForLength,
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { readJsonFile } = require('./json');
4
- const { parseTokenValueLength } = require('./token-sources');
4
+ const { conditionsOfNode, parseTokenValueLength, scopeOfNode } = require('./token-sources');
5
5
 
6
6
  const fs = require('node:fs');
7
7
  const path = require('node:path');
@@ -52,7 +52,27 @@ function displayOrigin(file) {
52
52
  return relative && !relative.startsWith('..') && !path.isAbsolute(relative) ? relative : file;
53
53
  }
54
54
 
55
- function addLengthValueMapping(map, rawLength, tokenReference, baseFontSize, origins = null, origin = null) {
55
+ /**
56
+ * The tokens one map source offers for each key, before they reach the map.
57
+ * A key collects the tokens whose value is written that way (`exact`) apart
58
+ * from the tokens that only convert to it (`converted`: a 1rem token under the
59
+ * 16px key), so a token in the literal's own unit is preferred, as the token
60
+ * index does.
61
+ */
62
+ function createCollector() {
63
+ return new Map();
64
+ }
65
+
66
+ function collect(collector, key, token, exact) {
67
+ if (!collector.has(key)) {
68
+ collector.set(key, { converted: new Set(), exact: new Set(), last: token });
69
+ }
70
+ const entry = collector.get(key);
71
+ (exact ? entry.exact : entry.converted).add(token);
72
+ entry.last = token;
73
+ }
74
+
75
+ function addLengthValueMapping(collector, rawLength, tokenReference, baseFontSize, origins = null, origin = null) {
56
76
  if (typeof rawLength !== 'string') {
57
77
  return;
58
78
  }
@@ -74,15 +94,49 @@ function addLengthValueMapping(map, rawLength, tokenReference, baseFontSize, ori
74
94
  // Keyed by the signed value: a -8px token stands for -8px, never for 8px
75
95
  // (issue #221). prefer-token negates a positive token for a negative literal.
76
96
  const normalizedRaw = formatLength(parsed.number, parsed.unit || 'px');
77
- map[normalizedRaw] = token;
97
+ collect(collector, normalizedRaw, token, true);
78
98
 
79
99
  const px = toPx(parsed.number, parsed.unit, baseFontSize);
80
100
  if (px !== null) {
81
- map[`${px}px`] = token;
101
+ const pxKey = `${px}px`;
102
+ collect(collector, pxKey, token, pxKey === normalizedRaw);
82
103
  }
83
104
  }
84
105
 
85
- function mergeExplicitTokenMap(target, source) {
106
+ /**
107
+ * The tokens a collected key stands for: the ones written in its unit when
108
+ * there are any, the converted ones otherwise. Sorted, so messages are stable.
109
+ */
110
+ function candidatesOf(entry) {
111
+ const chosen = entry.exact.size > 0 ? entry.exact : entry.converted;
112
+ return [...chosen].sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));
113
+ }
114
+
115
+ /**
116
+ * Write one source's keys into the map. A key one token holds maps to that
117
+ * token. A key several tokens hold is a guess either way, so it is recorded
118
+ * in `ambiguous` with every candidate and no fix writes it (fix-06); the map
119
+ * keeps a token under the key only so the set of keys (which scale inference
120
+ * reads) is unchanged. A later source replaces an earlier one key by key.
121
+ * `accept` may skip a key entirely, leaving earlier sources in charge of it.
122
+ */
123
+ function applyCollector(map, ambiguous, collector, accept = () => true) {
124
+ for (const [key, entry] of collector) {
125
+ const candidates = candidatesOf(entry);
126
+ if (!accept(candidates)) {
127
+ continue;
128
+ }
129
+ if (candidates.length === 1) {
130
+ map[key] = candidates[0];
131
+ delete ambiguous[key];
132
+ } else {
133
+ map[key] = entry.last;
134
+ ambiguous[key] = candidates;
135
+ }
136
+ }
137
+ }
138
+
139
+ function mergeExplicitTokenMap(target, source, ambiguous = {}) {
86
140
  if (!isPlainObject(source)) {
87
141
  return target;
88
142
  }
@@ -93,12 +147,13 @@ function mergeExplicitTokenMap(target, source) {
93
147
  }
94
148
 
95
149
  target[raw] = tokenReference;
150
+ delete ambiguous[raw];
96
151
  }
97
152
 
98
153
  return target;
99
154
  }
100
155
 
101
- function walkTokenGroup(map, group, prefix, baseFontSize, origins, origin) {
156
+ function walkTokenGroup(collector, group, prefix, baseFontSize, origins, origin) {
102
157
  for (const [key, value] of Object.entries(group)) {
103
158
  const tokenName = `${prefix}-${key}`;
104
159
 
@@ -108,26 +163,28 @@ function walkTokenGroup(map, group, prefix, baseFontSize, origins, origin) {
108
163
 
109
164
  // Leaf node with $value (DTCG)
110
165
  if (typeof value.$value === 'string') {
111
- addLengthValueMapping(map, value.$value, tokenName, baseFontSize, origins, origin);
166
+ addLengthValueMapping(collector, value.$value, tokenName, baseFontSize, origins, origin);
112
167
  continue;
113
168
  }
114
169
 
115
170
  // Leaf node with value (Style Dictionary)
116
171
  if (typeof value.value === 'string') {
117
- addLengthValueMapping(map, value.value, tokenName, baseFontSize, origins, origin);
172
+ addLengthValueMapping(collector, value.value, tokenName, baseFontSize, origins, origin);
118
173
  continue;
119
174
  }
120
175
 
121
176
  // Nested group: recurse deeper
122
- walkTokenGroup(map, value, tokenName, baseFontSize, origins, origin);
177
+ walkTokenGroup(collector, value, tokenName, baseFontSize, origins, origin);
123
178
  }
124
179
  }
125
180
 
126
181
  function mergeTokenMapFromFile({
182
+ ambiguous = {},
127
183
  baseFontSize,
128
184
  currentMap,
129
185
  origins = null,
130
186
  tokenMapFile,
187
+ warnings = [],
131
188
  }) {
132
189
  if (!tokenMapFile) {
133
190
  return currentMap;
@@ -135,13 +192,15 @@ function mergeTokenMapFromFile({
135
192
 
136
193
  const resolvedPath = path.resolve(process.cwd(), tokenMapFile);
137
194
  if (!fs.existsSync(resolvedPath)) {
195
+ warnings.push(`Token map file not found: ${tokenMapFile}`);
138
196
  return currentMap;
139
197
  }
140
198
 
141
199
  let parsed;
142
200
  try {
143
201
  parsed = readJsonFile(resolvedPath);
144
- } catch {
202
+ } catch (error) {
203
+ warnings.push(`Unable to parse token map file ${tokenMapFile}: ${error.message}`);
145
204
  return currentMap;
146
205
  }
147
206
 
@@ -152,6 +211,7 @@ function mergeTokenMapFromFile({
152
211
  const nextMap = {
153
212
  ...currentMap,
154
213
  };
214
+ const collector = createCollector();
155
215
  const origin = displayOrigin(resolvedPath);
156
216
 
157
217
  for (const [entryKey, entryValue] of Object.entries(parsed)) {
@@ -160,7 +220,7 @@ function mergeTokenMapFromFile({
160
220
  const valueAsLength = parseLengthToken(entryValue);
161
221
 
162
222
  if (keyAsLength) {
163
- nextMap[entryKey] = entryValue;
223
+ collect(collector, entryKey, entryValue, true);
164
224
  if (origins && !origins[entryValue]) {
165
225
  origins[entryValue] = origin;
166
226
  }
@@ -168,38 +228,48 @@ function mergeTokenMapFromFile({
168
228
  }
169
229
 
170
230
  if (valueAsLength) {
171
- addLengthValueMapping(nextMap, entryValue, entryKey, baseFontSize, origins, origin);
231
+ addLengthValueMapping(collector, entryValue, entryKey, baseFontSize, origins, origin);
172
232
  }
173
233
 
174
234
  continue;
175
235
  }
176
236
 
177
237
  if (typeof entryValue === 'number') {
178
- addLengthValueMapping(nextMap, `${entryValue}px`, entryKey, baseFontSize, origins, origin);
238
+ addLengthValueMapping(collector, `${entryValue}px`, entryKey, baseFontSize, origins, origin);
179
239
  continue;
180
240
  }
181
241
 
182
242
  if (isPlainObject(entryValue)) {
183
243
  // Style Dictionary format: { value: "16px" }
184
244
  if (typeof entryValue.value === 'string') {
185
- addLengthValueMapping(nextMap, entryValue.value, entryKey, baseFontSize, origins, origin);
245
+ addLengthValueMapping(collector, entryValue.value, entryKey, baseFontSize, origins, origin);
186
246
  continue;
187
247
  }
188
248
 
189
249
  // W3C DTCG format: { $value: "16px", $type: "dimension" }
190
250
  if (typeof entryValue.$value === 'string') {
191
- addLengthValueMapping(nextMap, entryValue.$value, entryKey, baseFontSize, origins, origin);
251
+ addLengthValueMapping(collector, entryValue.$value, entryKey, baseFontSize, origins, origin);
192
252
  continue;
193
253
  }
194
254
 
195
255
  // Nested group: recurse (e.g. { spacing: { 4: { $value: "16px" } } })
196
- walkTokenGroup(nextMap, entryValue, entryKey, baseFontSize, origins, origin);
256
+ walkTokenGroup(collector, entryValue, entryKey, baseFontSize, origins, origin);
197
257
  }
198
258
  }
199
259
 
260
+ applyCollector(nextMap, ambiguous, collector);
200
261
  return nextMap;
201
262
  }
202
263
 
264
+ /**
265
+ * Whether a custom property declaration is defined everywhere: at the root
266
+ * (`:root`, `html`, `@theme`) and outside every `@media`, `@supports` and
267
+ * `@container` block.
268
+ */
269
+ function declaredEverywhere(decl) {
270
+ return scopeOfNode(decl) === 'root' && conditionsOfNode(decl).length === 0;
271
+ }
272
+
203
273
  function mergeTokenMapFromCssCustomProperties({
204
274
  baseFontSize,
205
275
  currentMap,
@@ -225,24 +295,39 @@ function mergeTokenMapFromCssCustomProperties({
225
295
  const px = parsed ? toPx(parsed.number, parsed.unit, baseFontSize) : null;
226
296
  const key = px === null ? `raw:${decl.value.trim()}` : `px:${formatLength(px, 'px')}`;
227
297
  if (!valuesByProp.has(decl.prop)) {
228
- valuesByProp.set(decl.prop, { decl, keys: new Set() });
298
+ valuesByProp.set(decl.prop, { decl, everywhere: false, keys: new Set() });
229
299
  }
230
- valuesByProp.get(decl.prop).keys.add(key);
300
+ const entry = valuesByProp.get(decl.prop);
301
+ entry.keys.add(key);
302
+ entry.everywhere = entry.everywhere || declaredEverywhere(decl);
231
303
  });
232
304
 
233
- for (const { decl, keys } of valuesByProp.values()) {
234
- if (keys.size > 1) {
305
+ const collector = createCollector();
306
+ const everywhere = new Set();
307
+ for (const entry of valuesByProp.values()) {
308
+ if (entry.keys.size > 1) {
235
309
  continue;
236
310
  }
237
311
 
238
- const parsed = parseTokenValueLength(decl.value);
312
+ const parsed = parseTokenValueLength(entry.decl.value);
239
313
  if (!parsed || parsed.number === 0) {
240
314
  continue;
241
315
  }
242
316
 
243
- addLengthValueMapping(nextMap, decl.value, `var(${decl.prop})`, baseFontSize, origins, origin);
317
+ const token = `var(${entry.decl.prop})`;
318
+ if (entry.everywhere) {
319
+ everywhere.add(token);
320
+ }
321
+ addLengthValueMapping(collector, entry.decl.value, token, baseFontSize, origins, origin);
244
322
  }
245
323
 
324
+ // A value two tokens hold, or one held by a token that is not defined
325
+ // everywhere (a `.card` token, a token under `@media`), is left out of the
326
+ // map. prefer-token's token index then names every candidate defined where
327
+ // the value sits and writes one only when it is the only one (css-08,
328
+ // fix-02).
329
+ applyCollector(nextMap, {}, collector, (candidates) => candidates.length === 1 && everywhere.has(candidates[0]));
330
+
246
331
  return nextMap;
247
332
  }
248
333
 
@@ -274,6 +359,9 @@ function extractTailwindSpacing(config) {
274
359
  };
275
360
  }
276
361
 
362
+ // Why a Tailwind config could not be loaded, by resolved path (cq-05).
363
+ const tailwindLoadErrors = new Map();
364
+
277
365
  function loadTailwindSpacingFromRequire(resolvedPath) {
278
366
  try {
279
367
  const loaded = require(resolvedPath);
@@ -282,7 +370,8 @@ function loadTailwindSpacingFromRequire(resolvedPath) {
282
370
  : loaded;
283
371
 
284
372
  return extractTailwindSpacing(config);
285
- } catch {
373
+ } catch (error) {
374
+ tailwindLoadErrors.set(resolvedPath, error && error.message ? error.message.split('\n')[0] : String(error));
286
375
  return null;
287
376
  }
288
377
  }
@@ -302,9 +391,11 @@ function loadTailwindSpacing(resolvedPath) {
302
391
  }
303
392
 
304
393
  function mergeTokenMapFromTailwindSpacing({
394
+ ambiguous = {},
305
395
  currentMap,
306
396
  origins = null,
307
397
  tailwindConfigPath,
398
+ warnings = [],
308
399
  }) {
309
400
  if (!tailwindConfigPath) {
310
401
  return currentMap;
@@ -312,10 +403,16 @@ function mergeTokenMapFromTailwindSpacing({
312
403
 
313
404
  const resolvedPath = path.resolve(process.cwd(), tailwindConfigPath);
314
405
  if (!fs.existsSync(resolvedPath)) {
406
+ warnings.push(`Tailwind config not found: ${tailwindConfigPath}`);
315
407
  return currentMap;
316
408
  }
317
409
 
318
410
  const spacing = loadTailwindSpacing(resolvedPath);
411
+ if (tailwindLoadErrors.has(resolvedPath)) {
412
+ // A config that throws used to read as "no known token" (cq-05).
413
+ warnings.push(`Tailwind config ${tailwindConfigPath} could not be loaded: ${tailwindLoadErrors.get(resolvedPath)}`);
414
+ return currentMap;
415
+ }
319
416
  if (!isPlainObject(spacing) || Object.keys(spacing).length === 0) {
320
417
  return currentMap;
321
418
  }
@@ -323,6 +420,7 @@ function mergeTokenMapFromTailwindSpacing({
323
420
  const nextMap = {
324
421
  ...currentMap,
325
422
  };
423
+ const collector = createCollector();
326
424
 
327
425
  for (const [key, value] of Object.entries(spacing)) {
328
426
  if (typeof value !== 'string') {
@@ -335,12 +433,14 @@ function mergeTokenMapFromTailwindSpacing({
335
433
  }
336
434
 
337
435
  const normalizedRaw = formatLength(parsed.number, parsed.unit || 'px');
338
- nextMap[normalizedRaw] = `theme(spacing.${key})`;
339
- if (origins && !origins[nextMap[normalizedRaw]]) {
340
- origins[nextMap[normalizedRaw]] = displayOrigin(resolvedPath);
436
+ const token = `theme(spacing.${key})`;
437
+ collect(collector, normalizedRaw, token, true);
438
+ if (origins && !origins[token]) {
439
+ origins[token] = displayOrigin(resolvedPath);
341
440
  }
342
441
  }
343
442
 
443
+ applyCollector(nextMap, ambiguous, collector);
344
444
  return nextMap;
345
445
  }
346
446
 
@@ -348,18 +448,24 @@ function mergeTokenMapFromTailwindSpacing({
348
448
  * The raw-length to token-reference map a rule fixes with. Pass `origins` to
349
449
  * also learn where each token reference came from (the token map file, the
350
450
  * stylesheet, the Tailwind config), keyed by the reference; an explicit
351
- * `tokenMap` entry has no origin.
451
+ * `tokenMap` entry has no origin. Pass `ambiguous` to learn the keys several
452
+ * tokens of one source hold, each with its candidates: those keys are never a
453
+ * fix (fix-06).
352
454
  */
353
455
  function buildEffectiveTokenMap({
456
+ ambiguous = {},
354
457
  options,
355
458
  origins = null,
356
459
  root,
357
460
  tokenRegex,
461
+ warnings = [],
358
462
  }) {
359
463
  let tokenMap = {};
360
464
 
361
465
  if (options.tokenMapFile) {
362
466
  tokenMap = mergeTokenMapFromFile({
467
+ ambiguous,
468
+ warnings,
363
469
  baseFontSize: options.baseFontSize,
364
470
  currentMap: tokenMap,
365
471
  origins,
@@ -379,6 +485,8 @@ function buildEffectiveTokenMap({
379
485
 
380
486
  if (options.tokenMapFromTailwindSpacing && options.tailwindConfigPath) {
381
487
  tokenMap = mergeTokenMapFromTailwindSpacing({
488
+ ambiguous,
489
+ warnings,
382
490
  currentMap: tokenMap,
383
491
  origins,
384
492
  tailwindConfigPath: options.tailwindConfigPath,
@@ -386,7 +494,7 @@ function buildEffectiveTokenMap({
386
494
  }
387
495
 
388
496
  // Explicit tokenMap applied last so it takes precedence over auto-derived tokens
389
- tokenMap = mergeExplicitTokenMap(tokenMap, options.tokenMap);
497
+ tokenMap = mergeExplicitTokenMap(tokenMap, options.tokenMap, ambiguous);
390
498
 
391
499
  return tokenMap;
392
500
  }