oxlint-tailwindcss 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -7,7 +7,7 @@ import { tmpdir, userInfo } from "node:os";
7
7
  //#region \0rolldown/runtime.js
8
8
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
9
9
  //#endregion
10
- //#region ../../node_modules/.pnpm/@oxlint+plugins@1.74.0/node_modules/@oxlint/plugins/index.js
10
+ //#region ../../node_modules/.pnpm/@oxlint+plugins@1.76.0/node_modules/@oxlint/plugins/index.js
11
11
  /**
12
12
  * Define a plugin.
13
13
  *
@@ -963,6 +963,7 @@ function roundRemValue(className) {
963
963
  //#endregion
964
964
  //#region src/design-system/cache.ts
965
965
  const EMPTY_DECLARATIONS = [];
966
+ const EMPTY_TOKEN_VALUES = [];
966
967
  var DesignSystemCache = class DesignSystemCache {
967
968
  canonicalMap = /* @__PURE__ */ new Map();
968
969
  deprecatedMap = /* @__PURE__ */ new Map();
@@ -974,6 +975,7 @@ var DesignSystemCache = class DesignSystemCache {
974
975
  propsMemo = /* @__PURE__ */ new Map();
975
976
  partialSet = /* @__PURE__ */ new Set();
976
977
  valueIdByText = null;
978
+ nextValueId = 0;
977
979
  variantOrderMap = /* @__PURE__ */ new Map();
978
980
  variantFactsMap = /* @__PURE__ */ new Map();
979
981
  arbitraryEquivMap = /* @__PURE__ */ new Map();
@@ -984,6 +986,8 @@ var DesignSystemCache = class DesignSystemCache {
984
986
  componentSet = /* @__PURE__ */ new Set();
985
987
  themeRefs = /* @__PURE__ */ new Map();
986
988
  definedVarSet = /* @__PURE__ */ new Set();
989
+ tokenValuesMap = /* @__PURE__ */ new Map();
990
+ scaleFacts = null;
987
991
  static fromPrecomputed(data) {
988
992
  const cache = new DesignSystemCache();
989
993
  cache._validClasses = data.validClasses;
@@ -1011,6 +1015,12 @@ var DesignSystemCache = class DesignSystemCache {
1011
1015
  }
1012
1016
  for (const name of data.definedVars ?? []) cache.definedVarSet.add(name);
1013
1017
  if (data.themeRefs) for (const [name, refs] of Object.entries(data.themeRefs)) cache.themeRefs.set(name, refs);
1018
+ for (const [prefix, entries] of Object.entries(data.tokenValues ?? {})) cache.tokenValuesMap.set(prefix, entries);
1019
+ if (data.scale) cache.scaleFacts = {
1020
+ unit: data.scale.unit,
1021
+ step: data.scale.step,
1022
+ prefixes: new Set(data.scale.prefixes)
1023
+ };
1014
1024
  cache._prefix = data.prefix ?? "";
1015
1025
  if (data.arbitraryEquivalents) for (const [arb, named] of Object.entries(data.arbitraryEquivalents)) cache.arbitraryEquivMap.set(arb, named);
1016
1026
  return cache;
@@ -1133,10 +1143,63 @@ var DesignSystemCache = class DesignSystemCache {
1133
1143
  isKnownClass(className) {
1134
1144
  return this.validitySet.has(this.stripProjectPrefix(className));
1135
1145
  }
1146
+ /**
1147
+ * Is this a NAMED group/peer marker — `group/menu-item`, `peer/menu-button`?
1148
+ *
1149
+ * A marker binds a variant to one specific ancestor or sibling, and the
1150
+ * consumer's compiled selector hard-codes it as a class selector:
1151
+ * `group-hover/menu-item:underline` emits
1152
+ * `:is(:where(.group\/menu-item):hover *)`. A class selector matches whole
1153
+ * tokens, so bare `group` does not satisfy it — the named marker is required
1154
+ * markup. Tailwind emits no CSS for the marker itself, which is why
1155
+ * `no-unknown-classes` cannot ask "does it compile?" about one.
1156
+ *
1157
+ * Derived, not listed: the base must be a precomputed class that emits ZERO
1158
+ * declarations, which across every fixture resolves to exactly `group` and
1159
+ * `peer` (2 of ~23.6k). It self-prunes if Tailwind drops the variants,
1160
+ * self-extends if a new CSS-less marker appears, and excludes `@container/main`
1161
+ * for free — that one HAS declarations. The component set is subtracted
1162
+ * because a class referenced only through `[class~="…"]` (`not-prose`) also has
1163
+ * no declarations of its own, and `not-prose/x` is not Tailwind syntax.
1164
+ *
1165
+ * The name is user-chosen and Tailwind never checks that it exists, so any
1166
+ * NON-EMPTY name is accepted — including the shapes only an arbitrary modifier
1167
+ * can reach (`group/*`, `group/a/b`, `peer//x`), which is why this splits at
1168
+ * the FIRST slash rather than the last one `isValid` uses. The empty name is
1169
+ * the one genuinely dead spelling: `group-hover/` compiles to nothing.
1170
+ */
1171
+ isMarkerClass(className) {
1172
+ const bare = this.stripProjectPrefix(className);
1173
+ const slash = bare.indexOf("/");
1174
+ if (slash <= 0 || slash === bare.length - 1) return false;
1175
+ const base = bare.slice(0, slash);
1176
+ return this.validitySet.has(base) && !this.componentSet.has(base) && this.getCssDeclarations(base).length === 0;
1177
+ }
1136
1178
  /** Variant names the design system reports, for suggesting a typo's neighbour. */
1137
1179
  variantNames() {
1138
1180
  return [...this.variantOrderMap.keys()];
1139
1181
  }
1182
+ /**
1183
+ * The numeric theme tokens this utility prefix can be written with, as
1184
+ * `[literal value, class]`. Empty when the prefix has none.
1185
+ */
1186
+ tokenValuesFor(prefix) {
1187
+ return this.tokenValuesMap.get(this.stripProjectPrefix(prefix)) ?? EMPTY_TOKEN_VALUES;
1188
+ }
1189
+ /**
1190
+ * The spacing scale as the design system describes it: the resolved value of
1191
+ * `--spacing`, the granularity Tailwind's own enumerated steps use, and whether
1192
+ * a given prefix reads it. `null` when the theme has no `--spacing`.
1193
+ */
1194
+ get scale() {
1195
+ return this.scaleFacts ? {
1196
+ unit: this.scaleFacts.unit,
1197
+ step: this.scaleFacts.step
1198
+ } : null;
1199
+ }
1200
+ readsScale(prefix) {
1201
+ return this.scaleFacts?.prefixes.has(this.stripProjectPrefix(prefix)) ?? false;
1202
+ }
1140
1203
  isValid(className) {
1141
1204
  if (this.validitySet.has(className)) return true;
1142
1205
  const utility = extractUtility(className);
@@ -1281,7 +1344,10 @@ var DesignSystemCache = class DesignSystemCache {
1281
1344
  internDeclarations(className, raws, valueFacts) {
1282
1345
  const index = this.declIndex;
1283
1346
  if (!index) return EMPTY_DECLARATIONS;
1284
- if (!this.valueIdByText) this.valueIdByText = new Map(index.values.map((value, id) => [value, id]));
1347
+ if (!this.valueIdByText) {
1348
+ this.valueIdByText = new Map(index.values.map((value, id) => [value, id]));
1349
+ this.nextValueId = index.values.length;
1350
+ }
1285
1351
  const decls = [];
1286
1352
  let hasElement = false;
1287
1353
  let hasDescendant = false;
@@ -1289,8 +1355,7 @@ var DesignSystemCache = class DesignSystemCache {
1289
1355
  for (const [scopeToken, prop, value] of raws) {
1290
1356
  let valueId = this.valueIdByText.get(value);
1291
1357
  if (valueId === void 0) {
1292
- valueId = index.values.length;
1293
- index.values.push(value);
1358
+ valueId = this.nextValueId++;
1294
1359
  this.valueIdByText.set(value, valueId);
1295
1360
  }
1296
1361
  const facts = valueFacts[value];
@@ -1811,7 +1876,12 @@ function resolveImport(specifier, baseDir) {
1811
1876
  return null;
1812
1877
  }
1813
1878
 
1814
- function extractComponentClasses(cssPath, baseDir) {
1879
+ // The entry CSS plus every \`@import\` that resolves, one level deep. Shared by
1880
+ // the component-class scan and the \`definedVars\` scan: a custom property declared
1881
+ // in an imported file is as real to the browser as one in the entry, and treating
1882
+ // it as undefined makes prefer-theme-tokens propose a token that can change the
1883
+ // design (the #78 hazard, in miniature).
1884
+ function collectCssSources(cssPath, baseDir) {
1815
1885
  let css;
1816
1886
  try { css = readFileSync(cssPath, 'utf-8'); } catch { return []; }
1817
1887
  const files = [css];
@@ -1823,29 +1893,71 @@ function extractComponentClasses(cssPath, baseDir) {
1823
1893
  try { files.push(readFileSync(resolved, 'utf-8')); } catch {}
1824
1894
  }
1825
1895
  }
1826
- const result = [];
1896
+ return files;
1897
+ }
1898
+
1899
+ // Class names the project writes in its own CSS, read from the SELECTORS only.
1900
+ //
1901
+ // This used to scan whole files with two regexes, which harvested identifiers
1902
+ // from places that are not selectors at all: the URLs in Tailwind's own preflight
1903
+ // comments (\`developer.mozilla.org\` → \`mozilla\`, \`org\`; \`bugs.chromium.org\`;
1904
+ // \`-webkit-\`) and the decimals in declaration values (\`padding: 0.5rem\` →
1905
+ // \`5rem\`). Everything here reaches \`validitySet\`, so every project accepted
1906
+ // \`com\`, \`org\`, \`css\` and \`5rem\` as valid Tailwind classes.
1907
+ //
1908
+ // A selector is the text between the last \`{\`, \`}\` or \`;\` and the next \`{\`, so
1909
+ // scanning only what precedes a \`{\` skips declaration bodies by construction —
1910
+ // a declaration ends in \`;\` or \`}\` and never reaches one. Comments and strings
1911
+ // are stepped over. Requiring a CSS identifier start (never a digit) is the
1912
+ // second line of defence, for a decimal inside an at-rule prelude
1913
+ // (\`@media (min-width: 40.5rem)\`).
1914
+ function extractComponentClasses(cssPath, baseDir) {
1915
+ const files = collectCssSources(cssPath, baseDir);
1916
+ const result = new Set();
1917
+ const classRe = /\\.(-?[a-zA-Z_][\\w-]*)/g;
1827
1918
  for (const content of files) {
1828
- // Scan both @layer components AND @layer utilities
1829
- const layerRe = /@layer\\s+(?:components|utilities)\\s*\\{/g;
1830
- let lm;
1831
- while ((lm = layerRe.exec(content)) !== null) {
1832
- let depth = 1, i = lm.index + lm[0].length;
1833
- while (i < content.length && depth > 0) {
1834
- if (content[i] === '{') depth++;
1835
- if (content[i] === '}') depth--;
1919
+ let prelude = '';
1920
+ for (let i = 0; i < content.length; i++) {
1921
+ const c = content[i];
1922
+ if (c === '/' && content[i + 1] === '*') {
1923
+ const end = content.indexOf('*/', i + 2);
1924
+ i = end === -1 ? content.length : end + 1;
1925
+ continue;
1926
+ }
1927
+ if (c === '"' || c === "'") {
1928
+ const quote = c;
1836
1929
  i++;
1930
+ while (i < content.length && content[i] !== quote) {
1931
+ if (content[i] === '\\\\') i++;
1932
+ i++;
1933
+ }
1934
+ continue;
1935
+ }
1936
+ if (c === '{') {
1937
+ classRe.lastIndex = 0;
1938
+ let m;
1939
+ while ((m = classRe.exec(prelude)) !== null) result.add(m[1]);
1940
+ prelude = '';
1941
+ continue;
1837
1942
  }
1838
- const block = content.slice(lm.index + lm[0].length, i - 1);
1839
- const selRe = /\\.([\\w-]+)/g;
1840
- let sm;
1841
- while ((sm = selRe.exec(block)) !== null) result.push(sm[1]);
1943
+ if (c === '}' || c === ';') {
1944
+ // A statement at-rule carries a selector even though it has no block:
1945
+ // \`@custom-variant sidebar-open (&:where(.sidebar-open *));\` makes that
1946
+ // class load-bearing exactly the way \`group\`/\`peer\` are, so it has to
1947
+ // stay valid. Plain declarations never start with \`@\`, so this readmits
1948
+ // the selector without readmitting \`padding: 0.5rem\`.
1949
+ if (c === ';' && prelude.trimStart().charCodeAt(0) === 64) {
1950
+ classRe.lastIndex = 0;
1951
+ let m;
1952
+ while ((m = classRe.exec(prelude)) !== null) result.add(m[1]);
1953
+ }
1954
+ prelude = '';
1955
+ continue;
1956
+ }
1957
+ prelude += c;
1842
1958
  }
1843
- // Scan all class selectors anywhere in the file (.class-name)
1844
- const classSelRe = /\\.([a-zA-Z_][\\w-]*)/g;
1845
- let cs;
1846
- while ((cs = classSelRe.exec(content)) !== null) result.push(cs[1]);
1847
1959
  }
1848
- return [...new Set(result)];
1960
+ return [...result];
1849
1961
  }
1850
1962
 
1851
1963
  ${DECL_EXTRACTOR_SOURCE}
@@ -2250,11 +2362,13 @@ async function main() {
2250
2362
  }
2251
2363
 
2252
2364
  // Component classes from @layer components
2253
- const componentClasses = extractComponentClasses(cssPath, base);
2365
+ const componentSet = new Set(extractComponentClasses(cssPath, base));
2254
2366
 
2255
2367
  // Extract class names from attribute selectors [class~="..."] in CSS output.
2256
2368
  // Plugins like @tailwindcss/typography use these for modifier classes (e.g. "not-prose")
2257
2369
  // that don't generate their own CSS but are referenced in other classes' selectors.
2370
+ // Interned in a Set: typography references \`not-prose\` from ~230 selectors, and
2371
+ // pushing one entry per occurrence only inflated the cache artifact.
2258
2372
  const attrClassRe = /\\[class~="([^"]+)"\\]/g;
2259
2373
  for (let i = 0; i < cssResults.length; i++) {
2260
2374
  if (cssResults[i]) {
@@ -2262,10 +2376,11 @@ async function main() {
2262
2376
  attrClassRe.lastIndex = 0;
2263
2377
  while ((acm = attrClassRe.exec(cssResults[i])) !== null) {
2264
2378
  // Typography-style plugins emit \`[class~="tw:not-prose"]\` under a prefix.
2265
- componentClasses.push(unpfx(acm[1]));
2379
+ componentSet.add(unpfx(acm[1]));
2266
2380
  }
2267
2381
  }
2268
2382
  }
2383
+ const componentClasses = [...componentSet];
2269
2384
 
2270
2385
  // Arbitrary equivalents: map arbitrary forms to named equivalents.
2271
2386
  // Enumerate every dash split point so multi-segment utilities (e.g.
@@ -2309,20 +2424,21 @@ async function main() {
2309
2424
  }
2310
2425
  }
2311
2426
 
2312
- // Theme variables that dereference to another custom property. Only the
2313
- // referencing ones are stored (~a handful), and the reference list reuses the
2314
- // same balanced scanner the declaration values go through.
2315
- // Custom properties the project defines. The entry file covers the standard
2316
- // ':root { --x: ... }' pattern; definitions inside @imported files are not
2317
- // scanned, so an unseen definition reads as "undefined" — which only ever makes
2318
- // prefer-theme-tokens more willing to suggest, never less accurate about a
2319
- // definition it can see.
2320
- const definedVars = [...new Set(css.match(/--[\\w-]+(?=\\s*:)/g) || [])];
2427
+ // Custom properties the project defines, across the entry AND its resolved
2428
+ // @imports — splitting the theme across files is the normal shadcn/ui layout,
2429
+ // and a definition we cannot see reads as "undefined", which is what makes
2430
+ // prefer-theme-tokens propose a token that means something else. One level
2431
+ // deep, same as the component-class scan it shares \`collectCssSources\` with.
2432
+ const definedVars = [...new Set(
2433
+ collectCssSources(cssPath, base).flatMap(src => src.match(/--[\\w-]+(?=\\s*:)/g) || [])
2434
+ )];
2321
2435
 
2322
2436
  const themeRefs = {};
2437
+ const themeValues = new Map();
2323
2438
  if (ds.theme && typeof ds.theme.entries === 'function') {
2324
2439
  for (const [name, entry] of ds.theme.entries()) {
2325
2440
  const value = entry && typeof entry.value === 'string' ? entry.value : '';
2441
+ themeValues.set(name, value);
2326
2442
  if (!value.includes('var(')) continue;
2327
2443
  const reads = scanVarReads(value);
2328
2444
  const all = [...new Set([...reads[0], ...reads[1]])];
@@ -2330,7 +2446,77 @@ async function main() {
2330
2446
  }
2331
2447
  }
2332
2448
 
2333
- const json = JSON.stringify({ validClasses, canonical, deprecated, order, cssDeclarations, variantOrder, variantFacts, componentClasses, arbitraryEquivalents, themeRefs, definedVars, prefix });
2449
+ // ── What a literal value could have been written as (for prefer-scale-token) ──
2450
+ //
2451
+ // Two families, both derived. Neither is a name table: the emitted CSS says
2452
+ // which variable a class reads and the theme says what that variable is worth.
2453
+
2454
+ // A single declaration whose whole value is one \`var(--x)\` that the theme
2455
+ // resolves to a NUMBER. Numeric because that is the only thing the rule can
2456
+ // compare — a colour token could never match a literal the user typed — and
2457
+ // SINGLE because a class that declares more than the original is not an
2458
+ // equivalent: \`text-sm\` sets \`line-height\` too, so \`text-[14px]\` is not it.
2459
+ const NUMERIC_LITERAL = /^-?\\d*\\.?\\d+(rem|px|em|%|s|ms|deg)?$/;
2460
+ const tokenValues = {};
2461
+ for (const cls of validClasses) {
2462
+ if (cls.includes('[') || cls.includes('/')) continue;
2463
+ const css = declCss[cls];
2464
+ if (!css) continue;
2465
+ const open = css.indexOf('{');
2466
+ const close = css.indexOf('}');
2467
+ if (open < 0 || close < 0) continue;
2468
+ const body = css.slice(open + 1, close).replace(/\\s+/g, ' ').replace(/;\\s*$/, '').trim();
2469
+ const m = /^([a-z-]+):\\s*var\\((--[\\w-]+)\\)$/.exec(body);
2470
+ if (!m) continue;
2471
+ const value = themeValues.get(m[2]);
2472
+ if (!value || !NUMERIC_LITERAL.test(value)) continue;
2473
+ const dash = cls.lastIndexOf('-');
2474
+ if (dash <= 0) continue;
2475
+ const prefix = unpfx(cls).slice(0, unpfx(cls).lastIndexOf('-'));
2476
+ if (!prefix) continue;
2477
+ if (!tokenValues[prefix]) tokenValues[prefix] = [];
2478
+ tokenValues[prefix].push([value, unpfx(cls)]);
2479
+ }
2480
+
2481
+ // The spacing scale: its unit, which prefixes read it, and the granularity
2482
+ // Tailwind's own enumerated steps use. Every step getClassList() lists is a
2483
+ // multiple of that granularity, so deriving it is how the rule stays inside
2484
+ // what Tailwind does instead of inventing a threshold.
2485
+ const scaleUnit = themeValues.get('--spacing') || '';
2486
+ const scalePrefixes = [];
2487
+ if (scaleUnit) {
2488
+ const probes = [...knownPrefixes];
2489
+ const probeResults = ds.candidatesToCss(probes.map(p => pfx(p + '-1')));
2490
+ for (let i = 0; i < probes.length; i++) {
2491
+ const css = probeResults[i];
2492
+ if (!css) continue;
2493
+ // \`size-1\` emits width AND height, both reading the unit — one match is enough.
2494
+ if (css.includes('var(--spacing)')) scalePrefixes.push(probes[i]);
2495
+ }
2496
+ }
2497
+ let scaleStep = 0;
2498
+ if (scalePrefixes.length > 0) {
2499
+ const steps = new Set();
2500
+ const scaleSet = new Set(scalePrefixes);
2501
+ for (const cls of validClasses) {
2502
+ const dash = cls.lastIndexOf('-');
2503
+ if (dash <= 0) continue;
2504
+ if (!scaleSet.has(cls.slice(0, dash))) continue;
2505
+ const suffix = cls.slice(dash + 1);
2506
+ if (!/^\\d*\\.?\\d+$/.test(suffix)) continue;
2507
+ steps.add(parseFloat(suffix));
2508
+ }
2509
+ const sorted = [...steps].sort((a, b) => a - b);
2510
+ for (let i = 1; i < sorted.length; i++) {
2511
+ const gap = Math.round((sorted[i] - sorted[i - 1]) * 1000) / 1000;
2512
+ if (gap > 0 && (scaleStep === 0 || gap < scaleStep)) scaleStep = gap;
2513
+ }
2514
+ }
2515
+ const scale = scaleUnit && scalePrefixes.length > 0
2516
+ ? { unit: scaleUnit, step: scaleStep || 1, prefixes: scalePrefixes.sort() }
2517
+ : undefined;
2518
+
2519
+ const json = JSON.stringify({ validClasses, canonical, deprecated, order, cssDeclarations, variantOrder, variantFacts, componentClasses, arbitraryEquivalents, themeRefs, definedVars, tokenValues, scale, prefix });
2334
2520
  // Atomic write: write to a unique temp path then rename, so a peer isolate
2335
2521
  // busy-waiting on the cache file never observes a half-written JSON.
2336
2522
  writeFileSync(WD_TMP_PATH, json);
@@ -3333,45 +3519,49 @@ function answersFor(cache) {
3333
3519
  * Ask the design system about every class there is no answer for yet, intern the
3334
3520
  * declarations it returns, and record which classes produce no CSS at all.
3335
3521
  *
3336
- * Returns false when the service is unavailable. Callers treat that as "no
3337
- * information" rather than as an answer, so a broken worker degrades to the
3338
- * behaviour that predates it instead of to wrong diagnostics. Real failures still
3339
- * surface through the sticky error the worker records.
3522
+ * **Throws `SortServiceError` when the service is unavailable**, like the sort and
3523
+ * canonicalize services do. It used to swallow the failure and report "no
3524
+ * information", which was defensible when `no-conflicting-classes` was the only
3525
+ * caller — no declarations means no comparison, so the rule just went quiet. It
3526
+ * stopped being defensible once `no-unknown-classes` started asking about
3527
+ * VALIDITY: there, silence sends the rule back to the tolerant heuristic, so a
3528
+ * dead worker quietly reinstates the very false negatives the service exists to
3529
+ * remove, with nothing anywhere to say so.
3530
+ *
3531
+ * The caller decides what to do, and the two postures already exist in the
3532
+ * plugin: a DS-dependent rule surfaces it through `safeGetDS` as
3533
+ * `designSystemUnavailable` (what `enforce-canonical` does with the canonicalize
3534
+ * worker), a DS-OPTIONAL rule catches it and degrades.
3340
3535
  */
3341
3536
  function ask(cssPath, cache, classes) {
3342
3537
  const known = answersFor(cache);
3343
3538
  const pending = [...new Set(classes.filter((cls) => !known.has(cls)))];
3344
- if (pending.length === 0) return true;
3345
- let response;
3346
- try {
3347
- response = declWorker.callSync(cssPath, { classes: pending });
3348
- } catch (error) {
3349
- if (error instanceof SortServiceError) return false;
3350
- throw error;
3351
- }
3539
+ if (pending.length === 0) return;
3540
+ const response = declWorker.callSync(cssPath, { classes: pending });
3352
3541
  const invalid = new Set(response.invalid);
3353
3542
  for (const cls of pending) known.set(cls, !invalid.has(cls));
3354
3543
  for (const [cls, raws] of Object.entries(response.decls)) cache.internDeclarations(cls, raws, response.values);
3355
- return true;
3356
3544
  }
3357
3545
  /**
3358
3546
  * Resolve and intern declarations for `classes` that the precompute doesn't know.
3359
3547
  * They land in the cache, so the caller reads them back through
3360
3548
  * `cache.getCssDeclarations` like any other class.
3549
+ *
3550
+ * Throws `SortServiceError` if the service is unavailable — see `ask`.
3361
3551
  */
3362
3552
  function resolveDeclarationsSync(cssPath, cache, classes) {
3363
3553
  ask(cssPath, cache, classes);
3364
3554
  }
3365
3555
  /**
3366
- * Which of these classes produce CSS. `null` when the service is unavailable, so
3367
- * the caller can fall back instead of reading silence as an answer.
3556
+ * Which of these classes produce CSS.
3368
3557
  *
3369
3558
  * This is what makes validity exact for the classes the precompute cannot
3370
3559
  * enumerate: `w-45` and `bg-red-5000` are shaped identically, and only Tailwind
3371
- * knows that it compiles the first and not the second.
3560
+ * knows that it compiles the first and not the second. Throws
3561
+ * `SortServiceError` if the service is unavailable — see `ask`.
3372
3562
  */
3373
3563
  function validateClassesSync(cssPath, cache, classes) {
3374
- if (!ask(cssPath, cache, classes)) return null;
3564
+ ask(cssPath, cache, classes);
3375
3565
  return answersFor(cache);
3376
3566
  }
3377
3567
  //#endregion
@@ -3451,8 +3641,7 @@ const noUnknownClasses = defineRule({
3451
3641
  const memo = chainAnswers.get(key);
3452
3642
  if (memo !== void 0) return memo;
3453
3643
  const probe = `${chain}${PROBE_UTILITY}`;
3454
- const answers = validateClassesSync(entryPoint, cache, [probe]);
3455
- const verdict = answers ? answers.get(probe) ?? null : null;
3644
+ const verdict = validateClassesSync(entryPoint, cache, [probe]).get(probe) ?? null;
3456
3645
  chainAnswers.set(key, verdict);
3457
3646
  return verdict;
3458
3647
  }
@@ -3480,6 +3669,14 @@ const noUnknownClasses = defineRule({
3480
3669
  const ds = safeGetDS(getDS, context, locations[0].node);
3481
3670
  if (!ds) return;
3482
3671
  const { cache, entryPoint } = ds;
3672
+ try {
3673
+ checkLocations(locations, cache, entryPoint);
3674
+ } catch (error) {
3675
+ if (reportFatalDsError(context, error, locations[0].node)) return;
3676
+ throw error;
3677
+ }
3678
+ }
3679
+ function checkLocations(locations, cache, entryPoint) {
3483
3680
  for (const loc of locations) {
3484
3681
  const split = splitClassesWithSeparators(loc.value);
3485
3682
  const classes = split.classes;
@@ -3488,6 +3685,7 @@ const noUnknownClasses = defineRule({
3488
3685
  if (shouldIgnore(cls)) continue;
3489
3686
  const bare = strippedUtility(cls).bare;
3490
3687
  if (cache.isKnownClass(bare)) continue;
3688
+ if (cache.isMarkerClass(bare)) continue;
3491
3689
  if (!toVerify) toVerify = [];
3492
3690
  toVerify.push(bare);
3493
3691
  }
@@ -3507,6 +3705,7 @@ const noUnknownClasses = defineRule({
3507
3705
  }, split);
3508
3706
  continue;
3509
3707
  }
3708
+ if (cache.isMarkerClass(bare) && (!cache.prefix || variant.startsWith(`${cache.prefix}:`))) continue;
3510
3709
  const compiles = cache.isKnownClass(bare) ? true : verified?.get(bare);
3511
3710
  if (validity === "unknown" || compiles === false) {
3512
3711
  const suggestionBare = findBestSuggestion(bare, cache.validClasses);
@@ -3950,7 +4149,12 @@ const noConflictingClasses = defineRule({
3950
4149
  for (const [, variantClasses] of byVariant) {
3951
4150
  if (variantClasses.length < 2) continue;
3952
4151
  const unknown = variantClasses.map((cls) => splitImportant(extractUtility(cls)).bare).filter((bare) => cache.getCssDeclarations(bare).length === 0 && isUserValued(bare));
3953
- if (unknown.length > 0) resolveDeclarationsSync(ds.entryPoint, cache, unknown);
4152
+ if (unknown.length > 0) {
4153
+ if (!safeGetDS(() => {
4154
+ resolveDeclarationsSync(ds.entryPoint, cache, unknown);
4155
+ return true;
4156
+ }, context, loc.node)) return;
4157
+ }
3954
4158
  const facts = variantClasses.map((cls) => {
3955
4159
  const utility = extractUtility(cls);
3956
4160
  const bare = splitImportant(utility).bare;
@@ -5690,7 +5894,12 @@ const noDarkWithoutLight = defineRule({
5690
5894
  if (!unresolved) unresolved = [];
5691
5895
  unresolved.push(bare);
5692
5896
  }
5693
- if (unresolved) resolveDeclarationsSync(ds.entryPoint, cache, unresolved);
5897
+ if (unresolved) try {
5898
+ resolveDeclarationsSync(ds.entryPoint, cache, unresolved);
5899
+ } catch (error) {
5900
+ if (!isFatalError(error)) throw error;
5901
+ debugLog(`declaration service unavailable, grouping by prefix only: ${String(error)}`);
5902
+ }
5694
5903
  }
5695
5904
  const basePrefixes = /* @__PURE__ */ new Set();
5696
5905
  const baseProperties = /* @__PURE__ */ new Set();
@@ -6324,6 +6533,106 @@ function detectRawVariable(utility) {
6324
6533
  };
6325
6534
  return null;
6326
6535
  }
6536
+ const preferThemeTokens = defineRule({
6537
+ meta: {
6538
+ type: "suggestion",
6539
+ docs: { description: "Prefer named theme-token utilities over raw CSS variable references when a matching utility exists" },
6540
+ fixable: "code",
6541
+ schema: [{
6542
+ type: "object",
6543
+ properties: { entryPoint: { type: "string" } },
6544
+ additionalProperties: false
6545
+ }],
6546
+ hasSuggestions: true,
6547
+ defaultOptions: [{}],
6548
+ messages: {
6549
+ preferNamed: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named theme token.",
6550
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
6551
+ ...DS_UNAVAILABLE_MESSAGE
6552
+ }
6553
+ },
6554
+ createOnce(context) {
6555
+ const getDS = createLazyLoader(context);
6556
+ function check(locations) {
6557
+ if (locations.length === 0) return;
6558
+ const ds = safeGetDS(getDS, context, locations[0].node);
6559
+ if (!ds) return;
6560
+ const { cache } = ds;
6561
+ for (const loc of locations) {
6562
+ const split = splitClassesWithSeparators(loc.value);
6563
+ const offending = split.classes.flatMap((cls) => {
6564
+ const { utility, variant } = splitUtilityAndVariant(cls);
6565
+ const { bare: bareUtility, position } = splitImportant(utility);
6566
+ const match = detectRawVariable(bareUtility);
6567
+ if (!match) return [];
6568
+ const candidate = `${match.prefix}-${match.varName}${match.modifier}`;
6569
+ if (!cache.isValid(candidate)) return [];
6570
+ const target = `--${match.varName}`;
6571
+ const baseCandidate = `${match.prefix}-${match.varName}`;
6572
+ if (!cache.getCssDeclarations(baseCandidate).some((decl) => [...decl.readsVars, ...decl.readsFallbackVars].some((read) => cache.themeVarResolvesTo(read, target))) && cache.definesVar(target)) return [];
6573
+ const namedEquivalent = cache.getNamedEquivalent(bareUtility);
6574
+ if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) return [];
6575
+ return [{
6576
+ cls,
6577
+ replacement: variant + reattachImportant(candidate, position)
6578
+ }];
6579
+ });
6580
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "preferNamed" });
6581
+ }
6582
+ }
6583
+ return createExtractorVisitors(context, check);
6584
+ }
6585
+ });
6586
+ //#endregion
6587
+ //#region src/rules/prefer-scale-token.ts
6588
+ /** A length or plain number. Anything else can't be compared arithmetically. */
6589
+ const LENGTH_RE = /^(-?\d*\.?\d+)(rem|px|em)?$/;
6590
+ /**
6591
+ * Parse a CSS length. `em` is treated as `rem`, which is what it is at the root
6592
+ * and the only interpretation available without a layout.
6593
+ */
6594
+ function measure(value, rootFontSize) {
6595
+ const match = LENGTH_RE.exec(value.trim());
6596
+ if (!match) return null;
6597
+ const n = Number.parseFloat(match[1]);
6598
+ if (!Number.isFinite(n)) return null;
6599
+ switch (match[2]) {
6600
+ case "rem":
6601
+ case "em": return {
6602
+ px: n * rootFontSize,
6603
+ unitless: false
6604
+ };
6605
+ case "px": return {
6606
+ px: n,
6607
+ unitless: false
6608
+ };
6609
+ case void 0: return {
6610
+ px: n,
6611
+ unitless: true
6612
+ };
6613
+ default: return null;
6614
+ }
6615
+ }
6616
+ /**
6617
+ * Same value, allowing for float noise (`0.875rem` × 16 = 13.999999999999998).
6618
+ * A unitless number and a length are never the same value, whatever the digits.
6619
+ */
6620
+ function sameMeasure(a, b) {
6621
+ return a.unitless === b.unitless && Math.abs(a.px - b.px) < 1e-4;
6622
+ }
6623
+ /**
6624
+ * Is `n` a whole number of `step`s? `10 / 0.5` is exact in binary, `0.3 / 0.1`
6625
+ * is not, so the remainder is compared with a tolerance rather than to zero.
6626
+ */
6627
+ function isOnStep(n, step) {
6628
+ if (step <= 0) return false;
6629
+ const steps = n / step;
6630
+ return Math.abs(steps - Math.round(steps)) < 1e-4;
6631
+ }
6632
+ /** Trailing zeros make `p-2.50`, which is not what Tailwind calls the class. */
6633
+ function formatStep(n) {
6634
+ return String(Number.parseFloat(n.toFixed(4)));
6635
+ }
6327
6636
  //#endregion
6328
6637
  //#region src/index.ts
6329
6638
  const plugin = definePlugin({
@@ -6351,26 +6660,77 @@ const plugin = definePlugin({
6351
6660
  "consistent-variant-order": consistentVariantOrder,
6352
6661
  "enforce-consistent-line-wrapping": enforceConsistentLineWrapping,
6353
6662
  "no-unnecessary-arbitrary-value": noUnnecessaryArbitraryValue,
6354
- "prefer-theme-tokens": defineRule({
6663
+ "prefer-theme-tokens": preferThemeTokens,
6664
+ "prefer-scale-token": defineRule({
6355
6665
  meta: {
6356
6666
  type: "suggestion",
6357
- docs: { description: "Prefer named theme-token utilities over raw CSS variable references when a matching utility exists" },
6358
- fixable: "code",
6667
+ docs: { description: "Prefer the scale step or theme token a hardcoded value is numerically equal to" },
6668
+ hasSuggestions: true,
6359
6669
  schema: [{
6360
6670
  type: "object",
6361
- properties: { entryPoint: { type: "string" } },
6671
+ properties: {
6672
+ entryPoint: { type: "string" },
6673
+ step: { type: "number" },
6674
+ allow: {
6675
+ type: "array",
6676
+ items: { type: "string" }
6677
+ }
6678
+ },
6362
6679
  additionalProperties: false
6363
6680
  }],
6364
- hasSuggestions: true,
6365
6681
  defaultOptions: [{}],
6366
6682
  messages: {
6367
- preferNamed: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named theme token.",
6683
+ preferToken: "\"{{className}}\" is the same value as \"{{replacement}}\". Use the token — but check it first: the token resolves through a CSS variable, so the two are equal in this theme, not by construction.",
6368
6684
  suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
6369
6685
  ...DS_UNAVAILABLE_MESSAGE
6370
6686
  }
6371
6687
  },
6372
6688
  createOnce(context) {
6373
6689
  const getDS = createLazyLoader(context);
6690
+ const getOptions = createLazyOptions(context, (o) => ({
6691
+ step: typeof o?.step === "number" ? o.step : null,
6692
+ allow: o?.allow ?? []
6693
+ }));
6694
+ let _rem = null;
6695
+ function rootFontSize() {
6696
+ if (_rem === null) _rem = rootFontSizeFromSettings(safeSettings(context));
6697
+ return _rem;
6698
+ }
6699
+ /**
6700
+ * The class this literal could have been written as, or null.
6701
+ *
6702
+ * Two families, in order of preference: a named theme token whose value
6703
+ * matches (`rounded-[0.5rem]` → `rounded-lg`), then a step of the spacing
6704
+ * scale (`p-[10px]` → `p-2.5`). Both come from data the precompute derived
6705
+ * from the design system, so neither is a name table.
6706
+ */
6707
+ function equivalentOf(cache, bare) {
6708
+ const { step: stepOverride, allow } = getOptions();
6709
+ if (allow.some((prefix) => bare.startsWith(prefix))) return null;
6710
+ if (cache.getNamedEquivalent(bare)) return null;
6711
+ const value = getArbitraryValue(bare);
6712
+ if (value === null) return null;
6713
+ const written = measure(value, rootFontSize());
6714
+ if (written === null) return null;
6715
+ const open = bare.indexOf("[");
6716
+ if (open <= 0 || bare[open - 1] !== "-") return null;
6717
+ const prefix = bare.slice(0, open - 1);
6718
+ if (!prefix) return null;
6719
+ for (const [literal, className] of cache.tokenValuesFor(prefix)) {
6720
+ const token = measure(literal, rootFontSize());
6721
+ if (token !== null && sameMeasure(written, token)) return className;
6722
+ }
6723
+ if (!cache.readsScale(prefix)) return null;
6724
+ const scale = cache.scale;
6725
+ if (!scale) return null;
6726
+ const unit = measure(scale.unit, rootFontSize());
6727
+ if (unit === null || unit.px <= 0 || unit.unitless !== written.unitless) return null;
6728
+ const steps = written.px / unit.px;
6729
+ if (steps < 0) return null;
6730
+ if (!isOnStep(steps, stepOverride ?? scale.step)) return null;
6731
+ const candidate = `${prefix}-${formatStep(steps)}`;
6732
+ return cache.isValid(candidate) ? candidate : null;
6733
+ }
6374
6734
  function check(locations) {
6375
6735
  if (locations.length === 0) return;
6376
6736
  const ds = safeGetDS(getDS, context, locations[0].node);
@@ -6378,24 +6738,33 @@ const plugin = definePlugin({
6378
6738
  const { cache } = ds;
6379
6739
  for (const loc of locations) {
6380
6740
  const split = splitClassesWithSeparators(loc.value);
6381
- const offending = split.classes.flatMap((cls) => {
6741
+ for (const cls of split.classes) {
6742
+ if (!utilityHasDynamicValue(cls)) continue;
6382
6743
  const { utility, variant } = splitUtilityAndVariant(cls);
6383
- const { bare: bareUtility, position } = splitImportant(utility);
6384
- const match = detectRawVariable(bareUtility);
6385
- if (!match) return [];
6386
- const candidate = `${match.prefix}-${match.varName}${match.modifier}`;
6387
- if (!cache.isValid(candidate)) return [];
6388
- const target = `--${match.varName}`;
6389
- const baseCandidate = `${match.prefix}-${match.varName}`;
6390
- if (!cache.getCssDeclarations(baseCandidate).some((decl) => [...decl.readsVars, ...decl.readsFallbackVars].some((read) => cache.themeVarResolvesTo(read, target))) && cache.definesVar(target)) return [];
6391
- const namedEquivalent = cache.getNamedEquivalent(bareUtility);
6392
- if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) return [];
6393
- return [{
6394
- cls,
6395
- replacement: variant + reattachImportant(candidate, position)
6396
- }];
6397
- });
6398
- reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "preferNamed" });
6744
+ const { bare, position } = splitImportant(utility);
6745
+ const equivalent = equivalentOf(cache, bare);
6746
+ if (!equivalent) continue;
6747
+ const replacement = variant + reattachImportant(equivalent, position);
6748
+ const fixedValue = rebuildClassString(split, split.classes.map((c) => c === cls ? replacement : c));
6749
+ context.report({
6750
+ node: loc.node,
6751
+ messageId: "preferToken",
6752
+ data: {
6753
+ className: cls,
6754
+ replacement
6755
+ },
6756
+ suggest: [{
6757
+ messageId: "suggestReplace",
6758
+ data: {
6759
+ className: cls,
6760
+ replacement
6761
+ },
6762
+ fix(fixer) {
6763
+ return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
6764
+ }
6765
+ }]
6766
+ });
6767
+ }
6399
6768
  }
6400
6769
  }
6401
6770
  return createExtractorVisitors(context, check);