oxlint-tailwindcss 1.4.0 → 1.6.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 (3) hide show
  1. package/dist/index.cjs +1565 -671
  2. package/dist/index.mjs +1565 -671
  3. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -735,6 +735,18 @@ function utilityHasDynamicValue(cls) {
735
735
  return utility.includes("[") || utility.includes("(");
736
736
  }
737
737
  /**
738
+ * A utility the precompute cannot have enumerated, because the VALUE comes from
739
+ * the user rather than from the design system's class list: arbitrary brackets,
740
+ * the `(--var)` shorthand, a `/` modifier, or an off-scale number.
741
+ *
742
+ * Asking the design system about exactly these is what closes the "looks like
743
+ * coverage" false negatives — `p-4 p-[5px]` used to be accepted silently while
744
+ * `p-4 p-6` reported. Takes the bare utility (no variants, no `!`).
745
+ */
746
+ function isUserValued(utility) {
747
+ return utility.includes("[") || utility.includes("(") || utility.includes("/") || /-\d/.test(utility);
748
+ }
749
+ /**
738
750
  * Gets the arbitrary value from a class, or null if none.
739
751
  * e.g. "w-[200px]" → "200px"
740
752
  * "bg-[#ff0000]" → "#ff0000"
@@ -951,8 +963,10 @@ function roundRemValue(className) {
951
963
  //#endregion
952
964
  //#region src/design-system/cache.ts
953
965
  const EMPTY_DECLARATIONS = [];
966
+ const EMPTY_TOKEN_VALUES = [];
954
967
  var DesignSystemCache = class DesignSystemCache {
955
968
  canonicalMap = /* @__PURE__ */ new Map();
969
+ deprecatedMap = /* @__PURE__ */ new Map();
956
970
  validitySet = /* @__PURE__ */ new Set();
957
971
  orderMap = /* @__PURE__ */ new Map();
958
972
  declIndex = null;
@@ -961,6 +975,7 @@ var DesignSystemCache = class DesignSystemCache {
961
975
  propsMemo = /* @__PURE__ */ new Map();
962
976
  partialSet = /* @__PURE__ */ new Set();
963
977
  valueIdByText = null;
978
+ nextValueId = 0;
964
979
  variantOrderMap = /* @__PURE__ */ new Map();
965
980
  variantFactsMap = /* @__PURE__ */ new Map();
966
981
  arbitraryEquivMap = /* @__PURE__ */ new Map();
@@ -971,11 +986,14 @@ var DesignSystemCache = class DesignSystemCache {
971
986
  componentSet = /* @__PURE__ */ new Set();
972
987
  themeRefs = /* @__PURE__ */ new Map();
973
988
  definedVarSet = /* @__PURE__ */ new Set();
989
+ tokenValuesMap = /* @__PURE__ */ new Map();
990
+ scaleFacts = null;
974
991
  static fromPrecomputed(data) {
975
992
  const cache = new DesignSystemCache();
976
993
  cache._validClasses = data.validClasses;
977
994
  for (const cls of data.validClasses) cache.validitySet.add(cls);
978
995
  for (const [from, to] of Object.entries(data.canonical)) cache.canonicalMap.set(from, roundRemValue(to));
996
+ if (data.deprecated) for (const [from, to] of Object.entries(data.deprecated)) cache.deprecatedMap.set(from, to);
979
997
  for (const [cls, val] of Object.entries(data.order)) {
980
998
  const order = BigInt(val);
981
999
  cache.orderMap.set(cls, order);
@@ -997,6 +1015,12 @@ var DesignSystemCache = class DesignSystemCache {
997
1015
  }
998
1016
  for (const name of data.definedVars ?? []) cache.definedVarSet.add(name);
999
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
+ };
1000
1024
  cache._prefix = data.prefix ?? "";
1001
1025
  if (data.arbitraryEquivalents) for (const [arb, named] of Object.entries(data.arbitraryEquivalents)) cache.arbitraryEquivMap.set(arb, named);
1002
1026
  return cache;
@@ -1030,6 +1054,24 @@ var DesignSystemCache = class DesignSystemCache {
1030
1054
  return className;
1031
1055
  }
1032
1056
  /**
1057
+ * The v4 name of a class Tailwind renamed, or `null` if it isn't a renamed
1058
+ * spelling. Takes the BARE utility (no variants, no `!`) — the caller has
1059
+ * already split those off to rebuild the replacement around them.
1060
+ *
1061
+ * Derived by the precompute from what `canonicalizeCandidates` reports for the
1062
+ * v3 spellings, rather than from a map maintained by hand. Two rules read it:
1063
+ * `no-deprecated-classes`, which owns the diagnostic, and `enforce-canonical`,
1064
+ * which stays quiet about these so one class doesn't produce two identical
1065
+ * rewrites.
1066
+ */
1067
+ deprecatedReplacement(bareUtility) {
1068
+ return this.deprecatedMap.get(this.stripProjectPrefix(bareUtility)) ?? null;
1069
+ }
1070
+ /** Whether the precompute produced a deprecation map at all (older artifacts didn't). */
1071
+ get hasDeprecatedMap() {
1072
+ return this.deprecatedMap.size > 0;
1073
+ }
1074
+ /**
1033
1075
  * Resolve a variant name to its priority in the CSS output order.
1034
1076
  * Named variants use the precomputed map. Arbitrary variants use pattern-based heuristics
1035
1077
  * to approximate their position relative to named variants.
@@ -1088,6 +1130,44 @@ var DesignSystemCache = class DesignSystemCache {
1088
1130
  }
1089
1131
  return this._knownPrefixes;
1090
1132
  }
1133
+ /**
1134
+ * Is this class name in the precomputed set VERBATIM?
1135
+ *
1136
+ * `isValid` is deliberately tolerant: it accepts anything shaped like a dynamic
1137
+ * value (`w-45`, `bg-red-5000`, `bg-red-500/foo`) because there used to be no
1138
+ * way to ask the design system at lint time. That tolerance is what let
1139
+ * `no-unknown-classes` accept classes Tailwind compiles to nothing. This is the
1140
+ * exact answer, so a rule can tell "known to produce CSS" from "shaped like it
1141
+ * might" and ask the design system about the difference.
1142
+ */
1143
+ isKnownClass(className) {
1144
+ return this.validitySet.has(this.stripProjectPrefix(className));
1145
+ }
1146
+ /** Variant names the design system reports, for suggesting a typo's neighbour. */
1147
+ variantNames() {
1148
+ return [...this.variantOrderMap.keys()];
1149
+ }
1150
+ /**
1151
+ * The numeric theme tokens this utility prefix can be written with, as
1152
+ * `[literal value, class]`. Empty when the prefix has none.
1153
+ */
1154
+ tokenValuesFor(prefix) {
1155
+ return this.tokenValuesMap.get(this.stripProjectPrefix(prefix)) ?? EMPTY_TOKEN_VALUES;
1156
+ }
1157
+ /**
1158
+ * The spacing scale as the design system describes it: the resolved value of
1159
+ * `--spacing`, the granularity Tailwind's own enumerated steps use, and whether
1160
+ * a given prefix reads it. `null` when the theme has no `--spacing`.
1161
+ */
1162
+ get scale() {
1163
+ return this.scaleFacts ? {
1164
+ unit: this.scaleFacts.unit,
1165
+ step: this.scaleFacts.step
1166
+ } : null;
1167
+ }
1168
+ readsScale(prefix) {
1169
+ return this.scaleFacts?.prefixes.has(this.stripProjectPrefix(prefix)) ?? false;
1170
+ }
1091
1171
  isValid(className) {
1092
1172
  if (this.validitySet.has(className)) return true;
1093
1173
  const utility = extractUtility(className);
@@ -1232,7 +1312,10 @@ var DesignSystemCache = class DesignSystemCache {
1232
1312
  internDeclarations(className, raws, valueFacts) {
1233
1313
  const index = this.declIndex;
1234
1314
  if (!index) return EMPTY_DECLARATIONS;
1235
- if (!this.valueIdByText) this.valueIdByText = new Map(index.values.map((value, id) => [value, id]));
1315
+ if (!this.valueIdByText) {
1316
+ this.valueIdByText = new Map(index.values.map((value, id) => [value, id]));
1317
+ this.nextValueId = index.values.length;
1318
+ }
1236
1319
  const decls = [];
1237
1320
  let hasElement = false;
1238
1321
  let hasDescendant = false;
@@ -1240,8 +1323,7 @@ var DesignSystemCache = class DesignSystemCache {
1240
1323
  for (const [scopeToken, prop, value] of raws) {
1241
1324
  let valueId = this.valueIdByText.get(value);
1242
1325
  if (valueId === void 0) {
1243
- valueId = index.values.length;
1244
- index.values.push(value);
1326
+ valueId = this.nextValueId++;
1245
1327
  this.valueIdByText.set(value, valueId);
1246
1328
  }
1247
1329
  const facts = valueFacts[value];
@@ -1425,6 +1507,29 @@ function safeGetDS(getDS, context, node) {
1425
1507
  throw err;
1426
1508
  }
1427
1509
  }
1510
+ /**
1511
+ * `safeGetDS`'s quiet sibling, for the DS-OPTIONAL rules.
1512
+ *
1513
+ * A handful of rules work without a design system — their static fallback is
1514
+ * itself deterministic (`consistent-variant-order`'s variant table,
1515
+ * `no-dark-without-light`'s prefix grouping) — and an entry point only makes
1516
+ * them more accurate. Those rules must never emit `designSystemUnavailable`:
1517
+ * they were usable with no configuration before the DS lookup existed and have
1518
+ * to stay that way, or adding the lookup would break every project that runs
1519
+ * them without a CSS entry point.
1520
+ *
1521
+ * So: returns the load result, or `null` when the design system is unavailable
1522
+ * for a reason the plugin knows about. Non-fatal errors still propagate, since
1523
+ * those are bugs rather than missing configuration.
1524
+ */
1525
+ function softGetDS(getDS) {
1526
+ try {
1527
+ return getDS();
1528
+ } catch (err) {
1529
+ if (isFatalError(err)) return null;
1530
+ throw err;
1531
+ }
1532
+ }
1428
1533
  //#endregion
1429
1534
  //#region src/design-system/tailwind-node.ts
1430
1535
  /**
@@ -1739,7 +1844,12 @@ function resolveImport(specifier, baseDir) {
1739
1844
  return null;
1740
1845
  }
1741
1846
 
1742
- function extractComponentClasses(cssPath, baseDir) {
1847
+ // The entry CSS plus every \`@import\` that resolves, one level deep. Shared by
1848
+ // the component-class scan and the \`definedVars\` scan: a custom property declared
1849
+ // in an imported file is as real to the browser as one in the entry, and treating
1850
+ // it as undefined makes prefer-theme-tokens propose a token that can change the
1851
+ // design (the #78 hazard, in miniature).
1852
+ function collectCssSources(cssPath, baseDir) {
1743
1853
  let css;
1744
1854
  try { css = readFileSync(cssPath, 'utf-8'); } catch { return []; }
1745
1855
  const files = [css];
@@ -1751,6 +1861,11 @@ function extractComponentClasses(cssPath, baseDir) {
1751
1861
  try { files.push(readFileSync(resolved, 'utf-8')); } catch {}
1752
1862
  }
1753
1863
  }
1864
+ return files;
1865
+ }
1866
+
1867
+ function extractComponentClasses(cssPath, baseDir) {
1868
+ const files = collectCssSources(cssPath, baseDir);
1754
1869
  const result = [];
1755
1870
  for (const content of files) {
1756
1871
  // Scan both @layer components AND @layer utilities
@@ -1934,11 +2049,17 @@ async function main() {
1934
2049
  // their v4 equivalent, so we feed them in explicitly. Without this pass,
1935
2050
  // classes like \`break-words\` would be invisible to enforce-canonical
1936
2051
  // (issue #16).
1937
- // - Fixed renames mirror the internal v3->v4 map in tailwindcss/canonicalize.
1938
- // - Pattern renames (start-* -> inset-s-*, end-* -> inset-e-*) are derived
1939
- // from the inset-{s,e}-* utilities present in validClasses so we cover
1940
- // every numeric/named value the design system exposes.
1941
- const legacyCandidates = [
2052
+ //
2053
+ // Two kinds, and the difference is what \`deprecated\` records:
2054
+ // - RENAMES: a v3 spelling of a utility v4 calls something else. Mirrors the
2055
+ // internal v3->v4 map in tailwindcss/canonicalize. These ARE deprecated, and
2056
+ // no-deprecated-classes owns them.
2057
+ // - Pattern renames (start-* -> inset-s-*, end-* -> inset-e-*), derived from
2058
+ // the inset-{s,e}-* utilities in validClasses so every numeric/named value is
2059
+ // covered. These are NOT deprecated: \`start-2\` is current Tailwind (it is
2060
+ // what the docs use), it just isn't the canonical spelling. Calling it
2061
+ // deprecated would be a lie, so only enforce-canonical speaks about it.
2062
+ const v3Renames = [
1942
2063
  'order-none',
1943
2064
  'break-words',
1944
2065
  'overflow-ellipsis',
@@ -1953,12 +2074,15 @@ async function main() {
1953
2074
  'bg-left-top', 'bg-right-top', 'bg-left-bottom', 'bg-right-bottom',
1954
2075
  'object-left-top', 'object-right-top', 'object-left-bottom', 'object-right-bottom',
1955
2076
  ];
2077
+ const renameSet = new Set(v3Renames);
2078
+ const legacyCandidates = [...v3Renames];
1956
2079
  for (const cls of validClasses) {
1957
2080
  if (cls.startsWith('inset-s-')) legacyCandidates.push('start-' + cls.slice(8));
1958
2081
  else if (cls.startsWith('-inset-s-')) legacyCandidates.push('-start-' + cls.slice(9));
1959
2082
  else if (cls.startsWith('inset-e-')) legacyCandidates.push('end-' + cls.slice(8));
1960
2083
  else if (cls.startsWith('-inset-e-')) legacyCandidates.push('-end-' + cls.slice(9));
1961
2084
  }
2085
+ const deprecated = {};
1962
2086
  const legacyToProcess = legacyCandidates.filter(cls => !validSet.has(cls));
1963
2087
  if (legacyToProcess.length > 0) {
1964
2088
  const legacyCssResults = ds.candidatesToCss(legacyToProcess.map(pfx));
@@ -1969,6 +2093,10 @@ async function main() {
1969
2093
  const canon = result[0] ? unpfx(result[0]) : null;
1970
2094
  if (canon && canon !== cls) {
1971
2095
  canonical[cls] = canon;
2096
+ // Only a v3 rename that this Tailwind still compiles AND still renames.
2097
+ // A release that drops either of those drops the entry, so the rule can
2098
+ // never suggest a replacement for a class that no longer exists.
2099
+ if (renameSet.has(cls)) deprecated[cls] = canon;
1972
2100
  }
1973
2101
  // Mark as valid so no-unknown-classes doesn't flag legacy spellings.
1974
2102
  validClasses.push(cls);
@@ -2224,20 +2352,21 @@ async function main() {
2224
2352
  }
2225
2353
  }
2226
2354
 
2227
- // Theme variables that dereference to another custom property. Only the
2228
- // referencing ones are stored (~a handful), and the reference list reuses the
2229
- // same balanced scanner the declaration values go through.
2230
- // Custom properties the project defines. The entry file covers the standard
2231
- // ':root { --x: ... }' pattern; definitions inside @imported files are not
2232
- // scanned, so an unseen definition reads as "undefined" — which only ever makes
2233
- // prefer-theme-tokens more willing to suggest, never less accurate about a
2234
- // definition it can see.
2235
- const definedVars = [...new Set(css.match(/--[\\w-]+(?=\\s*:)/g) || [])];
2355
+ // Custom properties the project defines, across the entry AND its resolved
2356
+ // @imports — splitting the theme across files is the normal shadcn/ui layout,
2357
+ // and a definition we cannot see reads as "undefined", which is what makes
2358
+ // prefer-theme-tokens propose a token that means something else. One level
2359
+ // deep, same as the component-class scan it shares \`collectCssSources\` with.
2360
+ const definedVars = [...new Set(
2361
+ collectCssSources(cssPath, base).flatMap(src => src.match(/--[\\w-]+(?=\\s*:)/g) || [])
2362
+ )];
2236
2363
 
2237
2364
  const themeRefs = {};
2365
+ const themeValues = new Map();
2238
2366
  if (ds.theme && typeof ds.theme.entries === 'function') {
2239
2367
  for (const [name, entry] of ds.theme.entries()) {
2240
2368
  const value = entry && typeof entry.value === 'string' ? entry.value : '';
2369
+ themeValues.set(name, value);
2241
2370
  if (!value.includes('var(')) continue;
2242
2371
  const reads = scanVarReads(value);
2243
2372
  const all = [...new Set([...reads[0], ...reads[1]])];
@@ -2245,7 +2374,77 @@ async function main() {
2245
2374
  }
2246
2375
  }
2247
2376
 
2248
- const json = JSON.stringify({ validClasses, canonical, order, cssDeclarations, variantOrder, variantFacts, componentClasses, arbitraryEquivalents, themeRefs, definedVars, prefix });
2377
+ // ── What a literal value could have been written as (for prefer-scale-token) ──
2378
+ //
2379
+ // Two families, both derived. Neither is a name table: the emitted CSS says
2380
+ // which variable a class reads and the theme says what that variable is worth.
2381
+
2382
+ // A single declaration whose whole value is one \`var(--x)\` that the theme
2383
+ // resolves to a NUMBER. Numeric because that is the only thing the rule can
2384
+ // compare — a colour token could never match a literal the user typed — and
2385
+ // SINGLE because a class that declares more than the original is not an
2386
+ // equivalent: \`text-sm\` sets \`line-height\` too, so \`text-[14px]\` is not it.
2387
+ const NUMERIC_LITERAL = /^-?\\d*\\.?\\d+(rem|px|em|%|s|ms|deg)?$/;
2388
+ const tokenValues = {};
2389
+ for (const cls of validClasses) {
2390
+ if (cls.includes('[') || cls.includes('/')) continue;
2391
+ const css = declCss[cls];
2392
+ if (!css) continue;
2393
+ const open = css.indexOf('{');
2394
+ const close = css.indexOf('}');
2395
+ if (open < 0 || close < 0) continue;
2396
+ const body = css.slice(open + 1, close).replace(/\\s+/g, ' ').replace(/;\\s*$/, '').trim();
2397
+ const m = /^([a-z-]+):\\s*var\\((--[\\w-]+)\\)$/.exec(body);
2398
+ if (!m) continue;
2399
+ const value = themeValues.get(m[2]);
2400
+ if (!value || !NUMERIC_LITERAL.test(value)) continue;
2401
+ const dash = cls.lastIndexOf('-');
2402
+ if (dash <= 0) continue;
2403
+ const prefix = unpfx(cls).slice(0, unpfx(cls).lastIndexOf('-'));
2404
+ if (!prefix) continue;
2405
+ if (!tokenValues[prefix]) tokenValues[prefix] = [];
2406
+ tokenValues[prefix].push([value, unpfx(cls)]);
2407
+ }
2408
+
2409
+ // The spacing scale: its unit, which prefixes read it, and the granularity
2410
+ // Tailwind's own enumerated steps use. Every step getClassList() lists is a
2411
+ // multiple of that granularity, so deriving it is how the rule stays inside
2412
+ // what Tailwind does instead of inventing a threshold.
2413
+ const scaleUnit = themeValues.get('--spacing') || '';
2414
+ const scalePrefixes = [];
2415
+ if (scaleUnit) {
2416
+ const probes = [...knownPrefixes];
2417
+ const probeResults = ds.candidatesToCss(probes.map(p => pfx(p + '-1')));
2418
+ for (let i = 0; i < probes.length; i++) {
2419
+ const css = probeResults[i];
2420
+ if (!css) continue;
2421
+ // \`size-1\` emits width AND height, both reading the unit — one match is enough.
2422
+ if (css.includes('var(--spacing)')) scalePrefixes.push(probes[i]);
2423
+ }
2424
+ }
2425
+ let scaleStep = 0;
2426
+ if (scalePrefixes.length > 0) {
2427
+ const steps = new Set();
2428
+ const scaleSet = new Set(scalePrefixes);
2429
+ for (const cls of validClasses) {
2430
+ const dash = cls.lastIndexOf('-');
2431
+ if (dash <= 0) continue;
2432
+ if (!scaleSet.has(cls.slice(0, dash))) continue;
2433
+ const suffix = cls.slice(dash + 1);
2434
+ if (!/^\\d*\\.?\\d+$/.test(suffix)) continue;
2435
+ steps.add(parseFloat(suffix));
2436
+ }
2437
+ const sorted = [...steps].sort((a, b) => a - b);
2438
+ for (let i = 1; i < sorted.length; i++) {
2439
+ const gap = Math.round((sorted[i] - sorted[i - 1]) * 1000) / 1000;
2440
+ if (gap > 0 && (scaleStep === 0 || gap < scaleStep)) scaleStep = gap;
2441
+ }
2442
+ }
2443
+ const scale = scaleUnit && scalePrefixes.length > 0
2444
+ ? { unit: scaleUnit, step: scaleStep || 1, prefixes: scalePrefixes.sort() }
2445
+ : undefined;
2446
+
2447
+ const json = JSON.stringify({ validClasses, canonical, deprecated, order, cssDeclarations, variantOrder, variantFacts, componentClasses, arbitraryEquivalents, themeRefs, definedVars, tokenValues, scale, prefix });
2249
2448
  // Atomic write: write to a unique temp path then rename, so a peer isolate
2250
2449
  // busy-waiting on the cache file never observes a half-written JSON.
2251
2450
  writeFileSync(WD_TMP_PATH, json);
@@ -2949,351 +3148,107 @@ function resolveEntryPointForFile(ruleOptionEntry, settingsEntry, filePath, cwd
2949
3148
  throw new MissingEntryPointError(`\`settings.tailwindcss.entryPoint\` is required${filePath ? ` (linting \`${filePath}\`)` : ""}.`, "Set it to a string (single-project) or an array of `{ files, use }` mappings (monorepo).");
2950
3149
  }
2951
3150
  //#endregion
2952
- //#region src/utils/report.ts
3151
+ //#region src/design-system/ds-worker.ts
2953
3152
  /**
2954
- * Shared reporter for the "first-as-fix, rest-as-suggestion" pattern.
2955
- *
2956
- * Nine rules (enforce-canonical, enforce-logical, enforce-physical,
2957
- * enforce-consistent-variable-syntax, enforce-consistent-important-position,
2958
- * enforce-negative-arbitrary-values, no-deprecated-classes,
2959
- * no-unnecessary-arbitrary-value, prefer-theme-tokens) all emit
2960
- * replacements via the same shape:
3153
+ * Generic worker-thread service wrapping `__unstable__loadDesignSystem`.
2961
3154
  *
2962
- * 1. Collect `{ cls, replacement }` entries from a class string.
2963
- * 2. Rebuild the full class string with replacements applied.
2964
- * 3. Emit ONE diagnostic with the autofix attached.
2965
- * 4. Emit one MORE diagnostic per remaining offender, each carrying
2966
- * the same autofix as a `suggest`.
3155
+ * `sort-service.ts` and `canonicalize-service.ts` used to be near-byte-identical
3156
+ * (~500 LOC) — both spawned a worker that loaded the design system, then served
3157
+ * synchronous requests over a SharedArrayBuffer using `Atomics.wait`. The only
3158
+ * real difference was the body of the request loop: `getClassOrder` vs
3159
+ * `canonicalizeCandidates`. This class encapsulates the entire shared protocol
3160
+ * — SharedArrayBuffer layout, state machine, lifecycle, fail-loud — and each
3161
+ * service shrinks to ~40 LOC of singleton + public signature.
2967
3162
  *
2968
- * oxlint's fixer is single-shot per AST node, so multiple offenders in the
2969
- * same class string can only get one mechanical fix; the rest stay as
2970
- * suggestions the IDE can offer interactively.
3163
+ * v1: failures throw `SortServiceError`. The error is sticky for the lifetime
3164
+ * of the process (per cssPath) so subsequent calls don't pay another
3165
+ * init-timeout cost. Callers wrap via `safeGetDS` to surface the failure as a
3166
+ * single `designSystemUnavailable` diagnostic.
2971
3167
  */
3168
+ const BUFFER_SIZE = 4 * 1024 * 1024;
3169
+ const HEADER_INTS = 4;
3170
+ const LENGTH_OFFSET = HEADER_INTS * 4;
3171
+ const DATA_OFFSET = 20;
3172
+ const INIT_TIMEOUT = 6e4;
3173
+ const REQUEST_TIMEOUT = 3e4;
3174
+ const MAX_WORKERS = 8;
2972
3175
  /**
2973
- * Emit autofix + suggestion diagnostics for a list of class replacements.
2974
- *
2975
- * If `offending` is empty, no-op. The fixer's `replaceTextRange` is shared
2976
- * across all diagnostics — the first one is the primary fix, the rest carry
2977
- * the same fix as a suggestion (oxlint can only apply one autofix per node).
3176
+ * Build the worker script shared by `sort-service` and `canonicalize-service`.
3177
+ * Owns the entire SharedArrayBuffer protocol (offsets derived from the same
3178
+ * constants the host uses, so they can't drift), the design-system load with
3179
+ * error propagation (DS-M4: the real cause is written into the buffer so the
3180
+ * host can surface it, not a generic "failed to load"), the ready signal, and
3181
+ * the request loop. `handlerExpr` is a function expression `(ds, request) =>
3182
+ * result` — the only part that differs between services.
2978
3183
  */
2979
- function reportClassReplacements(context, loc, split, classes, offending, options) {
2980
- if (offending.length === 0) return;
2981
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
2982
- const fixedValue = rebuildClassString(split, classes.map((c) => replacements.get(c) ?? c));
2983
- const replacementKey = options.replacementKey ?? "replacement";
2984
- const suggestMessageId = options.suggestMessageId ?? "suggestReplace";
2985
- const applyFix = (fixer) => fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2986
- const report = context.report;
2987
- for (let i = 0; i < offending.length; i++) {
2988
- const { cls, replacement } = offending[i];
2989
- const primaryData = {
2990
- className: cls,
2991
- [replacementKey]: replacement
2992
- };
2993
- if (i === 0) report({
2994
- node: loc.node,
2995
- messageId: options.messageId,
2996
- data: primaryData,
2997
- fix: applyFix
2998
- });
2999
- else report({
3000
- node: loc.node,
3001
- messageId: options.messageId,
3002
- data: primaryData,
3003
- suggest: [{
3004
- messageId: suggestMessageId,
3005
- data: {
3006
- className: cls,
3007
- replacement
3008
- },
3009
- fix: applyFix
3010
- }]
3011
- });
3012
- }
3013
- }
3014
- //#endregion
3015
- //#region src/rules/no-deprecated-classes.ts
3016
- const DEPRECATED_MAP = {
3017
- "flex-grow": "grow",
3018
- "flex-grow-0": "grow-0",
3019
- "flex-shrink": "shrink",
3020
- "flex-shrink-0": "shrink-0",
3021
- "overflow-ellipsis": "text-ellipsis",
3022
- "decoration-slice": "box-decoration-slice",
3023
- "decoration-clone": "box-decoration-clone",
3024
- "bg-gradient-to-t": "bg-linear-to-t",
3025
- "bg-gradient-to-tr": "bg-linear-to-tr",
3026
- "bg-gradient-to-r": "bg-linear-to-r",
3027
- "bg-gradient-to-br": "bg-linear-to-br",
3028
- "bg-gradient-to-b": "bg-linear-to-b",
3029
- "bg-gradient-to-bl": "bg-linear-to-bl",
3030
- "bg-gradient-to-l": "bg-linear-to-l",
3031
- "bg-gradient-to-tl": "bg-linear-to-tl"
3032
- };
3033
- const noDeprecatedClasses = defineRule({
3034
- meta: {
3035
- type: "problem",
3036
- docs: { description: "Disallow deprecated Tailwind CSS v4 classes" },
3037
- fixable: "code",
3038
- schema: [{
3039
- type: "object",
3040
- properties: { entryPoint: { type: "string" } },
3041
- additionalProperties: false
3042
- }],
3043
- hasSuggestions: true,
3044
- defaultOptions: [{}],
3045
- messages: {
3046
- deprecated: "\"{{className}}\" is deprecated in Tailwind v4. Use \"{{replacement}}\" instead.",
3047
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
3048
- }
3049
- },
3050
- createOnce(context) {
3051
- function check(locations) {
3052
- if (locations.length === 0) return;
3053
- for (const loc of locations) {
3054
- const split = splitClassesWithSeparators(loc.value);
3055
- const offending = split.classes.flatMap((cls) => {
3056
- const { utility, variant } = splitUtilityAndVariant(cls);
3057
- const { bare: bareUtility, position } = splitImportant(utility);
3058
- const replacement = DEPRECATED_MAP[bareUtility];
3059
- return replacement ? [{
3060
- cls,
3061
- replacement: variant + reattachImportant(replacement, position)
3062
- }] : [];
3063
- });
3064
- reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "deprecated" });
3065
- }
3066
- }
3067
- return createExtractorVisitors(context, check);
3068
- }
3069
- });
3070
- //#endregion
3071
- //#region src/rules/no-unknown-classes.ts
3072
- const noUnknownClasses = defineRule({
3073
- meta: {
3074
- type: "problem",
3075
- docs: { description: "Disallow classes that are not defined in the Tailwind CSS design system" },
3076
- schema: [{
3077
- type: "object",
3078
- properties: {
3079
- entryPoint: { type: "string" },
3080
- allowlist: {
3081
- type: "array",
3082
- items: { type: "string" }
3083
- },
3084
- ignorePrefixes: {
3085
- type: "array",
3086
- items: { type: "string" }
3087
- }
3088
- },
3089
- additionalProperties: false
3090
- }],
3091
- hasSuggestions: true,
3092
- defaultOptions: [{
3093
- allowlist: [],
3094
- ignorePrefixes: []
3095
- }],
3096
- messages: {
3097
- unknown: "\"{{className}}\" is not a valid Tailwind class.",
3098
- unknownWithSuggestion: "\"{{className}}\" is not a valid Tailwind class. Did you mean \"{{suggestion}}\"?",
3099
- missingPrefix: "\"{{className}}\" needs the \"{{prefix}}:\" prefix to produce CSS. Did you mean \"{{suggestion}}\"?",
3100
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
3101
- ...DS_UNAVAILABLE_MESSAGE
3102
- }
3103
- },
3104
- createOnce(context) {
3105
- const getDS = createLazyLoader(context);
3106
- const getLazyOptions = createLazyOptions(context, (o) => ({
3107
- allowlist: new Set(o?.allowlist ?? []),
3108
- ignorePrefixes: o?.ignorePrefixes ?? []
3109
- }));
3110
- function shouldIgnore(className) {
3111
- const { allowlist, ignorePrefixes } = getLazyOptions();
3112
- if (allowlist.has(className)) return true;
3113
- return ignorePrefixes.some((prefix) => className.startsWith(prefix));
3114
- }
3115
- function strippedUtility(className) {
3116
- const { utility, variant } = splitUtilityAndVariant(className);
3117
- const { bare, position } = splitImportant(utility);
3118
- return {
3119
- variant,
3120
- bare,
3121
- position
3122
- };
3123
- }
3124
- function check(locations) {
3125
- if (locations.length === 0) return;
3126
- const ds = safeGetDS(getDS, context, locations[0].node);
3127
- if (!ds) return;
3128
- const { cache } = ds;
3129
- for (const loc of locations) {
3130
- const split = splitClassesWithSeparators(loc.value);
3131
- const classes = split.classes;
3132
- for (const cls of classes) {
3133
- if (shouldIgnore(cls)) continue;
3134
- const validity = cache.classValidity(cls);
3135
- if (validity === "valid") continue;
3136
- const { variant, bare, position } = strippedUtility(cls);
3137
- if (DEPRECATED_MAP[bare]) continue;
3138
- if (validity === "missing-prefix") {
3139
- const fixed = `${cache.prefix}:${cls}`;
3140
- const fixedValue = rebuildClassString(split, classes.map((c) => c === cls ? fixed : c));
3141
- context.report({
3142
- node: loc.node,
3143
- messageId: "missingPrefix",
3144
- data: {
3145
- className: cls,
3146
- prefix: cache.prefix,
3147
- suggestion: fixed
3148
- },
3149
- suggest: [{
3150
- messageId: "suggestReplace",
3151
- data: {
3152
- className: cls,
3153
- replacement: fixed
3154
- },
3155
- fix(fixer) {
3156
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3157
- }
3158
- }]
3159
- });
3160
- continue;
3161
- }
3162
- const suggestionBare = findBestSuggestion(bare, cache.validClasses);
3163
- const suggestion = suggestionBare ? variant + reattachImportant(suggestionBare, position) : null;
3164
- if (suggestion) {
3165
- const fixedValue = rebuildClassString(split, classes.map((c) => c === cls ? suggestion : c));
3166
- context.report({
3167
- node: loc.node,
3168
- messageId: "unknownWithSuggestion",
3169
- data: {
3170
- className: cls,
3171
- suggestion
3172
- },
3173
- suggest: [{
3174
- messageId: "suggestReplace",
3175
- data: {
3176
- className: cls,
3177
- replacement: suggestion
3178
- },
3179
- fix(fixer) {
3180
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3181
- }
3182
- }]
3183
- });
3184
- } else context.report({
3185
- node: loc.node,
3186
- messageId: "unknown",
3187
- data: { className: cls }
3188
- });
3189
- }
3190
- }
3191
- }
3192
- return createExtractorVisitors(context, check);
3193
- }
3194
- });
3195
- //#endregion
3196
- //#region src/design-system/ds-worker.ts
3197
- /**
3198
- * Generic worker-thread service wrapping `__unstable__loadDesignSystem`.
3199
- *
3200
- * `sort-service.ts` and `canonicalize-service.ts` used to be near-byte-identical
3201
- * (~500 LOC) — both spawned a worker that loaded the design system, then served
3202
- * synchronous requests over a SharedArrayBuffer using `Atomics.wait`. The only
3203
- * real difference was the body of the request loop: `getClassOrder` vs
3204
- * `canonicalizeCandidates`. This class encapsulates the entire shared protocol
3205
- * — SharedArrayBuffer layout, state machine, lifecycle, fail-loud — and each
3206
- * service shrinks to ~40 LOC of singleton + public signature.
3207
- *
3208
- * v1: failures throw `SortServiceError`. The error is sticky for the lifetime
3209
- * of the process (per cssPath) so subsequent calls don't pay another
3210
- * init-timeout cost. Callers wrap via `safeGetDS` to surface the failure as a
3211
- * single `designSystemUnavailable` diagnostic.
3212
- */
3213
- const BUFFER_SIZE = 4 * 1024 * 1024;
3214
- const HEADER_INTS = 4;
3215
- const LENGTH_OFFSET = HEADER_INTS * 4;
3216
- const DATA_OFFSET = 20;
3217
- const INIT_TIMEOUT = 6e4;
3218
- const REQUEST_TIMEOUT = 3e4;
3219
- const MAX_WORKERS = 8;
3220
- /**
3221
- * Build the worker script shared by `sort-service` and `canonicalize-service`.
3222
- * Owns the entire SharedArrayBuffer protocol (offsets derived from the same
3223
- * constants the host uses, so they can't drift), the design-system load with
3224
- * error propagation (DS-M4: the real cause is written into the buffer so the
3225
- * host can surface it, not a generic "failed to load"), the ready signal, and
3226
- * the request loop. `handlerExpr` is a function expression `(ds, request) =>
3227
- * result` — the only part that differs between services.
3228
- */
3229
- function makeWorkerScript(handlerExpr, preamble = "") {
3230
- return `
3231
- ${preamble}
3232
- const { workerData } = require('worker_threads');
3233
- async function main() {
3234
- const { sharedBuffer, cssPath } = workerData;
3235
- const control = new Int32Array(sharedBuffer, 0, ${HEADER_INTS});
3236
- const lengthView = new DataView(sharedBuffer, ${LENGTH_OFFSET}, 4);
3237
- const dataArea = new Uint8Array(sharedBuffer, ${DATA_OFFSET});
3238
-
3239
- // On load failure, write the real cause into the data region so the host can
3240
- // report it instead of a bare "failed to load the design system".
3241
- function signalLoadError(e) {
3242
- try {
3243
- const msg = Buffer.from(String((e && e.message) || e || 'unknown design-system load error'), 'utf-8');
3244
- const n = Math.min(msg.length, dataArea.length);
3245
- dataArea.set(msg.subarray(0, n), 0);
3246
- lengthView.setUint32(0, n);
3247
- } catch {}
3248
- Atomics.store(control, 2, -1);
3249
- Atomics.notify(control, 2);
3250
- }
3251
-
3252
- let ds;
3253
- try {
3254
- const { __unstable__loadDesignSystem } = require(workerData.tailwindNodePath);
3255
- const { readFileSync } = require('fs');
3256
- const { dirname } = require('path');
3257
- const css = readFileSync(cssPath, 'utf-8');
3258
- ds = await __unstable__loadDesignSystem(css, { base: dirname(cssPath) });
3259
- } catch (e) {
3260
- signalLoadError(e);
3261
- return;
3262
- }
3263
-
3264
- Atomics.store(control, 2, 1);
3265
- Atomics.notify(control, 2);
3266
-
3267
- const handler = ${handlerExpr};
3268
-
3269
- while (true) {
3270
- Atomics.wait(control, 0, 0);
3271
- const len = lengthView.getUint32(0);
3272
- const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
3273
- Atomics.store(control, 0, 0);
3274
-
3275
- let response;
3276
- try {
3277
- const request = JSON.parse(requestStr);
3278
- const result = handler(ds, request);
3279
- response = Buffer.from(JSON.stringify(result), 'utf-8');
3280
- } catch {
3281
- response = Buffer.from('null', 'utf-8');
3282
- }
3283
-
3284
- // DS-M6: if the response doesn't fit the shared buffer, reply with a
3285
- // sentinel the host reads as a rejected request, instead of letting
3286
- // dataArea.set throw and kill the worker (which would hang the caller
3287
- // until the request timeout and then report a misleading timeout).
3288
- if (response.length > dataArea.length) {
3289
- response = Buffer.from('null', 'utf-8');
3290
- }
3291
-
3292
- dataArea.set(response, 0);
3293
- lengthView.setUint32(0, response.length);
3294
- Atomics.store(control, 1, 1);
3295
- Atomics.notify(control, 1);
3296
- }
3184
+ function makeWorkerScript(handlerExpr, preamble = "") {
3185
+ return `
3186
+ ${preamble}
3187
+ const { workerData } = require('worker_threads');
3188
+ async function main() {
3189
+ const { sharedBuffer, cssPath } = workerData;
3190
+ const control = new Int32Array(sharedBuffer, 0, ${HEADER_INTS});
3191
+ const lengthView = new DataView(sharedBuffer, ${LENGTH_OFFSET}, 4);
3192
+ const dataArea = new Uint8Array(sharedBuffer, ${DATA_OFFSET});
3193
+
3194
+ // On load failure, write the real cause into the data region so the host can
3195
+ // report it instead of a bare "failed to load the design system".
3196
+ function signalLoadError(e) {
3197
+ try {
3198
+ const msg = Buffer.from(String((e && e.message) || e || 'unknown design-system load error'), 'utf-8');
3199
+ const n = Math.min(msg.length, dataArea.length);
3200
+ dataArea.set(msg.subarray(0, n), 0);
3201
+ lengthView.setUint32(0, n);
3202
+ } catch {}
3203
+ Atomics.store(control, 2, -1);
3204
+ Atomics.notify(control, 2);
3205
+ }
3206
+
3207
+ let ds;
3208
+ try {
3209
+ const { __unstable__loadDesignSystem } = require(workerData.tailwindNodePath);
3210
+ const { readFileSync } = require('fs');
3211
+ const { dirname } = require('path');
3212
+ const css = readFileSync(cssPath, 'utf-8');
3213
+ ds = await __unstable__loadDesignSystem(css, { base: dirname(cssPath) });
3214
+ } catch (e) {
3215
+ signalLoadError(e);
3216
+ return;
3217
+ }
3218
+
3219
+ Atomics.store(control, 2, 1);
3220
+ Atomics.notify(control, 2);
3221
+
3222
+ const handler = ${handlerExpr};
3223
+
3224
+ while (true) {
3225
+ Atomics.wait(control, 0, 0);
3226
+ const len = lengthView.getUint32(0);
3227
+ const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
3228
+ Atomics.store(control, 0, 0);
3229
+
3230
+ let response;
3231
+ try {
3232
+ const request = JSON.parse(requestStr);
3233
+ const result = handler(ds, request);
3234
+ response = Buffer.from(JSON.stringify(result), 'utf-8');
3235
+ } catch {
3236
+ response = Buffer.from('null', 'utf-8');
3237
+ }
3238
+
3239
+ // DS-M6: if the response doesn't fit the shared buffer, reply with a
3240
+ // sentinel the host reads as a rejected request, instead of letting
3241
+ // dataArea.set throw and kill the worker (which would hang the caller
3242
+ // until the request timeout and then report a misleading timeout).
3243
+ if (response.length > dataArea.length) {
3244
+ response = Buffer.from('null', 'utf-8');
3245
+ }
3246
+
3247
+ dataArea.set(response, 0);
3248
+ lengthView.setUint32(0, response.length);
3249
+ Atomics.store(control, 1, 1);
3250
+ Atomics.notify(control, 1);
3251
+ }
3297
3252
  }
3298
3253
  main().catch(() => {});
3299
3254
  `;
@@ -3410,102 +3365,358 @@ var DesignSystemWorker = class {
3410
3365
  this.dropWorker(cssPath);
3411
3366
  throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker returned null — the request body was rejected or its response did not fit the buffer.`, "This is a bug; please open an issue with the input that triggered it."));
3412
3367
  }
3413
- return parsed;
3414
- }
3415
- reset() {
3416
- for (const state of this.workers.values()) this.terminateWorker(state.worker);
3417
- this.workers.clear();
3418
- this.errors.clear();
3419
- }
3420
- /** Terminate and forget the worker for a single cssPath (on request failure). */
3421
- dropWorker(cssPath) {
3422
- const state = this.workers.get(cssPath);
3423
- if (state) {
3424
- this.workers.delete(cssPath);
3425
- this.terminateWorker(state.worker);
3368
+ return parsed;
3369
+ }
3370
+ reset() {
3371
+ for (const state of this.workers.values()) this.terminateWorker(state.worker);
3372
+ this.workers.clear();
3373
+ this.errors.clear();
3374
+ }
3375
+ /** Terminate and forget the worker for a single cssPath (on request failure). */
3376
+ dropWorker(cssPath) {
3377
+ const state = this.workers.get(cssPath);
3378
+ if (state) {
3379
+ this.workers.delete(cssPath);
3380
+ this.terminateWorker(state.worker);
3381
+ }
3382
+ }
3383
+ terminateWorker(worker) {
3384
+ try {
3385
+ worker.removeAllListeners("error");
3386
+ worker.terminate();
3387
+ } catch {}
3388
+ }
3389
+ };
3390
+ //#endregion
3391
+ //#region src/design-system/declaration-service.ts
3392
+ const declWorker = new DesignSystemWorker({
3393
+ workerScript: makeWorkerScript(`(ds, request) => {
3394
+ const decls = {};
3395
+ const values = {};
3396
+ const invalid = [];
3397
+ // A prefixed design system only resolves the PREFIXED form (\`tw:p-[5px]\`), and
3398
+ // the host asks with prefix-free names — \`extractUtility\` strips the project
3399
+ // prefix along with the variants. Same invariant the precompute follows: apply
3400
+ // the prefix only when talking to the design system, key everything returned
3401
+ // prefix-free. Without this the service resolved NOTHING in a prefixed project,
3402
+ // so every user-written value went silently uncompared.
3403
+ const prefix = (ds.theme && ds.theme.prefix) || '';
3404
+ const pfx = (c) => (prefix && !c.startsWith(prefix + ':')) ? prefix + ':' + c : c;
3405
+ const css = ds.candidatesToCss(request.classes.map(pfx));
3406
+ for (let i = 0; i < request.classes.length; i++) {
3407
+ if (!css[i]) { invalid.push(request.classes[i]); continue; }
3408
+ const cls = request.classes[i];
3409
+ const list = [];
3410
+ // The selector carries the prefix, so the scope classifier needs the
3411
+ // prefixed name even though the result is keyed by the bare one.
3412
+ walkDeclarations(css[i], pfx(cls), (scope, prop, value) => {
3413
+ list.push([scope, prop, value]);
3414
+ if (!(value in values)) {
3415
+ const reads = scanVarReads(value);
3416
+ values[value] = { p: reads[0], f: reads[1], u: isPureVarRead(value) };
3417
+ }
3418
+ });
3419
+ if (list.length > 0) decls[cls] = list;
3420
+ }
3421
+ return { decls, values, invalid };
3422
+ }`, DECL_EXTRACTOR_SOURCE),
3423
+ serviceName: "declarations"
3424
+ });
3425
+ /**
3426
+ * Everything already asked about, per design-system CACHE — not per entry point:
3427
+ * class name → does the design system produce CSS for it. A miss is remembered
3428
+ * too, so a class that compiles to nothing is not re-queried on every AST node it
3429
+ * appears in.
3430
+ *
3431
+ * The lifetime has to match the cache's, because that is where the declarations
3432
+ * are interned. Keyed by path, a rebuilt cache (an mtime bump in a long-lived
3433
+ * editor process, or `resetDesignSystem()`) inherited a fully-populated map and
3434
+ * could never re-learn: the rules went permanently blind to user-written values
3435
+ * with no diagnostic. A WeakMap also means there is nothing to reset.
3436
+ */
3437
+ const answers = /* @__PURE__ */ new WeakMap();
3438
+ function answersFor(cache) {
3439
+ let map = answers.get(cache);
3440
+ if (!map) {
3441
+ map = /* @__PURE__ */ new Map();
3442
+ answers.set(cache, map);
3443
+ }
3444
+ return map;
3445
+ }
3446
+ /**
3447
+ * Ask the design system about every class there is no answer for yet, intern the
3448
+ * declarations it returns, and record which classes produce no CSS at all.
3449
+ *
3450
+ * **Throws `SortServiceError` when the service is unavailable**, like the sort and
3451
+ * canonicalize services do. It used to swallow the failure and report "no
3452
+ * information", which was defensible when `no-conflicting-classes` was the only
3453
+ * caller — no declarations means no comparison, so the rule just went quiet. It
3454
+ * stopped being defensible once `no-unknown-classes` started asking about
3455
+ * VALIDITY: there, silence sends the rule back to the tolerant heuristic, so a
3456
+ * dead worker quietly reinstates the very false negatives the service exists to
3457
+ * remove, with nothing anywhere to say so.
3458
+ *
3459
+ * The caller decides what to do, and the two postures already exist in the
3460
+ * plugin: a DS-dependent rule surfaces it through `safeGetDS` as
3461
+ * `designSystemUnavailable` (what `enforce-canonical` does with the canonicalize
3462
+ * worker), a DS-OPTIONAL rule catches it and degrades.
3463
+ */
3464
+ function ask(cssPath, cache, classes) {
3465
+ const known = answersFor(cache);
3466
+ const pending = [...new Set(classes.filter((cls) => !known.has(cls)))];
3467
+ if (pending.length === 0) return;
3468
+ const response = declWorker.callSync(cssPath, { classes: pending });
3469
+ const invalid = new Set(response.invalid);
3470
+ for (const cls of pending) known.set(cls, !invalid.has(cls));
3471
+ for (const [cls, raws] of Object.entries(response.decls)) cache.internDeclarations(cls, raws, response.values);
3472
+ }
3473
+ /**
3474
+ * Resolve and intern declarations for `classes` that the precompute doesn't know.
3475
+ * They land in the cache, so the caller reads them back through
3476
+ * `cache.getCssDeclarations` like any other class.
3477
+ *
3478
+ * Throws `SortServiceError` if the service is unavailable — see `ask`.
3479
+ */
3480
+ function resolveDeclarationsSync(cssPath, cache, classes) {
3481
+ ask(cssPath, cache, classes);
3482
+ }
3483
+ /**
3484
+ * Which of these classes produce CSS.
3485
+ *
3486
+ * This is what makes validity exact for the classes the precompute cannot
3487
+ * enumerate: `w-45` and `bg-red-5000` are shaped identically, and only Tailwind
3488
+ * knows that it compiles the first and not the second. Throws
3489
+ * `SortServiceError` if the service is unavailable — see `ask`.
3490
+ */
3491
+ function validateClassesSync(cssPath, cache, classes) {
3492
+ ask(cssPath, cache, classes);
3493
+ return answersFor(cache);
3494
+ }
3495
+ //#endregion
3496
+ //#region src/rules/no-unknown-classes.ts
3497
+ /**
3498
+ * Utility used to probe a variant chain. Any always-valid utility works; `flex`
3499
+ * is the shortest one every Tailwind build has.
3500
+ */
3501
+ const PROBE_UTILITY = "flex";
3502
+ const noUnknownClasses = defineRule({
3503
+ meta: {
3504
+ type: "problem",
3505
+ docs: { description: "Disallow classes that are not defined in the Tailwind CSS design system" },
3506
+ schema: [{
3507
+ type: "object",
3508
+ properties: {
3509
+ entryPoint: { type: "string" },
3510
+ allowlist: {
3511
+ type: "array",
3512
+ items: { type: "string" }
3513
+ },
3514
+ ignorePrefixes: {
3515
+ type: "array",
3516
+ items: { type: "string" }
3517
+ }
3518
+ },
3519
+ additionalProperties: false
3520
+ }],
3521
+ hasSuggestions: true,
3522
+ defaultOptions: [{
3523
+ allowlist: [],
3524
+ ignorePrefixes: []
3525
+ }],
3526
+ messages: {
3527
+ unknown: "\"{{className}}\" is not a valid Tailwind class.",
3528
+ unknownWithSuggestion: "\"{{className}}\" is not a valid Tailwind class. Did you mean \"{{suggestion}}\"?",
3529
+ missingPrefix: "\"{{className}}\" needs the \"{{prefix}}:\" prefix to produce CSS. Did you mean \"{{suggestion}}\"?",
3530
+ unknownVariant: "\"{{className}}\" produces no CSS: \"{{variant}}\" is not a variant this design system knows.",
3531
+ unknownVariantWithSuggestion: "\"{{className}}\" produces no CSS: \"{{variant}}\" is not a variant this design system knows. Did you mean \"{{suggestion}}\"?",
3532
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
3533
+ ...DS_UNAVAILABLE_MESSAGE
3534
+ }
3535
+ },
3536
+ createOnce(context) {
3537
+ const getDS = createLazyLoader(context);
3538
+ const getLazyOptions = createLazyOptions(context, (o) => ({
3539
+ allowlist: new Set(o?.allowlist ?? []),
3540
+ ignorePrefixes: o?.ignorePrefixes ?? []
3541
+ }));
3542
+ function shouldIgnore(className) {
3543
+ const { allowlist, ignorePrefixes } = getLazyOptions();
3544
+ if (allowlist.has(className)) return true;
3545
+ return ignorePrefixes.some((prefix) => className.startsWith(prefix));
3546
+ }
3547
+ function strippedUtility(className) {
3548
+ const { utility, variant } = splitUtilityAndVariant(className);
3549
+ const { bare, position } = splitImportant(utility);
3550
+ return {
3551
+ variant,
3552
+ bare,
3553
+ position
3554
+ };
3555
+ }
3556
+ /**
3557
+ * Does the design system compile this variant chain?
3558
+ *
3559
+ * `variantOrder` only lists the STATIC variants (71 of them: `hover`, `md`,
3560
+ * `dark`, …). It has no `group`, no `data`, no `@md`, because those are
3561
+ * functional variants whose values are unbounded — so validating a chain
3562
+ * against that list would report `group-hover:` and `data-[x=1]:` as unknown.
3563
+ * Compiling a probe utility under the chain is the only exact answer, and it
3564
+ * costs one design-system call per DISTINCT chain in the project.
3565
+ */
3566
+ const chainAnswers = /* @__PURE__ */ new Map();
3567
+ function chainProduces(cache, entryPoint, chain) {
3568
+ const key = `${entryPoint}\0${chain}`;
3569
+ const memo = chainAnswers.get(key);
3570
+ if (memo !== void 0) return memo;
3571
+ const probe = `${chain}${PROBE_UTILITY}`;
3572
+ const verdict = validateClassesSync(entryPoint, cache, [probe]).get(probe) ?? null;
3573
+ chainAnswers.set(key, verdict);
3574
+ return verdict;
3575
+ }
3576
+ /** Replace one class in the location and report, with a quick-fix suggestion. */
3577
+ function reportWithSuggestion(loc, classes, cls, replacement, messageId, data, split) {
3578
+ const fixedValue = rebuildClassString(split, classes.map((c) => c === cls ? replacement : c));
3579
+ context.report({
3580
+ node: loc.node,
3581
+ messageId,
3582
+ data,
3583
+ suggest: [{
3584
+ messageId: "suggestReplace",
3585
+ data: {
3586
+ className: cls,
3587
+ replacement
3588
+ },
3589
+ fix(fixer) {
3590
+ return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3591
+ }
3592
+ }]
3593
+ });
3594
+ }
3595
+ function check(locations) {
3596
+ if (locations.length === 0) return;
3597
+ const ds = safeGetDS(getDS, context, locations[0].node);
3598
+ if (!ds) return;
3599
+ const { cache, entryPoint } = ds;
3600
+ try {
3601
+ checkLocations(locations, cache, entryPoint);
3602
+ } catch (error) {
3603
+ if (reportFatalDsError(context, error, locations[0].node)) return;
3604
+ throw error;
3605
+ }
3606
+ }
3607
+ function checkLocations(locations, cache, entryPoint) {
3608
+ for (const loc of locations) {
3609
+ const split = splitClassesWithSeparators(loc.value);
3610
+ const classes = split.classes;
3611
+ let toVerify = null;
3612
+ for (const cls of classes) {
3613
+ if (shouldIgnore(cls)) continue;
3614
+ const bare = strippedUtility(cls).bare;
3615
+ if (cache.isKnownClass(bare)) continue;
3616
+ if (!toVerify) toVerify = [];
3617
+ toVerify.push(bare);
3618
+ }
3619
+ const verified = toVerify ? validateClassesSync(entryPoint, cache, toVerify) : null;
3620
+ for (const cls of classes) {
3621
+ if (shouldIgnore(cls)) continue;
3622
+ const validity = cache.classValidity(cls);
3623
+ const { variant, bare, position } = strippedUtility(cls);
3624
+ if (validity === "valid" && !variant && cache.isKnownClass(bare)) continue;
3625
+ if (cache.deprecatedReplacement(bare)) continue;
3626
+ if (validity === "missing-prefix") {
3627
+ const fixed = `${cache.prefix}:${cls}`;
3628
+ reportWithSuggestion(loc, classes, cls, fixed, "missingPrefix", {
3629
+ className: cls,
3630
+ prefix: cache.prefix,
3631
+ suggestion: fixed
3632
+ }, split);
3633
+ continue;
3634
+ }
3635
+ const compiles = cache.isKnownClass(bare) ? true : verified?.get(bare);
3636
+ if (validity === "unknown" || compiles === false) {
3637
+ const suggestionBare = findBestSuggestion(bare, cache.validClasses);
3638
+ const suggestion = suggestionBare ? variant + reattachImportant(suggestionBare, position) : null;
3639
+ if (suggestion) reportWithSuggestion(loc, classes, cls, suggestion, "unknownWithSuggestion", {
3640
+ className: cls,
3641
+ suggestion
3642
+ }, split);
3643
+ else context.report({
3644
+ node: loc.node,
3645
+ messageId: "unknown",
3646
+ data: { className: cls }
3647
+ });
3648
+ continue;
3649
+ }
3650
+ if (!variant) continue;
3651
+ if (chainProduces(cache, entryPoint, variant) !== false) continue;
3652
+ const { variant: offending, suggestion, fixedChain } = diagnoseChain(cache, entryPoint, variant);
3653
+ const fixedClass = fixedChain ? fixedChain + reattachImportant(bare, position) : null;
3654
+ if (fixedClass && suggestion) reportWithSuggestion(loc, classes, cls, fixedClass, "unknownVariantWithSuggestion", {
3655
+ className: cls,
3656
+ variant: offending,
3657
+ suggestion
3658
+ }, split);
3659
+ else context.report({
3660
+ node: loc.node,
3661
+ messageId: "unknownVariant",
3662
+ data: {
3663
+ className: cls,
3664
+ variant: offending
3665
+ }
3666
+ });
3667
+ }
3668
+ }
3669
+ }
3670
+ /**
3671
+ * Which segment of an invalid chain is to blame, and what to use instead.
3672
+ *
3673
+ * Every candidate correction is checked against the design system before it
3674
+ * is offered, so a suggestion is never a guess: `group-hoverr` is corrected by
3675
+ * fixing its last dash-segment and confirming that `group-hover:` compiles.
3676
+ * That also means no list of compound roots (`group`, `peer`, `data`, …) has
3677
+ * to be maintained here.
3678
+ */
3679
+ function diagnoseChain(cache, entryPoint, chain) {
3680
+ const segments = extractVariants(`${chain}${PROBE_UTILITY}`);
3681
+ const names = cache.variantNames();
3682
+ for (const segment of segments) {
3683
+ if (segment.startsWith("[")) continue;
3684
+ if (chainProduces(cache, entryPoint, `${segment}:`) !== false) continue;
3685
+ for (const candidate of correctionsFor(segment, names)) {
3686
+ if (chainProduces(cache, entryPoint, `${candidate}:`) !== true) continue;
3687
+ return {
3688
+ variant: segment,
3689
+ suggestion: candidate,
3690
+ fixedChain: segments.map((s) => s === segment ? candidate : s).join(":") + ":"
3691
+ };
3692
+ }
3693
+ return {
3694
+ variant: segment,
3695
+ suggestion: null,
3696
+ fixedChain: null
3697
+ };
3698
+ }
3699
+ return {
3700
+ variant: chain.slice(0, -1),
3701
+ suggestion: null,
3702
+ fixedChain: null
3703
+ };
3426
3704
  }
3705
+ /** Spelling candidates for a variant segment, nearest neighbour first. */
3706
+ function correctionsFor(segment, names) {
3707
+ const out = [];
3708
+ const whole = findBestSuggestion(segment, names);
3709
+ if (whole) out.push(whole);
3710
+ const dash = segment.lastIndexOf("-");
3711
+ if (dash > 0) {
3712
+ const tail = findBestSuggestion(segment.slice(dash + 1), names);
3713
+ if (tail) out.push(`${segment.slice(0, dash)}-${tail}`);
3714
+ }
3715
+ return out;
3716
+ }
3717
+ return createExtractorVisitors(context, check);
3427
3718
  }
3428
- terminateWorker(worker) {
3429
- try {
3430
- worker.removeAllListeners("error");
3431
- worker.terminate();
3432
- } catch {}
3433
- }
3434
- };
3435
- //#endregion
3436
- //#region src/design-system/declaration-service.ts
3437
- const declWorker = new DesignSystemWorker({
3438
- workerScript: makeWorkerScript(`(ds, request) => {
3439
- const decls = {};
3440
- const values = {};
3441
- // A prefixed design system only resolves the PREFIXED form (\`tw:p-[5px]\`), and
3442
- // the host asks with prefix-free names — \`extractUtility\` strips the project
3443
- // prefix along with the variants. Same invariant the precompute follows: apply
3444
- // the prefix only when talking to the design system, key everything returned
3445
- // prefix-free. Without this the service resolved NOTHING in a prefixed project,
3446
- // so every user-written value went silently uncompared.
3447
- const prefix = (ds.theme && ds.theme.prefix) || '';
3448
- const pfx = (c) => (prefix && !c.startsWith(prefix + ':')) ? prefix + ':' + c : c;
3449
- const css = ds.candidatesToCss(request.classes.map(pfx));
3450
- for (let i = 0; i < request.classes.length; i++) {
3451
- if (!css[i]) continue;
3452
- const cls = request.classes[i];
3453
- const list = [];
3454
- // The selector carries the prefix, so the scope classifier needs the
3455
- // prefixed name even though the result is keyed by the bare one.
3456
- walkDeclarations(css[i], pfx(cls), (scope, prop, value) => {
3457
- list.push([scope, prop, value]);
3458
- if (!(value in values)) {
3459
- const reads = scanVarReads(value);
3460
- values[value] = { p: reads[0], f: reads[1], u: isPureVarRead(value) };
3461
- }
3462
- });
3463
- if (list.length > 0) decls[cls] = list;
3464
- }
3465
- return { decls, values };
3466
- }`, DECL_EXTRACTOR_SOURCE),
3467
- serviceName: "declarations"
3468
3719
  });
3469
- /**
3470
- * Classes already asked about, per design-system CACHE — not per entry point. A
3471
- * miss is remembered too: a class the design system produces no CSS for must not
3472
- * be re-queried on every AST node it appears in.
3473
- *
3474
- * The lifetime has to match the cache's, because that is where the answers are
3475
- * interned. Keyed by path, a rebuilt cache (an mtime bump in a long-lived editor
3476
- * process, or `resetDesignSystem()`) inherited a fully-populated set and could
3477
- * never re-learn: the rule went permanently blind to user-written values with no
3478
- * diagnostic. A WeakMap also means there is nothing to reset.
3479
- */
3480
- const queried = /* @__PURE__ */ new WeakMap();
3481
- function queriedFor(cache) {
3482
- let set = queried.get(cache);
3483
- if (!set) {
3484
- set = /* @__PURE__ */ new Set();
3485
- queried.set(cache, set);
3486
- }
3487
- return set;
3488
- }
3489
- /**
3490
- * Resolve declarations for `classes` that the precompute doesn't know.
3491
- *
3492
- * Returns null when the service is unavailable, which the caller treats as "no
3493
- * information" — the same posture as a class with no declarations, so a broken
3494
- * worker degrades to today's silence rather than to wrong diagnostics. Real
3495
- * failures still surface through the sticky error the worker records.
3496
- */
3497
- function resolveDeclarationsSync(cssPath, cache, classes) {
3498
- const seen = queriedFor(cache);
3499
- const pending = classes.filter((cls) => !seen.has(cls));
3500
- if (pending.length === 0) return null;
3501
- for (const cls of pending) seen.add(cls);
3502
- try {
3503
- return declWorker.callSync(cssPath, { classes: pending });
3504
- } catch (error) {
3505
- if (error instanceof SortServiceError) return null;
3506
- throw error;
3507
- }
3508
- }
3509
3720
  //#endregion
3510
3721
  //#region src/rules/no-conflicting-classes/spec.ts
3511
3722
  const COMPLEMENTARY_GROUPS = [{
@@ -3785,15 +3996,6 @@ function shouldSkipPair(a, b, rules = {}) {
3785
3996
  for (const { a: reA, b: reB } of pairs) if (reA.test(ua) && reB.test(ub) || reA.test(ub) && reB.test(ua)) return true;
3786
3997
  return false;
3787
3998
  }
3788
- /**
3789
- * A class the precompute cannot have enumerated: the value is written by the
3790
- * user, not by the design system's class list. Asking the design system about
3791
- * these is what closes the false negatives — `p-4 p-[5px]` used to be silently
3792
- * accepted while `p-4 p-6` reported.
3793
- */
3794
- function isUserValued(utility) {
3795
- return utility.includes("[") || utility.includes("(") || utility.includes("/") || /-\d/.test(utility);
3796
- }
3797
3999
  /** Whether the user's `allow` option silences this pair. */
3798
4000
  function isAllowed(a, b, allowClasses, allowPairs) {
3799
4001
  if (matchesAny(a, allowClasses) || matchesAny(b, allowClasses)) return true;
@@ -3874,8 +4076,10 @@ const noConflictingClasses = defineRule({
3874
4076
  if (variantClasses.length < 2) continue;
3875
4077
  const unknown = variantClasses.map((cls) => splitImportant(extractUtility(cls)).bare).filter((bare) => cache.getCssDeclarations(bare).length === 0 && isUserValued(bare));
3876
4078
  if (unknown.length > 0) {
3877
- const resolved = resolveDeclarationsSync(ds.entryPoint, cache, unknown);
3878
- if (resolved) for (const [cls, raws] of Object.entries(resolved.decls)) cache.internDeclarations(cls, raws, resolved.values);
4079
+ if (!safeGetDS(() => {
4080
+ resolveDeclarationsSync(ds.entryPoint, cache, unknown);
4081
+ return true;
4082
+ }, context, loc.node)) return;
3879
4083
  }
3880
4084
  const facts = variantClasses.map((cls) => {
3881
4085
  const utility = extractUtility(cls);
@@ -3950,6 +4154,156 @@ const noConflictingClasses = defineRule({
3950
4154
  }
3951
4155
  });
3952
4156
  //#endregion
4157
+ //#region src/utils/report.ts
4158
+ /**
4159
+ * Shared reporter for the "first-as-fix, rest-as-suggestion" pattern.
4160
+ *
4161
+ * Nine rules (enforce-canonical, enforce-logical, enforce-physical,
4162
+ * enforce-consistent-variable-syntax, enforce-consistent-important-position,
4163
+ * enforce-negative-arbitrary-values, no-deprecated-classes,
4164
+ * no-unnecessary-arbitrary-value, prefer-theme-tokens) all emit
4165
+ * replacements via the same shape:
4166
+ *
4167
+ * 1. Collect `{ cls, replacement }` entries from a class string.
4168
+ * 2. Rebuild the full class string with replacements applied.
4169
+ * 3. Emit ONE diagnostic with the autofix attached.
4170
+ * 4. Emit one MORE diagnostic per remaining offender, each carrying
4171
+ * the same autofix as a `suggest`.
4172
+ *
4173
+ * oxlint's fixer is single-shot per AST node, so multiple offenders in the
4174
+ * same class string can only get one mechanical fix; the rest stay as
4175
+ * suggestions the IDE can offer interactively.
4176
+ */
4177
+ /**
4178
+ * Emit autofix + suggestion diagnostics for a list of class replacements.
4179
+ *
4180
+ * If `offending` is empty, no-op. The fixer's `replaceTextRange` is shared
4181
+ * across all diagnostics — the first one is the primary fix, the rest carry
4182
+ * the same fix as a suggestion (oxlint can only apply one autofix per node).
4183
+ */
4184
+ function reportClassReplacements(context, loc, split, classes, offending, options) {
4185
+ if (offending.length === 0) return;
4186
+ const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
4187
+ const fixedValue = rebuildClassString(split, classes.map((c) => replacements.get(c) ?? c));
4188
+ const replacementKey = options.replacementKey ?? "replacement";
4189
+ const suggestMessageId = options.suggestMessageId ?? "suggestReplace";
4190
+ const applyFix = (fixer) => fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
4191
+ const report = context.report;
4192
+ for (let i = 0; i < offending.length; i++) {
4193
+ const { cls, replacement } = offending[i];
4194
+ const primaryData = {
4195
+ className: cls,
4196
+ [replacementKey]: replacement
4197
+ };
4198
+ if (i === 0) report({
4199
+ node: loc.node,
4200
+ messageId: options.messageId,
4201
+ data: primaryData,
4202
+ fix: applyFix
4203
+ });
4204
+ else report({
4205
+ node: loc.node,
4206
+ messageId: options.messageId,
4207
+ data: primaryData,
4208
+ suggest: [{
4209
+ messageId: suggestMessageId,
4210
+ data: {
4211
+ className: cls,
4212
+ replacement
4213
+ },
4214
+ fix: applyFix
4215
+ }]
4216
+ });
4217
+ }
4218
+ }
4219
+ //#endregion
4220
+ //#region src/utils/replacement.ts
4221
+ /**
4222
+ * Returns a predicate that answers "would this replacement produce CSS?".
4223
+ *
4224
+ * `cache.isValid` is the tolerant validity check, so it accepts arbitrary values
4225
+ * (`foo-[5px]`) it cannot verify. That is the right posture here: a rewrite of an
4226
+ * already-invalid class is `no-unknown-classes`' business, and this guard only
4227
+ * has to stop a rewrite from INTRODUCING an invalid class.
4228
+ */
4229
+ function makeReplacementGuard(cache) {
4230
+ if (!cache) return () => true;
4231
+ return (replacement) => cache.isValid(replacement);
4232
+ }
4233
+ //#endregion
4234
+ //#region src/rules/no-deprecated-classes.ts
4235
+ /**
4236
+ * Fallback rename map, for when no design system is available.
4237
+ *
4238
+ * With an `entryPoint` configured the rule uses the map the precompute derives
4239
+ * from `canonicalizeCandidates`, which is strictly better: it covers the renames
4240
+ * this list misses (`break-words`, `order-none`, the reordered
4241
+ * `bg-left-top`/`object-left-top` position spellings) and it prunes itself when a
4242
+ * Tailwind release stops compiling one of them. This table only has to keep the
4243
+ * unconfigured case working exactly as it did.
4244
+ */
4245
+ const DEPRECATED_MAP = {
4246
+ "flex-grow": "grow",
4247
+ "flex-grow-0": "grow-0",
4248
+ "flex-shrink": "shrink",
4249
+ "flex-shrink-0": "shrink-0",
4250
+ "overflow-ellipsis": "text-ellipsis",
4251
+ "decoration-slice": "box-decoration-slice",
4252
+ "decoration-clone": "box-decoration-clone",
4253
+ "bg-gradient-to-t": "bg-linear-to-t",
4254
+ "bg-gradient-to-tr": "bg-linear-to-tr",
4255
+ "bg-gradient-to-r": "bg-linear-to-r",
4256
+ "bg-gradient-to-br": "bg-linear-to-br",
4257
+ "bg-gradient-to-b": "bg-linear-to-b",
4258
+ "bg-gradient-to-bl": "bg-linear-to-bl",
4259
+ "bg-gradient-to-l": "bg-linear-to-l",
4260
+ "bg-gradient-to-tl": "bg-linear-to-tl"
4261
+ };
4262
+ const noDeprecatedClasses = defineRule({
4263
+ meta: {
4264
+ type: "problem",
4265
+ docs: { description: "Disallow deprecated Tailwind CSS v4 classes" },
4266
+ fixable: "code",
4267
+ schema: [{
4268
+ type: "object",
4269
+ properties: { entryPoint: { type: "string" } },
4270
+ additionalProperties: false
4271
+ }],
4272
+ hasSuggestions: true,
4273
+ defaultOptions: [{}],
4274
+ messages: {
4275
+ deprecated: "\"{{className}}\" is deprecated in Tailwind v4. Use \"{{replacement}}\" instead.",
4276
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
4277
+ }
4278
+ },
4279
+ createOnce(context) {
4280
+ const getDS = createLazyLoader(context);
4281
+ function check(locations) {
4282
+ if (locations.length === 0) return;
4283
+ const ds = softGetDS(getDS);
4284
+ const cache = ds ? ds.cache : null;
4285
+ const replacementFor = (bare) => cache?.hasDeprecatedMap ? cache.deprecatedReplacement(bare) : DEPRECATED_MAP[bare] ?? null;
4286
+ const isUsable = makeReplacementGuard(cache);
4287
+ for (const loc of locations) {
4288
+ const split = splitClassesWithSeparators(loc.value);
4289
+ const offending = split.classes.flatMap((cls) => {
4290
+ const { utility, variant } = splitUtilityAndVariant(cls);
4291
+ const { bare: bareUtility, position } = splitImportant(utility);
4292
+ const replacement = replacementFor(bareUtility);
4293
+ if (!replacement) return [];
4294
+ const rebuilt = variant + reattachImportant(replacement, position);
4295
+ return isUsable(rebuilt) ? [{
4296
+ cls,
4297
+ replacement: rebuilt
4298
+ }] : [];
4299
+ });
4300
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "deprecated" });
4301
+ }
4302
+ }
4303
+ return createExtractorVisitors(context, check);
4304
+ }
4305
+ });
4306
+ //#endregion
3953
4307
  //#region src/design-system/canonicalize-service.ts
3954
4308
  /**
3955
4309
  * Persistent canonicalize service backed by `DesignSystemWorker`.
@@ -4264,10 +4618,17 @@ const enforceCanonical = defineRule({
4264
4618
  const canonicals = Array.from({ length: classes.length });
4265
4619
  const arbitraryIdx = [];
4266
4620
  const arbitrary = [];
4267
- for (let i = 0; i < classes.length; i++) if (utilityHasDynamicValue(classes[i])) {
4268
- arbitraryIdx.push(i);
4269
- arbitrary.push(classes[i]);
4270
- } else canonicals[i] = cache.canonicalize(classes[i]);
4621
+ for (let i = 0; i < classes.length; i++) {
4622
+ const { utility } = splitUtilityAndVariant(classes[i]);
4623
+ if (cache.deprecatedReplacement(splitImportant(utility).bare)) {
4624
+ canonicals[i] = classes[i];
4625
+ continue;
4626
+ }
4627
+ if (utilityHasDynamicValue(classes[i])) {
4628
+ arbitraryIdx.push(i);
4629
+ arbitrary.push(classes[i]);
4630
+ } else canonicals[i] = cache.canonicalize(classes[i]);
4631
+ }
4271
4632
  if (arbitrary.length > 0) {
4272
4633
  const rem = getRem();
4273
4634
  const dynamic = safeGetDS(() => canonicalizeClassesSync(entryPoint, arbitrary, rem), context, loc.node);
@@ -4414,124 +4775,320 @@ const enforceSortOrder = defineRule({
4414
4775
  }
4415
4776
  return createExtractorVisitors(context, check);
4416
4777
  }
4417
- });
4418
- //#endregion
4419
- //#region src/rules/enforce-shorthand.ts
4420
- const VALUE_RE = /^(?:m[trbl]|mx|my|p[trbl]|px|py|[wh]|rounded-t[lr]|rounded-b[lr]|min-[wh]|max-[wh])-(.+)$/;
4421
- const INVALID_SIZE_VALUES = /* @__PURE__ */ new Set([
4422
- "screen",
4778
+ });
4779
+ //#endregion
4780
+ //#region src/rules/enforce-shorthand.ts
4781
+ /**
4782
+ * The `m`/`p` shape, shared by `margin`, `padding`, `scroll-margin` and
4783
+ * `scroll-padding`: four sides, each axis, and the logical inline pair (`ms`+`me`
4784
+ * IS `margin-inline`, so that one is property-identical rather than merely
4785
+ * equivalent).
4786
+ */
4787
+ function boxFamilies(p) {
4788
+ return [
4789
+ {
4790
+ parts: [
4791
+ `${p}t`,
4792
+ `${p}r`,
4793
+ `${p}b`,
4794
+ `${p}l`
4795
+ ],
4796
+ to: p
4797
+ },
4798
+ {
4799
+ parts: [`${p}t`, `${p}b`],
4800
+ to: `${p}y`
4801
+ },
4802
+ {
4803
+ parts: [`${p}l`, `${p}r`],
4804
+ to: `${p}x`
4805
+ },
4806
+ {
4807
+ parts: [`${p}s`, `${p}e`],
4808
+ to: `${p}x`
4809
+ },
4810
+ {
4811
+ parts: [`${p}x`, `${p}y`],
4812
+ to: p
4813
+ }
4814
+ ];
4815
+ }
4816
+ const SHORTHAND_FAMILIES = [
4817
+ ...boxFamilies("m"),
4818
+ ...boxFamilies("p"),
4819
+ ...boxFamilies("scroll-m"),
4820
+ ...boxFamilies("scroll-p"),
4821
+ {
4822
+ parts: ["w", "h"],
4823
+ to: "size",
4824
+ perAxisNamespaces: true
4825
+ },
4826
+ {
4827
+ parts: [
4828
+ "rounded-tl",
4829
+ "rounded-tr",
4830
+ "rounded-br",
4831
+ "rounded-bl"
4832
+ ],
4833
+ to: "rounded"
4834
+ },
4835
+ {
4836
+ parts: [
4837
+ "rounded-ss",
4838
+ "rounded-se",
4839
+ "rounded-ee",
4840
+ "rounded-es"
4841
+ ],
4842
+ to: "rounded"
4843
+ },
4844
+ {
4845
+ parts: ["rounded-tl", "rounded-tr"],
4846
+ to: "rounded-t"
4847
+ },
4848
+ {
4849
+ parts: ["rounded-bl", "rounded-br"],
4850
+ to: "rounded-b"
4851
+ },
4852
+ {
4853
+ parts: ["rounded-tl", "rounded-bl"],
4854
+ to: "rounded-l"
4855
+ },
4856
+ {
4857
+ parts: ["rounded-tr", "rounded-br"],
4858
+ to: "rounded-r"
4859
+ },
4860
+ {
4861
+ parts: ["rounded-ss", "rounded-es"],
4862
+ to: "rounded-s"
4863
+ },
4864
+ {
4865
+ parts: ["rounded-se", "rounded-ee"],
4866
+ to: "rounded-e"
4867
+ },
4868
+ {
4869
+ parts: ["rounded-t", "rounded-b"],
4870
+ to: "rounded"
4871
+ },
4872
+ {
4873
+ parts: ["rounded-l", "rounded-r"],
4874
+ to: "rounded"
4875
+ },
4876
+ {
4877
+ parts: ["rounded-s", "rounded-e"],
4878
+ to: "rounded"
4879
+ },
4880
+ {
4881
+ parts: [
4882
+ "border-t",
4883
+ "border-r",
4884
+ "border-b",
4885
+ "border-l"
4886
+ ],
4887
+ to: "border"
4888
+ },
4889
+ {
4890
+ parts: ["border-t", "border-b"],
4891
+ to: "border-y"
4892
+ },
4893
+ {
4894
+ parts: ["border-l", "border-r"],
4895
+ to: "border-x"
4896
+ },
4897
+ {
4898
+ parts: ["border-s", "border-e"],
4899
+ to: "border-x"
4900
+ },
4901
+ {
4902
+ parts: ["border-x", "border-y"],
4903
+ to: "border"
4904
+ },
4905
+ {
4906
+ parts: [
4907
+ "top",
4908
+ "right",
4909
+ "bottom",
4910
+ "left"
4911
+ ],
4912
+ to: "inset"
4913
+ },
4914
+ {
4915
+ parts: ["top", "bottom"],
4916
+ to: "inset-y"
4917
+ },
4918
+ {
4919
+ parts: ["left", "right"],
4920
+ to: "inset-x"
4921
+ },
4922
+ {
4923
+ parts: ["start", "end"],
4924
+ to: "inset-x"
4925
+ },
4926
+ {
4927
+ parts: ["inset-x", "inset-y"],
4928
+ to: "inset"
4929
+ },
4930
+ {
4931
+ parts: ["gap-x", "gap-y"],
4932
+ to: "gap"
4933
+ },
4934
+ {
4935
+ parts: ["overflow-x", "overflow-y"],
4936
+ to: "overflow"
4937
+ },
4938
+ {
4939
+ parts: ["overscroll-x", "overscroll-y"],
4940
+ to: "overscroll"
4941
+ },
4942
+ {
4943
+ parts: ["border-spacing-x", "border-spacing-y"],
4944
+ to: "border-spacing"
4945
+ },
4946
+ {
4947
+ parts: ["translate-x", "translate-y"],
4948
+ to: "translate"
4949
+ }
4950
+ ];
4951
+ /**
4952
+ * Largest merges first, so four sides collapse to `m-2` instead of also
4953
+ * reporting the `my-2`/`mx-2` halves — three diagnostics for one problem, which
4954
+ * is what this rule used to emit. `sort` is stable, so same-size families keep
4955
+ * their declaration order and the choice stays deterministic.
4956
+ */
4957
+ const FAMILIES_BY_SIZE = [...SHORTHAND_FAMILIES].sort((a, b) => b.parts.length - a.parts.length);
4958
+ /**
4959
+ * `^<part>-<value>$`, longest prefix first so `rounded-tl-lg` is read as
4960
+ * `rounded-tl` + `lg` and never as `rounded-t` + `l-lg`.
4961
+ */
4962
+ const VALUE_RE = (() => {
4963
+ const prefixes = [...new Set(SHORTHAND_FAMILIES.flatMap((f) => f.parts))].sort((a, b) => b.length - a.length);
4964
+ return new RegExp(`^(${prefixes.join("|")})-(.+)$`);
4965
+ })();
4966
+ /** A plain number or fraction: always the shared numeric/`--spacing` scale. */
4967
+ const NUMERIC_VALUE_RE = /^\d+(?:\.\d+)?(?:\/\d+(?:\.\d+)?)?$/;
4968
+ /**
4969
+ * Core keywords whose per-axis forms are known to agree, for when no design
4970
+ * system is available to check. Deliberately excludes `screen` (`w-screen` is
4971
+ * `100vw`, `h-screen` is `100vh`) and every named theme token, which is the case
4972
+ * that can only be settled by looking at the emitted CSS.
4973
+ */
4974
+ const AXIS_SAFE_KEYWORDS = /* @__PURE__ */ new Set([
4975
+ "full",
4976
+ "auto",
4977
+ "min",
4978
+ "max",
4979
+ "fit",
4980
+ "px",
4423
4981
  "dvw",
4424
4982
  "dvh",
4425
- "svw",
4426
- "svh",
4427
4983
  "lvw",
4428
- "lvh"
4984
+ "lvh",
4985
+ "svw",
4986
+ "svh"
4429
4987
  ]);
4988
+ /** The value is a literal the user wrote, injected verbatim into every part. */
4989
+ function isWrittenValue(value) {
4990
+ return value.startsWith("[") || value.startsWith("(");
4991
+ }
4430
4992
  /**
4431
- * Generates shorthand rules parameterized by value.
4432
- * E.g.: mt-2 + mr-2 + mb-2 + ml-2 -> m-2
4993
+ * Values the class declares on its own box, unconditionally. `null` when the
4994
+ * class produces nothing — which for a named token means it does not exist.
4433
4995
  */
4434
- function createShorthandRules(value) {
4435
- return [
4436
- {
4437
- parts: [
4438
- `mt-${value}`,
4439
- `mr-${value}`,
4440
- `mb-${value}`,
4441
- `ml-${value}`
4442
- ],
4443
- replacement: `m-${value}`
4444
- },
4445
- {
4446
- parts: [`mt-${value}`, `mb-${value}`],
4447
- replacement: `my-${value}`
4448
- },
4449
- {
4450
- parts: [`ml-${value}`, `mr-${value}`],
4451
- replacement: `mx-${value}`
4452
- },
4453
- {
4454
- parts: [`mx-${value}`, `my-${value}`],
4455
- replacement: `m-${value}`
4456
- },
4457
- {
4458
- parts: [
4459
- `pt-${value}`,
4460
- `pr-${value}`,
4461
- `pb-${value}`,
4462
- `pl-${value}`
4463
- ],
4464
- replacement: `p-${value}`
4465
- },
4466
- {
4467
- parts: [`pt-${value}`, `pb-${value}`],
4468
- replacement: `py-${value}`
4469
- },
4470
- {
4471
- parts: [`pl-${value}`, `pr-${value}`],
4472
- replacement: `px-${value}`
4473
- },
4474
- {
4475
- parts: [`px-${value}`, `py-${value}`],
4476
- replacement: `p-${value}`
4477
- },
4478
- ...!INVALID_SIZE_VALUES.has(value) ? [{
4479
- parts: [`w-${value}`, `h-${value}`],
4480
- replacement: `size-${value}`
4481
- }] : [],
4482
- {
4483
- parts: [
4484
- `rounded-tl-${value}`,
4485
- `rounded-tr-${value}`,
4486
- `rounded-br-${value}`,
4487
- `rounded-bl-${value}`
4488
- ],
4489
- replacement: `rounded-${value}`
4490
- }
4491
- ];
4996
+ function declaredValues(cache, cls) {
4997
+ const values = /* @__PURE__ */ new Set();
4998
+ for (const decl of cache.getCssDeclarations(cls)) {
4999
+ if (decl.conditional) continue;
5000
+ values.add(decl.value);
5001
+ }
5002
+ return values.size > 0 ? values : null;
5003
+ }
5004
+ function sameValues(a, b) {
5005
+ if (a.size !== b.size) return false;
5006
+ for (const value of a) if (!b.has(value)) return false;
5007
+ return true;
5008
+ }
5009
+ /**
5010
+ * Would collapsing this family at this value keep the CSS identical?
5011
+ *
5012
+ * With a design system this is answered from the emitted declarations. Without
5013
+ * one it falls back to what is safe by construction, which is everything except
5014
+ * a named token on the one family whose parts read different namespaces.
5015
+ */
5016
+ function mergeIsSafe(family, value, cache) {
5017
+ const structurallySafe = NUMERIC_VALUE_RE.test(value) || isWrittenValue(value);
5018
+ if (!cache) {
5019
+ if (!family.perAxisNamespaces) return true;
5020
+ return structurallySafe || AXIS_SAFE_KEYWORDS.has(value);
5021
+ }
5022
+ if (!cache.isValid(`${family.to}-${value}`)) return false;
5023
+ if (structurallySafe) return true;
5024
+ const expected = declaredValues(cache, `${family.parts[0]}-${value}`);
5025
+ if (!expected) return false;
5026
+ for (let i = 1; i < family.parts.length; i++) {
5027
+ const actual = declaredValues(cache, `${family.parts[i]}-${value}`);
5028
+ if (!actual || !sameValues(expected, actual)) return false;
5029
+ }
5030
+ const replacement = declaredValues(cache, `${family.to}-${value}`);
5031
+ return replacement !== null && sameValues(expected, replacement);
4492
5032
  }
4493
5033
  const enforceShorthand = defineRule({
4494
5034
  meta: {
4495
5035
  type: "suggestion",
4496
5036
  docs: { description: "Enforce shorthand Tailwind CSS classes when all axes have the same value" },
4497
5037
  fixable: "code",
4498
- schema: [],
5038
+ schema: [{
5039
+ type: "object",
5040
+ properties: { entryPoint: { type: "string" } },
5041
+ additionalProperties: false
5042
+ }],
5043
+ defaultOptions: [{}],
4499
5044
  messages: { shorthand: "{{parts}} can be simplified to \"{{replacement}}\"." }
4500
5045
  },
4501
5046
  createOnce(context) {
5047
+ const getDS = createLazyLoader(context);
4502
5048
  function check(locations) {
5049
+ const ds = softGetDS(getDS);
5050
+ const cache = ds ? ds.cache : null;
4503
5051
  for (const loc of locations) {
4504
5052
  const split = splitClassesWithSeparators(loc.value);
4505
5053
  const classes = split.classes;
4506
5054
  if (classes.length < 2) continue;
4507
- const classSet = new Set(classes);
4508
- const variantValues = /* @__PURE__ */ new Set();
5055
+ const groups = /* @__PURE__ */ new Map();
4509
5056
  for (const cls of classes) {
4510
5057
  const { utility, variant } = splitUtilityAndVariant(cls);
4511
- const match = VALUE_RE.exec(splitImportant(utility).bare);
4512
- if (match) variantValues.add(`${variant}\0${match[1]}`);
5058
+ const { bare, position } = splitImportant(utility);
5059
+ const match = VALUE_RE.exec(bare);
5060
+ if (!match) continue;
5061
+ const [, part, value] = match;
5062
+ const key = `${variant}\0${position ?? ""}\0${value}`;
5063
+ let group = groups.get(key);
5064
+ if (!group) {
5065
+ group = {
5066
+ variant,
5067
+ position,
5068
+ value,
5069
+ byPart: /* @__PURE__ */ new Map()
5070
+ };
5071
+ groups.set(key, group);
5072
+ }
5073
+ group.byPart.set(part, cls);
4513
5074
  }
4514
- for (const variantValue of variantValues) {
4515
- const nul = variantValue.indexOf("\0");
4516
- const variant = variantValue.slice(0, nul);
4517
- const rules = createShorthandRules(variantValue.slice(nul + 1));
4518
- for (const rule of rules) {
4519
- const withVariant = (p) => `${variant}${p}`;
4520
- const hasImportantPrefix = rule.parts.every((p) => classSet.has(withVariant(`!${p}`)));
4521
- const hasImportantSuffix = !hasImportantPrefix && rule.parts.every((p) => classSet.has(withVariant(`${p}!`)));
4522
- const hasPlain = rule.parts.every((p) => classSet.has(withVariant(p)));
4523
- if (!hasImportantPrefix && !hasImportantSuffix && !hasPlain) continue;
4524
- const importantStart = hasImportantPrefix ? "!" : "";
4525
- const importantEnd = hasImportantSuffix ? "!" : "";
4526
- const matchParts = rule.parts.map((p) => withVariant(`${importantStart}${p}${importantEnd}`));
4527
- const remaining = classes.filter((c) => !matchParts.includes(c));
4528
- remaining.push(withVariant(`${importantStart}${rule.replacement}${importantEnd}`));
5075
+ for (const group of groups.values()) {
5076
+ if (group.byPart.size < 2) continue;
5077
+ const consumed = /* @__PURE__ */ new Set();
5078
+ for (const family of FAMILIES_BY_SIZE) {
5079
+ if (family.parts.some((part) => !group.byPart.has(part) || consumed.has(part))) continue;
5080
+ if (!mergeIsSafe(family, group.value, cache)) continue;
5081
+ const matched = family.parts.map((part) => group.byPart.get(part));
5082
+ const replacement = group.variant + reattachImportant(`${family.to}-${group.value}`, group.position);
5083
+ const remaining = classes.filter((cls) => !matched.includes(cls));
5084
+ if (!remaining.includes(replacement)) remaining.push(replacement);
5085
+ for (const part of family.parts) consumed.add(part);
4529
5086
  context.report({
4530
5087
  node: loc.node,
4531
5088
  messageId: "shorthand",
4532
5089
  data: {
4533
- parts: matchParts.map((p) => `"${p}"`).join(", "),
4534
- replacement: withVariant(`${importantStart}${rule.replacement}${importantEnd}`)
5090
+ parts: matched.map((p) => `"${p}"`).join(", "),
5091
+ replacement
4535
5092
  },
4536
5093
  fix(fixer) {
4537
5094
  return fixer.replaceTextRange(loc.range, preserveSpaces(loc, rebuildClassString(split, remaining)));
@@ -4560,7 +5117,8 @@ const LOGICAL_PHYSICAL_SCHEMA = {
4560
5117
  "block",
4561
5118
  "both"
4562
5119
  ]
4563
- }
5120
+ },
5121
+ entryPoint: { type: "string" }
4564
5122
  },
4565
5123
  additionalProperties: false
4566
5124
  };
@@ -4654,17 +5212,73 @@ const PHYSICAL_TO_LOGICAL_MAPPINGS = [
4654
5212
  from: "scroll-pr",
4655
5213
  to: "scroll-pe",
4656
5214
  axis: "inline"
5215
+ },
5216
+ {
5217
+ from: "float-left",
5218
+ to: "float-start",
5219
+ axis: "inline",
5220
+ exact: true
5221
+ },
5222
+ {
5223
+ from: "float-right",
5224
+ to: "float-end",
5225
+ axis: "inline",
5226
+ exact: true
5227
+ },
5228
+ {
5229
+ from: "clear-left",
5230
+ to: "clear-start",
5231
+ axis: "inline",
5232
+ exact: true
5233
+ },
5234
+ {
5235
+ from: "clear-right",
5236
+ to: "clear-end",
5237
+ axis: "inline",
5238
+ exact: true
5239
+ },
5240
+ {
5241
+ from: "text-left",
5242
+ to: "text-start",
5243
+ axis: "inline",
5244
+ exact: true
5245
+ },
5246
+ {
5247
+ from: "text-right",
5248
+ to: "text-end",
5249
+ axis: "inline",
5250
+ exact: true
4657
5251
  }
4658
5252
  ];
5253
+ /**
5254
+ * Extra sources for enforce-physical ONLY.
5255
+ *
5256
+ * `enforce-logical` rewrites `left-2` to `start-2`, the spelling Tailwind's own
5257
+ * docs use. `enforce-canonical`, asking the design system, then rewrites that to
5258
+ * `inset-s-2` — same CSS, canonical name. So a codebase that ran both ends up with
5259
+ * `inset-s-*`, and enforce-physical had no way back: its table only knew `start`.
5260
+ *
5261
+ * Kept out of the main table so inverting it doesn't change what enforce-logical
5262
+ * suggests (both spellings map to the same physical class, but only one of them
5263
+ * can be the recommendation).
5264
+ */
5265
+ const LOGICAL_INSET_ALIASES = [{
5266
+ from: "inset-s",
5267
+ to: "left",
5268
+ axis: "inline"
5269
+ }, {
5270
+ from: "inset-e",
5271
+ to: "right",
5272
+ axis: "inline"
5273
+ }];
4659
5274
  /** Invert a directional table. enforce-physical consumes this. */
4660
5275
  function invertAxisMappings(mappings) {
4661
5276
  return mappings.map((m) => ({
5277
+ ...m,
4662
5278
  from: m.to,
4663
- to: m.from,
4664
- axis: m.axis
5279
+ to: m.from
4665
5280
  }));
4666
5281
  }
4667
- Object.fromEntries(PHYSICAL_TO_LOGICAL_MAPPINGS.map((m) => [m.from, m.to]));
4668
5282
  /**
4669
5283
  * Build the `check` callback for a directional-rewrite rule. Both
4670
5284
  * enforce-logical and enforce-physical instantiate this with their own
@@ -4680,6 +5294,7 @@ function createDirectionalMapper(context, opts) {
4680
5294
  allowlist: compileRegexList(o?.allowlist),
4681
5295
  direction: o?.direction ?? "both"
4682
5296
  }));
5297
+ const getDS = createLazyLoader(context);
4683
5298
  function convertClass(cls) {
4684
5299
  const { allowlist, direction } = getState();
4685
5300
  if (matchesAny(cls, allowlist)) return null;
@@ -4687,24 +5302,26 @@ function createDirectionalMapper(context, opts) {
4687
5302
  const { bare: bareUtility, position } = splitImportant(utility);
4688
5303
  const negative = bareUtility.startsWith("-");
4689
5304
  const core = negative ? bareUtility.slice(1) : bareUtility;
4690
- for (const { from, to, axis } of opts.mappings) {
5305
+ for (const { from, to, axis, exact } of opts.mappings) {
4691
5306
  if (direction !== "both" && direction !== axis) continue;
4692
- if (core === from || core.startsWith(`${from}-`)) {
4693
- const suffix = core.slice(from.length);
4694
- return `${variant}${reattachImportant(`${negative ? "-" : ""}${to}${suffix}`, position)}`;
4695
- }
5307
+ if (!(core === from || !exact && core.startsWith(`${from}-`))) continue;
5308
+ const suffix = core.slice(from.length);
5309
+ return `${variant}${reattachImportant(`${negative ? "-" : ""}${to}${suffix}`, position)}`;
4696
5310
  }
4697
5311
  return null;
4698
5312
  }
4699
5313
  function check(locations) {
5314
+ const ds = softGetDS(getDS);
5315
+ const isUsable = makeReplacementGuard(ds ? ds.cache : null);
4700
5316
  for (const loc of locations) {
4701
5317
  const split = splitClassesWithSeparators(loc.value);
4702
5318
  const offending = split.classes.flatMap((cls) => {
4703
5319
  const converted = convertClass(cls);
4704
- return converted ? [{
5320
+ if (!converted || !isUsable(converted)) return [];
5321
+ return [{
4705
5322
  cls,
4706
5323
  replacement: converted
4707
- }] : [];
5324
+ }];
4708
5325
  });
4709
5326
  reportClassReplacements(context, loc, split, split.classes, offending, { messageId: opts.messageId });
4710
5327
  }
@@ -4755,7 +5372,7 @@ const enforcePhysical = defineRule({
4755
5372
  },
4756
5373
  createOnce(context) {
4757
5374
  const { check } = createDirectionalMapper(context, {
4758
- mappings: invertAxisMappings(PHYSICAL_TO_LOGICAL_MAPPINGS),
5375
+ mappings: [...invertAxisMappings(PHYSICAL_TO_LOGICAL_MAPPINGS), ...LOGICAL_INSET_ALIASES],
4759
5376
  messageId: "usePhysical"
4760
5377
  });
4761
5378
  return createExtractorVisitors(context, check);
@@ -4908,7 +5525,7 @@ const noArbitraryValue = defineRule({
4908
5525
  for (const loc of locations) {
4909
5526
  const classes = splitClasses(loc.value);
4910
5527
  for (const cls of classes) {
4911
- if (!hasArbitraryValue(cls)) continue;
5528
+ if (!utilityHasDynamicValue(cls)) continue;
4912
5529
  const utility = splitImportant(extractUtility(cls)).bare;
4913
5530
  if (isAllowed(utility)) continue;
4914
5531
  context.report({
@@ -5173,10 +5790,13 @@ const noDarkWithoutLight = defineRule({
5173
5790
  docs: { description: "Require a base (light) utility when using dark: (or other scheme) variant" },
5174
5791
  schema: [{
5175
5792
  type: "object",
5176
- properties: { variants: {
5177
- type: "array",
5178
- items: { type: "string" }
5179
- } },
5793
+ properties: {
5794
+ variants: {
5795
+ type: "array",
5796
+ items: { type: "string" }
5797
+ },
5798
+ entryPoint: { type: "string" }
5799
+ },
5180
5800
  additionalProperties: false
5181
5801
  }],
5182
5802
  defaultOptions: [{ variants: DEFAULT_VARIANTS }],
@@ -5184,85 +5804,211 @@ const noDarkWithoutLight = defineRule({
5184
5804
  },
5185
5805
  createOnce(context) {
5186
5806
  const getWatchedVariants = createLazyOptions(context, (o) => new Set(o?.variants ?? DEFAULT_VARIANTS));
5807
+ const getDS = createLazyLoader(context);
5808
+ const bareOf = (cls) => splitImportant(extractUtility(cls)).bare;
5187
5809
  function check(locations) {
5188
5810
  const watchedVariants = getWatchedVariants();
5811
+ const ds = softGetDS(getDS);
5812
+ const cache = ds ? ds.cache : null;
5189
5813
  for (const loc of locations) {
5190
5814
  const classes = splitClasses(loc.value);
5815
+ if (cache && ds) {
5816
+ let unresolved = null;
5817
+ for (const cls of classes) {
5818
+ const bare = bareOf(cls);
5819
+ if (cache.getCssProperties(bare).length > 0 || !isUserValued(bare)) continue;
5820
+ if (!unresolved) unresolved = [];
5821
+ unresolved.push(bare);
5822
+ }
5823
+ if (unresolved) try {
5824
+ resolveDeclarationsSync(ds.entryPoint, cache, unresolved);
5825
+ } catch (error) {
5826
+ if (!isFatalError(error)) throw error;
5827
+ debugLog(`declaration service unavailable, grouping by prefix only: ${String(error)}`);
5828
+ }
5829
+ }
5191
5830
  const basePrefixes = /* @__PURE__ */ new Set();
5831
+ const baseProperties = /* @__PURE__ */ new Set();
5192
5832
  const variantClasses = [];
5193
5833
  for (const cls of classes) {
5194
5834
  const variants = extractVariants(cls);
5195
5835
  const prefix = getUtilityPrefix(extractUtility(cls));
5196
- if (variants.some((v) => watchedVariants.has(v))) {
5197
- const variant = variants.find((v) => watchedVariants.has(v));
5198
- variantClasses.push({
5199
- cls,
5836
+ const properties = cache ? cache.getCssProperties(bareOf(cls)) : [];
5837
+ const variant = variants.find((v) => watchedVariants.has(v));
5838
+ if (variant !== void 0) variantClasses.push({
5839
+ cls,
5840
+ variant,
5841
+ prefix,
5842
+ properties
5843
+ });
5844
+ else {
5845
+ basePrefixes.add(prefix);
5846
+ for (const property of properties) baseProperties.add(property);
5847
+ }
5848
+ }
5849
+ for (const { cls, variant, prefix, properties } of variantClasses) {
5850
+ if (basePrefixes.has(prefix)) continue;
5851
+ if (properties.some((property) => baseProperties.has(property))) continue;
5852
+ context.report({
5853
+ node: loc.node,
5854
+ messageId: "missingBase",
5855
+ data: {
5856
+ className: cls,
5200
5857
  variant,
5201
5858
  prefix
5202
- });
5203
- } else basePrefixes.add(prefix);
5859
+ }
5860
+ });
5204
5861
  }
5205
- for (const { cls, variant, prefix } of variantClasses) if (!basePrefixes.has(prefix)) context.report({
5206
- node: loc.node,
5207
- messageId: "missingBase",
5208
- data: {
5209
- className: cls,
5210
- variant,
5211
- prefix
5212
- }
5213
- });
5214
5862
  }
5215
5863
  }
5216
5864
  return createExtractorVisitors(context, check);
5217
5865
  }
5218
5866
  });
5219
5867
  //#endregion
5868
+ //#region src/utils/color-literal.ts
5869
+ /**
5870
+ * Does this CSS value contain a hardcoded color literal, anywhere in it?
5871
+ *
5872
+ * `no-hardcoded-colors` used to answer that with `^`-anchored regexes over the
5873
+ * whole value, which only ever matched a value that IS a color. Every real
5874
+ * shorthand slipped through: `shadow-[0_1px_2px_#000]` carries a hardcoded black
5875
+ * that the rule promised to catch and didn't. Anchoring also forced a companion
5876
+ * list of "color-bearing utility prefixes" to keep the match plausible, and that
5877
+ * list drifted from Tailwind (it has `ring` but not `inset-ring`, `shadow` but not
5878
+ * `inset-shadow`, and no way to spell an arbitrary property like `[color:#f00]`).
5879
+ *
5880
+ * Scanning the value instead of anchoring to it drops both problems: the value
5881
+ * carries the color or it doesn't, whatever utility it is attached to.
5882
+ *
5883
+ * Two things must NOT count, and they are why this is a scanner rather than a
5884
+ * regex:
5885
+ * - quoted strings — `content-['#fff']` is the text `#fff`, not a color;
5886
+ * - `url()` contents — `fill-[url(#gradient)]` references an SVG node by id, the
5887
+ * single most common `#` in a Tailwind class that isn't a color.
5888
+ *
5889
+ * The notation set is exactly the one the rule documents (hex + the CSS color
5890
+ * functions). Named colors (`bg-[red]`) are deliberately absent: they were never
5891
+ * covered, and `currentColor`/`transparent`/`inherit` make that a separate
5892
+ * judgement call rather than a scan.
5893
+ */
5894
+ /** CSS color functions. `color-mix` is absent on purpose: its arguments are scanned. */
5895
+ const COLOR_FUNCTIONS = /* @__PURE__ */ new Set([
5896
+ "rgb",
5897
+ "rgba",
5898
+ "hsl",
5899
+ "hsla",
5900
+ "hwb",
5901
+ "lab",
5902
+ "lch",
5903
+ "oklab",
5904
+ "oklch",
5905
+ "color"
5906
+ ]);
5907
+ /** Hex digit counts CSS accepts: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`. */
5908
+ const HEX_LENGTHS = /* @__PURE__ */ new Set([
5909
+ 3,
5910
+ 4,
5911
+ 6,
5912
+ 8
5913
+ ]);
5914
+ function isHexDigit(ch) {
5915
+ return ch >= "0" && ch <= "9" || ch >= "a" && ch <= "f" || ch >= "A" && ch <= "F";
5916
+ }
5917
+ /**
5918
+ * `-` belongs to the identifier so `color-mix(` is not read as `color(`. `_` does
5919
+ * NOT: in a Tailwind arbitrary value an underscore stands for a space, so
5920
+ * `0_0_4px_rgb(…)` has to break into words or the function name never surfaces.
5921
+ */
5922
+ function isIdentChar(ch) {
5923
+ return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch >= "0" && ch <= "9" || ch === "-";
5924
+ }
5925
+ function isIdentStart(ch) {
5926
+ return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z";
5927
+ }
5928
+ /** Index just past the closing quote (or end of input on an unterminated string). */
5929
+ function skipQuoted(value, start) {
5930
+ const quote = value[start];
5931
+ let i = start + 1;
5932
+ while (i < value.length) {
5933
+ if (value[i] === "\\") {
5934
+ i += 2;
5935
+ continue;
5936
+ }
5937
+ if (value[i] === quote) return i + 1;
5938
+ i++;
5939
+ }
5940
+ return value.length;
5941
+ }
5942
+ /** Index just past the matching `)`, given `open` pointing at a `(`. */
5943
+ function skipBalanced(value, open) {
5944
+ let depth = 0;
5945
+ let i = open;
5946
+ while (i < value.length) {
5947
+ const ch = value[i];
5948
+ if (ch === "\"" || ch === "'") {
5949
+ i = skipQuoted(value, i);
5950
+ continue;
5951
+ }
5952
+ if (ch === "(") depth++;
5953
+ else if (ch === ")") {
5954
+ depth--;
5955
+ if (depth === 0) return i + 1;
5956
+ }
5957
+ i++;
5958
+ }
5959
+ return value.length;
5960
+ }
5961
+ function containsColorLiteral(value) {
5962
+ let i = 0;
5963
+ while (i < value.length) {
5964
+ const ch = value[i];
5965
+ if (ch === "\"" || ch === "'") {
5966
+ i = skipQuoted(value, i);
5967
+ continue;
5968
+ }
5969
+ if (ch === "#") {
5970
+ let end = i + 1;
5971
+ while (end < value.length && isHexDigit(value[end])) end++;
5972
+ if (HEX_LENGTHS.has(end - i - 1)) return true;
5973
+ i = end > i + 1 ? end : i + 1;
5974
+ continue;
5975
+ }
5976
+ if (isIdentStart(ch)) {
5977
+ const start = i;
5978
+ while (i < value.length && isIdentChar(value[i])) i++;
5979
+ if (value[i] !== "(") continue;
5980
+ const name = value.slice(start, i).toLowerCase();
5981
+ if (name === "url") {
5982
+ i = skipBalanced(value, i);
5983
+ continue;
5984
+ }
5985
+ if (COLOR_FUNCTIONS.has(name)) return true;
5986
+ continue;
5987
+ }
5988
+ i++;
5989
+ }
5990
+ return false;
5991
+ }
5992
+ //#endregion
5220
5993
  //#region src/rules/no-hardcoded-colors.ts
5221
- const COLOR_UTILITY_PREFIXES = [
5222
- "bg",
5223
- "text",
5224
- "border",
5225
- "border-t",
5226
- "border-b",
5227
- "border-l",
5228
- "border-r",
5229
- "border-s",
5230
- "border-e",
5231
- "border-x",
5232
- "border-y",
5233
- "outline",
5234
- "ring",
5235
- "ring-offset",
5236
- "shadow",
5237
- "accent",
5238
- "caret",
5239
- "fill",
5240
- "stroke",
5241
- "decoration",
5242
- "divide",
5243
- "placeholder",
5244
- "from",
5245
- "via",
5246
- "to"
5247
- ];
5248
- const HEX_RE = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
5249
- const RGB_RE = /^rgba?\s*\(/;
5250
- const HSL_RE = /^hsla?\s*\(/;
5251
- const OKLCH_RE = /^oklch\s*\(/;
5252
- const OKLAB_RE = /^oklab\s*\(/;
5253
- const LCH_RE = /^lch\s*\(/;
5254
- const LAB_RE = /^lab\s*\(/;
5255
- const HWB_RE = /^hwb\s*\(/;
5256
- const COLOR_RE = /^color\s*\(/;
5257
5994
  const VAR_REF_RE = /var\(\s*--[\w-]+/i;
5995
+ /**
5996
+ * Does the arbitrary value the user wrote carry a hardcoded colour?
5997
+ *
5998
+ * This used to be a set of `^`-anchored regexes plus a list of "colour-bearing
5999
+ * utility prefixes", and both halves leaked. The anchoring meant only a value
6000
+ * that IS a colour matched, so `shadow-[0_1px_2px_#000]` passed. The prefix list
6001
+ * had `ring` but not `inset-ring`, `shadow` but not `inset-shadow`, and no way to
6002
+ * spell an arbitrary property at all (`[color:#f00]`, `[--brand:#f00]`).
6003
+ *
6004
+ * Neither is needed: the value carries the colour or it doesn't, whatever utility
6005
+ * it is attached to. `containsColorLiteral` skips quoted strings and `url()`
6006
+ * contents, which is what keeps `content-['#fff']` and `fill-[url(#gradient)]` out.
6007
+ */
5258
6008
  function isHardcodedColor(value) {
5259
6009
  const trimmed = value.trim();
5260
6010
  if (VAR_REF_RE.test(trimmed)) return false;
5261
- return HEX_RE.test(trimmed) || RGB_RE.test(trimmed) || HSL_RE.test(trimmed) || OKLCH_RE.test(trimmed) || OKLAB_RE.test(trimmed) || LCH_RE.test(trimmed) || LAB_RE.test(trimmed) || HWB_RE.test(trimmed) || COLOR_RE.test(trimmed);
5262
- }
5263
- function isColorUtility(utility) {
5264
- for (const prefix of COLOR_UTILITY_PREFIXES) if (utility === prefix || utility.startsWith(`${prefix}-`)) return true;
5265
- return false;
6011
+ return containsColorLiteral(trimmed);
5266
6012
  }
5267
6013
  const noHardcodedColors = defineRule({
5268
6014
  meta: {
@@ -5288,8 +6034,6 @@ const noHardcodedColors = defineRule({
5288
6034
  for (const cls of classes) {
5289
6035
  if (allowlist.has(cls)) continue;
5290
6036
  if (!hasArbitraryValue(cls)) continue;
5291
- const utility = splitImportant(extractUtility(cls)).bare;
5292
- if (!isColorUtility(utility)) continue;
5293
6037
  const value = getArbitraryValue(cls);
5294
6038
  if (!value) continue;
5295
6039
  if (isHardcodedColor(value)) context.report({
@@ -5320,13 +6064,9 @@ const noContradictingVariants = defineRule({
5320
6064
  createOnce(context) {
5321
6065
  const getDS = createLazyLoader(context);
5322
6066
  function variantFactsLookup() {
5323
- try {
5324
- const ds = getDS();
5325
- return (variant) => ds.cache.getVariantFacts(variant);
5326
- } catch (err) {
5327
- if (!isFatalError(err)) throw err;
5328
- return () => void 0;
5329
- }
6067
+ const ds = softGetDS(getDS);
6068
+ if (!ds) return () => void 0;
6069
+ return (variant) => ds.cache.getVariantFacts(variant);
5330
6070
  }
5331
6071
  function check(locations) {
5332
6072
  const factsFor = variantFactsLookup();
@@ -5473,15 +6213,9 @@ const consistentVariantOrder = defineRule({
5473
6213
  const priorityByEntry = /* @__PURE__ */ new Map();
5474
6214
  const prefixByEntry = /* @__PURE__ */ new Map();
5475
6215
  function resolveForFile() {
5476
- let dsCache = null;
5477
- let entryKey = "";
5478
- try {
5479
- const ds = getDS();
5480
- dsCache = ds.cache;
5481
- entryKey = ds.entryPoint;
5482
- } catch (err) {
5483
- if (!isFatalError(err)) throw err;
5484
- }
6216
+ const ds = softGetDS(getDS);
6217
+ const dsCache = ds ? ds.cache : null;
6218
+ const entryKey = ds ? ds.entryPoint : "";
5485
6219
  let priorityOf = priorityByEntry.get(entryKey);
5486
6220
  if (!priorityOf) {
5487
6221
  priorityOf = buildPriority(getOptions().order, dsCache);
@@ -5725,6 +6459,106 @@ function detectRawVariable(utility) {
5725
6459
  };
5726
6460
  return null;
5727
6461
  }
6462
+ const preferThemeTokens = defineRule({
6463
+ meta: {
6464
+ type: "suggestion",
6465
+ docs: { description: "Prefer named theme-token utilities over raw CSS variable references when a matching utility exists" },
6466
+ fixable: "code",
6467
+ schema: [{
6468
+ type: "object",
6469
+ properties: { entryPoint: { type: "string" } },
6470
+ additionalProperties: false
6471
+ }],
6472
+ hasSuggestions: true,
6473
+ defaultOptions: [{}],
6474
+ messages: {
6475
+ preferNamed: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named theme token.",
6476
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
6477
+ ...DS_UNAVAILABLE_MESSAGE
6478
+ }
6479
+ },
6480
+ createOnce(context) {
6481
+ const getDS = createLazyLoader(context);
6482
+ function check(locations) {
6483
+ if (locations.length === 0) return;
6484
+ const ds = safeGetDS(getDS, context, locations[0].node);
6485
+ if (!ds) return;
6486
+ const { cache } = ds;
6487
+ for (const loc of locations) {
6488
+ const split = splitClassesWithSeparators(loc.value);
6489
+ const offending = split.classes.flatMap((cls) => {
6490
+ const { utility, variant } = splitUtilityAndVariant(cls);
6491
+ const { bare: bareUtility, position } = splitImportant(utility);
6492
+ const match = detectRawVariable(bareUtility);
6493
+ if (!match) return [];
6494
+ const candidate = `${match.prefix}-${match.varName}${match.modifier}`;
6495
+ if (!cache.isValid(candidate)) return [];
6496
+ const target = `--${match.varName}`;
6497
+ const baseCandidate = `${match.prefix}-${match.varName}`;
6498
+ if (!cache.getCssDeclarations(baseCandidate).some((decl) => [...decl.readsVars, ...decl.readsFallbackVars].some((read) => cache.themeVarResolvesTo(read, target))) && cache.definesVar(target)) return [];
6499
+ const namedEquivalent = cache.getNamedEquivalent(bareUtility);
6500
+ if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) return [];
6501
+ return [{
6502
+ cls,
6503
+ replacement: variant + reattachImportant(candidate, position)
6504
+ }];
6505
+ });
6506
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "preferNamed" });
6507
+ }
6508
+ }
6509
+ return createExtractorVisitors(context, check);
6510
+ }
6511
+ });
6512
+ //#endregion
6513
+ //#region src/rules/prefer-scale-token.ts
6514
+ /** A length or plain number. Anything else can't be compared arithmetically. */
6515
+ const LENGTH_RE = /^(-?\d*\.?\d+)(rem|px|em)?$/;
6516
+ /**
6517
+ * Parse a CSS length. `em` is treated as `rem`, which is what it is at the root
6518
+ * and the only interpretation available without a layout.
6519
+ */
6520
+ function measure(value, rootFontSize) {
6521
+ const match = LENGTH_RE.exec(value.trim());
6522
+ if (!match) return null;
6523
+ const n = Number.parseFloat(match[1]);
6524
+ if (!Number.isFinite(n)) return null;
6525
+ switch (match[2]) {
6526
+ case "rem":
6527
+ case "em": return {
6528
+ px: n * rootFontSize,
6529
+ unitless: false
6530
+ };
6531
+ case "px": return {
6532
+ px: n,
6533
+ unitless: false
6534
+ };
6535
+ case void 0: return {
6536
+ px: n,
6537
+ unitless: true
6538
+ };
6539
+ default: return null;
6540
+ }
6541
+ }
6542
+ /**
6543
+ * Same value, allowing for float noise (`0.875rem` × 16 = 13.999999999999998).
6544
+ * A unitless number and a length are never the same value, whatever the digits.
6545
+ */
6546
+ function sameMeasure(a, b) {
6547
+ return a.unitless === b.unitless && Math.abs(a.px - b.px) < 1e-4;
6548
+ }
6549
+ /**
6550
+ * Is `n` a whole number of `step`s? `10 / 0.5` is exact in binary, `0.3 / 0.1`
6551
+ * is not, so the remainder is compared with a tolerance rather than to zero.
6552
+ */
6553
+ function isOnStep(n, step) {
6554
+ if (step <= 0) return false;
6555
+ const steps = n / step;
6556
+ return Math.abs(steps - Math.round(steps)) < 1e-4;
6557
+ }
6558
+ /** Trailing zeros make `p-2.50`, which is not what Tailwind calls the class. */
6559
+ function formatStep(n) {
6560
+ return String(Number.parseFloat(n.toFixed(4)));
6561
+ }
5728
6562
  //#endregion
5729
6563
  //#region src/index.ts
5730
6564
  const plugin = definePlugin({
@@ -5752,26 +6586,77 @@ const plugin = definePlugin({
5752
6586
  "consistent-variant-order": consistentVariantOrder,
5753
6587
  "enforce-consistent-line-wrapping": enforceConsistentLineWrapping,
5754
6588
  "no-unnecessary-arbitrary-value": noUnnecessaryArbitraryValue,
5755
- "prefer-theme-tokens": defineRule({
6589
+ "prefer-theme-tokens": preferThemeTokens,
6590
+ "prefer-scale-token": defineRule({
5756
6591
  meta: {
5757
6592
  type: "suggestion",
5758
- docs: { description: "Prefer named theme-token utilities over raw CSS variable references when a matching utility exists" },
5759
- fixable: "code",
6593
+ docs: { description: "Prefer the scale step or theme token a hardcoded value is numerically equal to" },
6594
+ hasSuggestions: true,
5760
6595
  schema: [{
5761
6596
  type: "object",
5762
- properties: { entryPoint: { type: "string" } },
6597
+ properties: {
6598
+ entryPoint: { type: "string" },
6599
+ step: { type: "number" },
6600
+ allow: {
6601
+ type: "array",
6602
+ items: { type: "string" }
6603
+ }
6604
+ },
5763
6605
  additionalProperties: false
5764
6606
  }],
5765
- hasSuggestions: true,
5766
6607
  defaultOptions: [{}],
5767
6608
  messages: {
5768
- preferNamed: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named theme token.",
6609
+ 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.",
5769
6610
  suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
5770
6611
  ...DS_UNAVAILABLE_MESSAGE
5771
6612
  }
5772
6613
  },
5773
6614
  createOnce(context) {
5774
6615
  const getDS = createLazyLoader(context);
6616
+ const getOptions = createLazyOptions(context, (o) => ({
6617
+ step: typeof o?.step === "number" ? o.step : null,
6618
+ allow: o?.allow ?? []
6619
+ }));
6620
+ let _rem = null;
6621
+ function rootFontSize() {
6622
+ if (_rem === null) _rem = rootFontSizeFromSettings(safeSettings(context));
6623
+ return _rem;
6624
+ }
6625
+ /**
6626
+ * The class this literal could have been written as, or null.
6627
+ *
6628
+ * Two families, in order of preference: a named theme token whose value
6629
+ * matches (`rounded-[0.5rem]` → `rounded-lg`), then a step of the spacing
6630
+ * scale (`p-[10px]` → `p-2.5`). Both come from data the precompute derived
6631
+ * from the design system, so neither is a name table.
6632
+ */
6633
+ function equivalentOf(cache, bare) {
6634
+ const { step: stepOverride, allow } = getOptions();
6635
+ if (allow.some((prefix) => bare.startsWith(prefix))) return null;
6636
+ if (cache.getNamedEquivalent(bare)) return null;
6637
+ const value = getArbitraryValue(bare);
6638
+ if (value === null) return null;
6639
+ const written = measure(value, rootFontSize());
6640
+ if (written === null) return null;
6641
+ const open = bare.indexOf("[");
6642
+ if (open <= 0 || bare[open - 1] !== "-") return null;
6643
+ const prefix = bare.slice(0, open - 1);
6644
+ if (!prefix) return null;
6645
+ for (const [literal, className] of cache.tokenValuesFor(prefix)) {
6646
+ const token = measure(literal, rootFontSize());
6647
+ if (token !== null && sameMeasure(written, token)) return className;
6648
+ }
6649
+ if (!cache.readsScale(prefix)) return null;
6650
+ const scale = cache.scale;
6651
+ if (!scale) return null;
6652
+ const unit = measure(scale.unit, rootFontSize());
6653
+ if (unit === null || unit.px <= 0 || unit.unitless !== written.unitless) return null;
6654
+ const steps = written.px / unit.px;
6655
+ if (steps < 0) return null;
6656
+ if (!isOnStep(steps, stepOverride ?? scale.step)) return null;
6657
+ const candidate = `${prefix}-${formatStep(steps)}`;
6658
+ return cache.isValid(candidate) ? candidate : null;
6659
+ }
5775
6660
  function check(locations) {
5776
6661
  if (locations.length === 0) return;
5777
6662
  const ds = safeGetDS(getDS, context, locations[0].node);
@@ -5779,24 +6664,33 @@ const plugin = definePlugin({
5779
6664
  const { cache } = ds;
5780
6665
  for (const loc of locations) {
5781
6666
  const split = splitClassesWithSeparators(loc.value);
5782
- const offending = split.classes.flatMap((cls) => {
6667
+ for (const cls of split.classes) {
6668
+ if (!utilityHasDynamicValue(cls)) continue;
5783
6669
  const { utility, variant } = splitUtilityAndVariant(cls);
5784
- const { bare: bareUtility, position } = splitImportant(utility);
5785
- const match = detectRawVariable(bareUtility);
5786
- if (!match) return [];
5787
- const candidate = `${match.prefix}-${match.varName}${match.modifier}`;
5788
- if (!cache.isValid(candidate)) return [];
5789
- const target = `--${match.varName}`;
5790
- const baseCandidate = `${match.prefix}-${match.varName}`;
5791
- if (!cache.getCssDeclarations(baseCandidate).some((decl) => [...decl.readsVars, ...decl.readsFallbackVars].some((read) => cache.themeVarResolvesTo(read, target))) && cache.definesVar(target)) return [];
5792
- const namedEquivalent = cache.getNamedEquivalent(bareUtility);
5793
- if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) return [];
5794
- return [{
5795
- cls,
5796
- replacement: variant + reattachImportant(candidate, position)
5797
- }];
5798
- });
5799
- reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "preferNamed" });
6670
+ const { bare, position } = splitImportant(utility);
6671
+ const equivalent = equivalentOf(cache, bare);
6672
+ if (!equivalent) continue;
6673
+ const replacement = variant + reattachImportant(equivalent, position);
6674
+ const fixedValue = rebuildClassString(split, split.classes.map((c) => c === cls ? replacement : c));
6675
+ context.report({
6676
+ node: loc.node,
6677
+ messageId: "preferToken",
6678
+ data: {
6679
+ className: cls,
6680
+ replacement
6681
+ },
6682
+ suggest: [{
6683
+ messageId: "suggestReplace",
6684
+ data: {
6685
+ className: cls,
6686
+ replacement
6687
+ },
6688
+ fix(fixer) {
6689
+ return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
6690
+ }
6691
+ }]
6692
+ });
6693
+ }
5800
6694
  }
5801
6695
  }
5802
6696
  return createExtractorVisitors(context, check);