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
@@ -45,6 +45,52 @@ const TOKEN_KIND_PATTERNS = Object.freeze({
45
45
  typography: /^--(?:(?:font|font-size|line-height|leading|tracking|typography|text|fs)-|(?:[\w-]*-)?(?:letter|word)-spacing(?:-|$))/,
46
46
  });
47
47
 
48
+ /*
49
+ * The second reading of a spacing token source, used only when the first, by
50
+ * the names above, finds no length in it (tf-01). A file that resolved a scale
51
+ * before resolves the same one; a file that gave nothing gets these chances:
52
+ *
53
+ * - names in any case, with a camelCase or digit boundary after the word:
54
+ * `--spacingXs` (the default @tokens-studio/sd-transforms output), `--Space-1`,
55
+ * `Space1` from Style Dictionary's json/flat;
56
+ * - in JSON, a token typed as a dimension whatever its name: DTCG `$type:
57
+ * dimension` on the token or a group above it, or a Tokens Studio or Style
58
+ * Dictionary `type` of `spacing`, `sizing` or `dimension`. A typed token
59
+ * named for another kind (radius, font size, border width, breakpoint) is
60
+ * still left out.
61
+ */
62
+ const RELAXED_SPACING_NAME = /^--(?:[\w-]*-)?(?<![Ll]etter-)(?<![Ww]ord-)(?<!LETTER-)(?<!WORD-)(?:[Ss]pac(?:e|ing|er)|SPAC(?:E|ING|ER))(?:-|$|(?=[A-Z0-9]))/;
63
+ const SPACING_TOKEN_TYPES = new Set(['dimension', 'spacing', 'sizing']);
64
+ const OTHER_KIND_NAME_SEGMENTS = new Set([
65
+ 'avatar', 'blur', 'border', 'breakpoint', 'breakpoints', 'container', 'corner', 'delay', 'duration', 'ease', 'easing',
66
+ 'elevation', 'font', 'fontsize', 'fs', 'height', 'icon', 'leading', 'letter', 'line', 'lineheight', 'motion', 'opacity',
67
+ 'outline', 'radii', 'radius', 'rounded', 'screen', 'screens', 'shadow', 'size', 'sizes', 'sizing', 'stroke', 'text',
68
+ 'tracking', 'typography', 'width', 'word', 'z',
69
+ ]);
70
+
71
+ /** Whether a token's name says it belongs to another kind: `--radius-sm`, `--fontSize-200`, `--border-width-thin`. */
72
+ function isOtherKindName(token) {
73
+ if (['typography', 'radius', 'motion', 'size'].some((kind) => TOKEN_KIND_PATTERNS[kind].test(token))) {
74
+ return true;
75
+ }
76
+ return token
77
+ .replace(/^--/, '')
78
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
79
+ .toLowerCase()
80
+ .split(/[-_.\s]+/)
81
+ .some((segment) => OTHER_KIND_NAME_SEGMENTS.has(segment));
82
+ }
83
+
84
+ function createRelaxedSpacingMatcher(matchesKind) {
85
+ return (token) => matchesKind(token) || RELAXED_SPACING_NAME.test(token);
86
+ }
87
+
88
+ /** A token whose value is a length, so a scale can be built from it; a unitless ratio is not one. */
89
+ function isLengthToken(token) {
90
+ const parsed = parseTokenValueLength(String(token.value));
91
+ return Boolean(parsed) && !(parsed.unit === '' && parsed.number !== 0);
92
+ }
93
+
48
94
  function isPlainObject(value) {
49
95
  return (
50
96
  value !== null &&
@@ -76,6 +122,7 @@ function createPatternMatcher(pattern, fallback) {
76
122
  const regex = new RegExp(pattern);
77
123
  return (token) => regex.test(token);
78
124
  } catch {
125
+ // Unreachable for token sources, which are validated first; the kind matcher is the safe default.
79
126
  return fallback;
80
127
  }
81
128
  }
@@ -100,11 +147,31 @@ function emptySourceWarning(source, format, tokenKind) {
100
147
  return `${prefix} tokens.`;
101
148
  }
102
149
  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.`;
150
+ return `${prefix} spacing tokens; spacing tokens are read by name (space, spacing or spacer, in any case) or, in JSON, by a dimension type, so set a tokenPattern on this source if its tokens are named and typed otherwise.`;
104
151
  }
105
152
  return `${prefix} ${tokenKind} tokens.`;
106
153
  }
107
154
 
155
+ /** Why a token value is not a length, for the warning that names a few (tf-02). */
156
+ function whyNotALength(value) {
157
+ const text = String(value).trim();
158
+ if (/^\{[^}]+\}$/.test(text)) return 'an alias to a token outside this file';
159
+ if (/\{[^}]+\}/.test(text)) return 'arithmetic over aliases';
160
+ if (/var\(/i.test(text)) return 'a var() chain';
161
+ if (/^-?\d*\.?\d+$/.test(text)) return 'a unitless number';
162
+ return 'not a length';
163
+ }
164
+
165
+ /**
166
+ * A source whose tokens parse but none of which is a length: aliases into
167
+ * another file, var() chains, unitless values. It counted its tokens and fell
168
+ * back silently before (tf-02); this names the count, three examples and why.
169
+ */
170
+ function noLengthWarning(source, format, tokens, kind) {
171
+ const examples = tokens.slice(0, 3).map((token) => `${token.token}: ${String(token.value).trim()} (${whyNotALength(token.value)})`);
172
+ return `Token source ${source.displayPath} (${format}): ${tokens.length} ${kind} token${tokens.length === 1 ? '' : 's'} found, none carries a length: ${examples.join('; ')}${tokens.length > 3 ? '; ...' : ''}. Add the file the aliases point to, or use values with a unit.`;
173
+ }
174
+
108
175
  /**
109
176
  * Read token sources into definitions, with one report per source. With
110
177
  * `warnWhenEmpty`, a source that parses but yields no token of the kind read
@@ -152,21 +219,38 @@ function parseTokenSources({
152
219
  continue;
153
220
  }
154
221
 
155
- let tokens;
156
- const matchesSource = normalizedSource.tokenPattern
222
+ // An invalid tokenPattern on a source used to fall back to the name rule in silence (cq-05).
223
+ let validPattern = Boolean(normalizedSource.tokenPattern);
224
+ if (validPattern) {
225
+ try {
226
+ new RegExp(normalizedSource.tokenPattern);
227
+ } catch (error) {
228
+ validPattern = false;
229
+ const warning = `Token source ${normalizedSource.displayPath}: tokenPattern "${normalizedSource.tokenPattern}" is not a valid regular expression (${error.message}); its tokens are read by name instead.`;
230
+ sourceReport.warnings.push(warning);
231
+ warnings.push(warning);
232
+ }
233
+ }
234
+ const matchesSource = validPattern
157
235
  ? createPatternMatcher(normalizedSource.tokenPattern, matchesKind)
158
236
  : matchesKind;
159
- const skipped = [];
237
+ let read;
160
238
  try {
161
- if (normalizedSource.format === 'css') {
162
- tokens = collectCssTokens(text, matchesSource, { lineComments: hasLineComments(normalizedSource.resolvedPath) });
163
- } else {
164
- const parsed = JSON.parse(text);
165
- const detectedFormat = normalizedSource.requestedFormat === 'auto'
166
- ? detectJsonTokenFormat(parsed)
239
+ const document = normalizedSource.format === 'css' ? null : JSON.parse(text);
240
+ if (document !== null) {
241
+ sourceReport.format = normalizedSource.requestedFormat === 'auto'
242
+ ? detectJsonTokenFormat(document)
167
243
  : normalizedSource.format;
168
- sourceReport.format = detectedFormat;
169
- tokens = collectJsonTokens(parsed, matchesSource, (token, reason) => skipped.push(`${token} (${reason})`));
244
+ }
245
+ const readWith = (selection) => readSourceTokens(normalizedSource, text, document, selection);
246
+ read = readWith({ matchesKind: matchesSource, selectedBy: validPattern ? 'tokenPattern' : 'name' });
247
+ // Names first; a source with no spacing length by name is read again by
248
+ // the wider rule (any case, camelCase, `$type`). See RELAXED_SPACING_NAME.
249
+ if (kind === 'spacing' && !validPattern && !read.tokens.some(isLengthToken)) {
250
+ const relaxed = readWith({ matchesKind: createRelaxedSpacingMatcher(matchesKind), selectByType: true, selectedBy: 'name' });
251
+ if (relaxed.tokens.some(isLengthToken)) {
252
+ read = relaxed;
253
+ }
170
254
  }
171
255
  } catch (err) {
172
256
  const warning = `Unable to parse token source ${normalizedSource.displayPath}: ${err.message}`;
@@ -176,6 +260,13 @@ function parseTokenSources({
176
260
  continue;
177
261
  }
178
262
 
263
+ const { deprecated, skipped, tokens } = read;
264
+ sourceReport.selectedBy = read.selectedBy;
265
+ if (deprecated.length > 0) {
266
+ // DTCG `$deprecated` tokens: on the scale in 3.x, never written by a fix (tf-11).
267
+ sourceReport.deprecated = deprecated;
268
+ }
269
+
179
270
  if (skipped.length > 0) {
180
271
  const warning = `Token source ${normalizedSource.displayPath}: skipped ${skipped.join(', ')}.`;
181
272
  sourceReport.warnings.push(warning);
@@ -188,6 +279,13 @@ function parseTokenSources({
188
279
  warnings.push(warning);
189
280
  }
190
281
 
282
+ // Tokens but no length: always a warning, since the scale falls back (tf-02).
283
+ if (kind === 'spacing' && tokens.length > 0 && !tokens.some(isLengthToken)) {
284
+ const warning = noLengthWarning(normalizedSource, sourceReport.format, tokens, kind);
285
+ sourceReport.warnings.push(warning);
286
+ warnings.push(warning);
287
+ }
288
+
191
289
  for (const token of tokens) {
192
290
  addDefinition(definitions, {
193
291
  baseFontSize,
@@ -195,6 +293,8 @@ function parseTokenSources({
195
293
  // `:root` and `@theme` declarations are the scale; a `.chip` variable is a
196
294
  // component parameter and stays out of it, as in the linted stylesheet (issue #258).
197
295
  scope: token.scope || 'root',
296
+ conditions: token.conditions || [],
297
+ deprecated: token.deprecated === true,
198
298
  source: sourceReport.file,
199
299
  token: token.token,
200
300
  value: token.value,
@@ -212,6 +312,29 @@ function parseTokenSources({
212
312
  };
213
313
  }
214
314
 
315
+ /**
316
+ * One reading of a parsed source: the tokens `selection` picks, the tokens it
317
+ * skipped with why, the deprecated tokens it left out, and how the tokens were
318
+ * chosen (`selectedBy`): `tokenPattern`, `name`, or `type` when at least one
319
+ * token was taken for its `$type` alone.
320
+ */
321
+ function readSourceTokens(source, text, document, selection) {
322
+ const skipped = [];
323
+ const deprecated = [];
324
+ const tokens = document === null
325
+ ? collectCssTokens(text, selection.matchesKind, { lineComments: hasLineComments(source.resolvedPath) })
326
+ : collectJsonTokens(document, selection, {
327
+ onDeprecated: (token) => deprecated.push(token),
328
+ onSkip: (token, reason) => skipped.push(`${token} (${reason})`),
329
+ });
330
+ return {
331
+ deprecated: Array.from(new Set(deprecated)).sort(),
332
+ selectedBy: tokens.some((token) => token.selectedBy === 'type') ? 'type' : selection.selectedBy,
333
+ skipped,
334
+ tokens,
335
+ };
336
+ }
337
+
215
338
  function normalizeTokenSource(source) {
216
339
  if (!isPlainObject(source)) {
217
340
  throw new Error('Token source entries must be strings or objects with a path.');
@@ -247,6 +370,10 @@ function detectSourceFormat(filePath) {
247
370
  }
248
371
 
249
372
  function detectJsonTokenFormat(parsed) {
373
+ if (tokensStudioSets(parsed)) {
374
+ return 'tokens-studio';
375
+ }
376
+
250
377
  let hasDtcg = false;
251
378
  let hasStyleDictionary = false;
252
379
 
@@ -307,6 +434,23 @@ function hasLineComments(filePath) {
307
434
  const ROOT_SELECTOR = /^(?::root|html|:host|:(?:where|is)\(\s*(?::root|html)\s*\))$/i;
308
435
  // At-rules that only condition their contents; the enclosing selector still decides the scope.
309
436
  const TRANSPARENT_AT_RULES = new Set(['media', 'supports', 'layer', 'container', 'scope', 'document']);
437
+ // Of those, the ones that apply their contents only some of the time. A token
438
+ // declared under one is undefined outside it, so a fix may write it only where
439
+ // the same condition holds (fix-02). `@layer` applies always.
440
+ const CONDITIONAL_AT_RULES = new Set(['media', 'supports', 'container', 'scope', 'document']);
441
+
442
+ /**
443
+ * A conditional at-rule as a comparable key: `@media (min-width:768px)` and
444
+ * `@media (min-width: 768px)` are one condition.
445
+ */
446
+ function conditionKey(name, params) {
447
+ const text = `${String(name).toLowerCase()} ${String(params || '')}`
448
+ .replace(/\s+/g, ' ')
449
+ .replace(/\s*([():,])\s*/g, '$1')
450
+ .trim()
451
+ .toLowerCase();
452
+ return text;
453
+ }
310
454
 
311
455
  /**
312
456
  * Whether `//` at `index` starts a line comment. Never in plain CSS, and never
@@ -402,6 +546,44 @@ function readCustomPropertyValue(source, start, lineComments) {
402
546
  return { end: index, value: value.replace(/\s*!\s*important\s*$/i, '').trim() };
403
547
  }
404
548
 
549
+ /** The scope of a declaration node: the AST-side twin of customPropertyDeclarations. */
550
+ function scopeOfNode(decl) {
551
+ for (let node = decl.parent; node; node = node.parent) {
552
+ if (node.type === 'rule') {
553
+ return String(node.selector).split(',').every((selector) => ROOT_SELECTOR.test(selector.trim())) ? 'root' : 'component';
554
+ }
555
+ if (node.type === 'atrule') {
556
+ const name = String(node.name).toLowerCase();
557
+ if (name === 'theme') return 'root';
558
+ if (!TRANSPARENT_AT_RULES.has(name)) return 'component';
559
+ }
560
+ }
561
+ return 'root';
562
+ }
563
+
564
+ /** The conditional at-rules (`@media`, `@supports`, `@container`) a PostCSS node sits under, as condition keys. */
565
+ function conditionsOfNode(node) {
566
+ const conditions = [];
567
+ for (let parent = node.parent; parent; parent = parent.parent) {
568
+ if (parent.type === 'atrule' && CONDITIONAL_AT_RULES.has(String(parent.name).toLowerCase())) {
569
+ conditions.push(conditionKey(parent.name, parent.params));
570
+ }
571
+ }
572
+ return conditions;
573
+ }
574
+
575
+ /** The conditional at-rules a declaration sits under, as condition keys. */
576
+ function conditionsOfBlockHeaders(headers) {
577
+ const conditions = [];
578
+ for (const header of headers) {
579
+ const match = header.match(/^@([\w-]+)\s*(.*)$/);
580
+ if (match && CONDITIONAL_AT_RULES.has(match[1].toLowerCase())) {
581
+ conditions.push(conditionKey(match[1], match[2]));
582
+ }
583
+ }
584
+ return conditions;
585
+ }
586
+
405
587
  function scopeOfBlockHeaders(headers) {
406
588
  for (let index = headers.length - 1; index >= 0; index -= 1) {
407
589
  const header = headers[index];
@@ -421,7 +603,7 @@ function scopeOfBlockHeaders(headers) {
421
603
  * for `:root`, `html`, `:host` and `@theme` blocks (through conditional
422
604
  * at-rules), `component` for anything else. One pass over the source that
423
605
  * skips comments and strings, so a brace in a comment cannot shift the
424
- * scope; this is the text-side twin of scopeOfNode in scale-inference.js.
606
+ * scope; this is the text-side twin of scopeOfNode.
425
607
  */
426
608
  function customPropertyDeclarations(source, { lineComments = true } = {}) {
427
609
  const declarations = [];
@@ -475,7 +657,7 @@ function customPropertyDeclarations(source, { lineComments = true } = {}) {
475
657
  if (match) {
476
658
  const { end, value } = readCustomPropertyValue(source, index + match[0].length, lineComments);
477
659
  if (value) {
478
- declarations.push({ scope: scopeOfBlockHeaders(headers), token: match[1], value });
660
+ declarations.push({ conditions: conditionsOfBlockHeaders(headers), scope: scopeOfBlockHeaders(headers), token: match[1], value });
479
661
  }
480
662
  index = end;
481
663
  continue;
@@ -1013,33 +1195,67 @@ function formatScssValue(value) {
1013
1195
  }
1014
1196
 
1015
1197
  /**
1016
- * Tokens in a DTCG, Style Dictionary or flat JSON file. References
1017
- * (`{dimension.100}`, `{size.base.value}`) are resolved against the whole file
1018
- * first, so a semantic alias over a primitive of another kind still counts
1019
- * (issue #267). `onSkip(token, reason)` hears about tokens of the requested
1020
- * kind that were left out, such as a dimension in an unsupported unit.
1198
+ * Tokens in a DTCG, Style Dictionary, Tokens Studio or flat JSON file.
1199
+ * References (`{dimension.100}`, `{size.base.value}`) are resolved against the
1200
+ * whole file first, so a semantic alias over a primitive of another kind still
1201
+ * counts (issue #267). `selection.matchesKind` picks tokens by name and, with
1202
+ * `selection.selectByType`, a token typed as a dimension is picked whatever its
1203
+ * name (tf-01). `hooks.onSkip(token, reason)` hears about tokens of the
1204
+ * requested kind that were left out, such as a dimension in an unsupported
1205
+ * unit, and `hooks.onDeprecated(token)` about DTCG `$deprecated` ones (tf-11).
1021
1206
  */
1022
- function collectJsonTokens(parsed, matchesKind, onSkip = () => {}) {
1207
+ function collectJsonTokens(parsed, selection, hooks = {}) {
1023
1208
  if (!isPlainObject(parsed)) {
1024
1209
  return [];
1025
1210
  }
1026
1211
 
1027
1212
  const tokens = [];
1028
- const context = { matchesKind, onSkip, root: parsed };
1029
- walkJsonTokenGroup(parsed, [], tokens, context);
1213
+ const context = {
1214
+ matchesKind: selection.matchesKind,
1215
+ onDeprecated: hooks.onDeprecated || (() => {}),
1216
+ onSkip: hooks.onSkip || (() => {}),
1217
+ root: parsed,
1218
+ selectByType: Boolean(selection.selectByType),
1219
+ };
1220
+ const studio = tokensStudioSets(parsed);
1221
+ if (!studio) {
1222
+ walkJsonTokenGroup(parsed, [], tokens, context);
1223
+ return tokens;
1224
+ }
1225
+
1226
+ // Tokens Studio (tf-08): each set is read without its set name, as
1227
+ // sd-transforms names them, and references resolve across the sets in
1228
+ // `tokenSetOrder`, a later set overriding an earlier one.
1229
+ const seen = new Set();
1230
+ for (const name of studio.sets) {
1231
+ const setTokens = [];
1232
+ walkJsonTokenGroup(parsed[name], [], setTokens, { ...context, root: studio.root, setName: name, studio: true });
1233
+ for (const token of setTokens) {
1234
+ const key = `${token.token}\n${token.value}`;
1235
+ if (!seen.has(key)) {
1236
+ seen.add(key);
1237
+ tokens.push(token);
1238
+ }
1239
+ }
1240
+ }
1030
1241
  return tokens;
1031
1242
  }
1032
1243
 
1033
- function walkJsonTokenGroup(group, segments, tokens, context, inheritedType = null) {
1034
- const { matchesKind, onSkip } = context;
1244
+ function walkJsonTokenGroup(group, segments, tokens, context, inherited = { deprecated: undefined, type: null }) {
1035
1245
  for (const [key, value] of Object.entries(group)) {
1246
+ // DTCG 2025.10 `$root`: the group's own token, named for the group (`space.$root` is `--space`).
1247
+ if (key === '$root' && isPlainObject(value) && segments.length > 0) {
1248
+ readJsonToken(value, segments, null, tokens, context, inherited);
1249
+ continue;
1250
+ }
1251
+
1036
1252
  if (isMetadataKey(key)) {
1037
1253
  continue;
1038
1254
  }
1039
1255
 
1040
1256
  if (typeof value === 'string' || typeof value === 'number') {
1041
1257
  const tokenEntry = tokenFromPrimitive(key, value, segments);
1042
- if (tokenEntry && matchesKind(tokenEntry.token)) {
1258
+ if (tokenEntry && context.matchesKind(tokenEntry.token)) {
1043
1259
  tokens.push(tokenEntry);
1044
1260
  }
1045
1261
  continue;
@@ -1049,27 +1265,204 @@ function walkJsonTokenGroup(group, segments, tokens, context, inheritedType = nu
1049
1265
  continue;
1050
1266
  }
1051
1267
 
1052
- // DTCG `$type` applies to the node and, on a group, to every token below it.
1053
- const type = typeof value.$type === 'string' ? value.$type : inheritedType;
1054
- const leaf = leafTokenValue(value, context.root, type);
1055
- if (leaf !== null) {
1056
- const token = key.startsWith('--')
1057
- ? key
1058
- : toCustomProperty([...segments, key]);
1059
- if (matchesKind(token)) {
1060
- if (leaf.value !== null) {
1061
- tokens.push({ token, value: leaf.value });
1062
- } else if (leaf.skipped) {
1063
- onSkip(token, leaf.skipped);
1064
- }
1065
- }
1268
+ if (readJsonToken(value, [...segments, key], key.startsWith('--') ? key : null, tokens, context, inherited)) {
1066
1269
  continue;
1067
1270
  }
1068
1271
 
1069
- walkJsonTokenGroup(value, [...segments, key], tokens, context, type);
1272
+ walkJsonTokenGroup(value, [...segments, key], tokens, context, inheritedFrom(value, inherited));
1070
1273
  }
1071
1274
  }
1072
1275
 
1276
+ /** What a node passes down: DTCG `$type` and `$deprecated` apply to the node and, on a group, to every token below it. */
1277
+ function inheritedFrom(node, inherited) {
1278
+ return {
1279
+ deprecated: Object.prototype.hasOwnProperty.call(node, '$deprecated') ? node.$deprecated : inherited.deprecated,
1280
+ type: typeof node.$type === 'string' ? node.$type : inherited.type,
1281
+ };
1282
+ }
1283
+
1284
+ /** DTCG `$deprecated`: `true` or an explanation string; `false` undoes a group's. */
1285
+ function isDeprecated(value) {
1286
+ return value === true || typeof value === 'string';
1287
+ }
1288
+
1289
+ /**
1290
+ * Read `node` as one token named by `segments` (or `explicitName`), when it is
1291
+ * a token. Returns false for a group, so the caller walks into it.
1292
+ */
1293
+ function readJsonToken(node, segments, explicitName, tokens, context, inherited) {
1294
+ const own = inheritedFrom(node, inherited);
1295
+ const leaf = leafTokenValue(node, context.root, own.type);
1296
+ if (leaf === null) {
1297
+ return false;
1298
+ }
1299
+
1300
+ const selection = tokenSelection(explicitName || toCustomProperty(segments), segments, node, own, context);
1301
+ if (!selection) {
1302
+ return true;
1303
+ }
1304
+ const { selectedBy, token } = selection;
1305
+ // A DTCG `$deprecated` token is named in provenance and never written by a
1306
+ // fix; in 3.x its value stays on the scale so no finding is added (tf-11).
1307
+ // It leaves the scale in 4.0.
1308
+ const deprecated = isDeprecated(own.deprecated);
1309
+ if (deprecated) {
1310
+ context.onDeprecated(token);
1311
+ }
1312
+
1313
+ const value = context.studio && leaf.value !== null
1314
+ ? tokensStudioValue(leaf.value, context.root, tokenTypeOf(node, own))
1315
+ : leaf.value;
1316
+ if (value !== null) {
1317
+ tokens.push({ ...(deprecated ? { deprecated } : {}), ...(selectedBy === 'type' ? { selectedBy } : {}), token, value });
1318
+ } else if (leaf.skipped) {
1319
+ context.onSkip(token, leaf.skipped);
1320
+ }
1321
+ return true;
1322
+ }
1323
+
1324
+ /** The type a token declares: DTCG `$type` (its own or a group's), else a Tokens Studio or Style Dictionary `type`. */
1325
+ function tokenTypeOf(node, own) {
1326
+ const type = own.type || (typeof node.type === 'string' ? node.type : null);
1327
+ return type ? type.trim().toLowerCase() : null;
1328
+ }
1329
+
1330
+ /** Whether a token is read, and why (`name` or `type`), with the name it is read under; null when it is not. */
1331
+ function tokenSelection(token, segments, node, own, context) {
1332
+ if (context.matchesKind(token)) {
1333
+ return { selectedBy: 'name', token };
1334
+ }
1335
+ // Before 3.20 a Tokens Studio token was named with its set; a set called `spacing` still gives `--spacing-*` tokens.
1336
+ const legacyName = context.setName ? toCustomProperty([context.setName, ...segments]) : null;
1337
+ if (legacyName && context.matchesKind(legacyName)) {
1338
+ return { selectedBy: 'name', token: legacyName };
1339
+ }
1340
+ if (context.selectByType && SPACING_TOKEN_TYPES.has(tokenTypeOf(node, own)) && !isOtherKindName(token)) {
1341
+ return { selectedBy: 'type', token };
1342
+ }
1343
+ return null;
1344
+ }
1345
+
1346
+ /**
1347
+ * Tokens Studio's shape: sets at the top level, ordered by
1348
+ * `$metadata.tokenSetOrder`, with `$themes` naming which sets a theme enables.
1349
+ * Returns the sets to read, in order, and the merged tree references resolve
1350
+ * against; null when the file is not a Tokens Studio export.
1351
+ *
1352
+ * Every set in `tokenSetOrder` is read, as every set was read before, so the
1353
+ * scale stays the union of the sets; without an order, the sets the first
1354
+ * theme enables are read.
1355
+ */
1356
+ function tokensStudioSets(parsed) {
1357
+ if (!isPlainObject(parsed)) {
1358
+ return null;
1359
+ }
1360
+ const order = isPlainObject(parsed.$metadata) && Array.isArray(parsed.$metadata.tokenSetOrder)
1361
+ ? parsed.$metadata.tokenSetOrder
1362
+ : null;
1363
+ const themes = Array.isArray(parsed.$themes) ? parsed.$themes : null;
1364
+ if (!order && !themes) {
1365
+ return null;
1366
+ }
1367
+
1368
+ const isSet = (name) => typeof name === 'string' && !name.startsWith('$') && isPlainObject(parsed[name]);
1369
+ const allSets = Object.keys(parsed).filter(isSet);
1370
+ let sets;
1371
+ if (order) {
1372
+ const ordered = Array.from(new Set(order.filter(isSet)));
1373
+ sets = [...ordered, ...allSets.filter((name) => !ordered.includes(name))];
1374
+ } else {
1375
+ const theme = themes.find((entry) => isPlainObject(entry) && isPlainObject(entry.selectedTokenSets));
1376
+ const enabled = theme
1377
+ ? Object.keys(theme.selectedTokenSets).filter((name) => theme.selectedTokenSets[name] === 'enabled' && isSet(name))
1378
+ : [];
1379
+ sets = enabled.length > 0 ? enabled : allSets;
1380
+ }
1381
+
1382
+ // Sets that are only referenced (a theme's `source` sets) first, then the read sets in order.
1383
+ const root = Object.create(null);
1384
+ for (const name of [...allSets.filter((item) => !sets.includes(item)), ...sets]) {
1385
+ mergeTokenTree(root, parsed[name]);
1386
+ }
1387
+ return { root, sets };
1388
+ }
1389
+
1390
+ /** Merge a token tree into `target`: groups merge, a token replaces. Null-prototype copies, so no key reaches a prototype. */
1391
+ function mergeTokenTree(target, source) {
1392
+ for (const [key, value] of Object.entries(source)) {
1393
+ const isGroup = isPlainObject(value) && rawTokenValue(value) === undefined;
1394
+ if (isGroup && isPlainObject(target[key]) && rawTokenValue(target[key]) === undefined) {
1395
+ mergeTokenTree(target[key], value);
1396
+ } else {
1397
+ target[key] = isGroup ? mergeTokenTree(Object.create(null), value) : value;
1398
+ }
1399
+ }
1400
+ return target;
1401
+ }
1402
+
1403
+ const UNITLESS_NUMBER = /^-?(?:\d+\.?\d*|\.\d+)$/;
1404
+ const STUDIO_REFERENCE = /\{([^{}]+)\}/g;
1405
+
1406
+ /**
1407
+ * A Tokens Studio value for a spacing, sizing or dimension token: a unitless
1408
+ * number is px, as Tokens Studio and sd-transforms read it, and `+ - * /`
1409
+ * over numbers and references (`{spacing.sm} * 2`) is evaluated by the Sass
1410
+ * evaluator. Other types, and what cannot be evaluated, are left as written.
1411
+ */
1412
+ function tokensStudioValue(value, root, type) {
1413
+ if (!SPACING_TOKEN_TYPES.has(type)) {
1414
+ return value;
1415
+ }
1416
+ const text = String(value).trim();
1417
+ if (UNITLESS_NUMBER.test(text)) {
1418
+ return `${Number(text)}px`;
1419
+ }
1420
+ if (parseLengthToken(text)) {
1421
+ return text;
1422
+ }
1423
+ return evaluateTokensStudioMath(text, root, new Set()) || value;
1424
+ }
1425
+
1426
+ function evaluateTokensStudioMath(text, root, stack) {
1427
+ const references = [];
1428
+ // A reference becomes a parenthesised Sass variable; a px literal becomes a plain number, as a resolved reference does.
1429
+ const expression = text
1430
+ .replace(STUDIO_REFERENCE, (match, reference) => `($r${references.push(reference.trim()) - 1})`)
1431
+ .replace(/(\d)px\b/gi, '$1');
1432
+ const resolveVariable = (name) => {
1433
+ const reference = references[Number(name.slice(1))];
1434
+ if (reference === undefined || stack.has(reference) || stack.size >= MAX_JSON_REFERENCE_DEPTH) {
1435
+ return null;
1436
+ }
1437
+ const raw = lookupJsonReference(root, reference);
1438
+ if (raw === undefined || raw === null) {
1439
+ return null;
1440
+ }
1441
+ stack.add(reference);
1442
+ try {
1443
+ const resolved = resolveJsonValue(raw, root);
1444
+ if (resolved.value === null) {
1445
+ return null;
1446
+ }
1447
+ const inner = String(resolved.value).trim();
1448
+ const length = parseLengthToken(inner) ? inner : evaluateTokensStudioMath(inner, root, stack);
1449
+ const parsed = length ? parseLengthToken(length) : null;
1450
+ if (!parsed) {
1451
+ return null;
1452
+ }
1453
+ return { number: parsed.number, unit: parsed.unit === 'px' ? '' : parsed.unit };
1454
+ } finally {
1455
+ stack.delete(reference);
1456
+ }
1457
+ };
1458
+ const result = evaluateScssExpression(expression, resolveVariable, stack);
1459
+ if (!result || !Number.isFinite(result.number) || !['', 'rem'].includes(result.unit)) {
1460
+ return null;
1461
+ }
1462
+ const rounded = Math.round(result.number * 1000) / 1000;
1463
+ return `${rounded}${result.unit || 'px'}`;
1464
+ }
1465
+
1073
1466
  function tokenFromPrimitive(key, value, segments) {
1074
1467
  if (key.startsWith('--')) {
1075
1468
  return {
@@ -1195,6 +1588,7 @@ function lookupJsonPointer(root, pointer) {
1195
1588
  try {
1196
1589
  segment = decodeURIComponent(encoded).replace(/~1/g, '/').replace(/~0/g, '~');
1197
1590
  } catch {
1591
+ // A malformed escape names no token: the reference is reported as unresolved.
1198
1592
  return undefined;
1199
1593
  }
1200
1594
  if (Array.isArray(node)) {
@@ -1325,8 +1719,27 @@ function extractTokenName(value) {
1325
1719
  return null;
1326
1720
  }
1327
1721
 
1722
+ /**
1723
+ * Where a fix may write a token from one declaration of it (fix-02):
1724
+ * `{ global: true }` for a root declaration outside every conditional at-rule,
1725
+ * `{ conditions }` for a root declaration under `@media`, `@supports` or
1726
+ * `@container` (the fixed declaration must sit under the same conditions),
1727
+ * `{ anchor }` for a declaration in the linted stylesheet's own component
1728
+ * block (the fixed declaration must sit inside that block), and null for a
1729
+ * component declaration in another file, which no fix may write.
1730
+ */
1731
+ function fixScopeOf(scope, conditions, anchor) {
1732
+ if (scope === 'root') {
1733
+ return conditions.length === 0 ? { global: true } : { conditions: [...conditions] };
1734
+ }
1735
+ return anchor ? { anchor } : null;
1736
+ }
1737
+
1328
1738
  function addDefinition(definitions, {
1739
+ anchor = null,
1329
1740
  baseFontSize,
1741
+ conditions = [],
1742
+ deprecated = false,
1330
1743
  file,
1331
1744
  scope = 'root',
1332
1745
  source,
@@ -1335,6 +1748,7 @@ function addDefinition(definitions, {
1335
1748
  }) {
1336
1749
  const entry = definitions.get(token) || {
1337
1750
  files: new Set(),
1751
+ fixScopes: [],
1338
1752
  normalizedValues: new Set(),
1339
1753
  scopes: new Set(),
1340
1754
  sources: new Set(),
@@ -1344,6 +1758,11 @@ function addDefinition(definitions, {
1344
1758
 
1345
1759
  entry.files.add(file);
1346
1760
  entry.scopes.add(scope);
1761
+ // A deprecated token gets no fix scope, so no fix writes it.
1762
+ const fixScope = deprecated ? null : fixScopeOf(scope, conditions, anchor);
1763
+ if (fixScope) {
1764
+ entry.fixScopes.push(fixScope);
1765
+ }
1347
1766
  entry.sources.add(source);
1348
1767
  entry.values.add(String(value).trim());
1349
1768
 
@@ -1425,7 +1844,9 @@ module.exports = {
1425
1844
  addDefinition,
1426
1845
  collectCssTokens,
1427
1846
  collectScssTokens,
1847
+ conditionsOfNode,
1428
1848
  customPropertyDeclarations,
1849
+ scopeOfNode,
1429
1850
  createTokenKindMatcher,
1430
1851
  getNormalizedValueKeys,
1431
1852
  hasLineComments,
@@ -84,7 +84,7 @@ function varFallbackNodes(node) {
84
84
  * Walk value nodes for a length rule. `walkNode` returns true to skip a
85
85
  * function's children, or WALK_TOKEN_FALLBACK to walk only the fallback of a
86
86
  * var(). Nodes inside a fallback carry `tokenFallbackOf`, the names of the
87
- * var()s they fall back from, outermost first.
87
+ * var()s they fall back from, outermost first, whether the name is a token or not.
88
88
  */
89
89
  function createNodeWalker(walkNode, rootFunctionName = null) {
90
90
  const walkNodes = (nodes, parentFunction, firstArgIndex = 1, tokenFallbackOf = []) => {
@@ -106,7 +106,9 @@ function createNodeWalker(walkNode, rootFunctionName = null) {
106
106
  const fnName = node.value.toLowerCase();
107
107
  const skipChildren = walkNode(node, context);
108
108
 
109
- if (skipChildren === WALK_TOKEN_FALLBACK) {
109
+ // Any var() falls back from its name, a token or not: its fallback
110
+ // nodes carry that name, so no fix writes a token there (fix-02).
111
+ if (skipChildren === WALK_TOKEN_FALLBACK || (!skipChildren && fnName === 'var')) {
110
112
  walkNodes(varFallbackNodes(node), { name: fnName }, 2, [...tokenFallbackOf, varName(node)]);
111
113
  continue;
112
114
  }