oxlint-tailwindcss 1.2.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -2,12 +2,32 @@ import { createRequire } from "node:module";
2
2
  import { definePlugin, defineRule } from "@oxlint/plugins";
3
3
  import { Worker, threadId } from "node:worker_threads";
4
4
  import { createHash } from "node:crypto";
5
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync } from "node:fs";
5
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync } from "node:fs";
6
6
  import { dirname, join, relative, resolve } from "node:path";
7
- import { tmpdir } from "node:os";
7
+ import { tmpdir, userInfo } from "node:os";
8
8
  //#region \0rolldown/runtime.js
9
9
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
10
10
  //#endregion
11
+ //#region src/utils/allowlist.ts
12
+ /**
13
+ * Shared regex-allowlist helpers used by rules that accept an `allowlist`
14
+ * option of regex source strings (currently enforce-logical / enforce-physical).
15
+ *
16
+ * Invalid regex sources are skipped rather than thrown so a typo in one
17
+ * pattern doesn't blow up the entire lint run.
18
+ */
19
+ function compileRegexList(patterns) {
20
+ if (!patterns || patterns.length === 0) return [];
21
+ const compiled = [];
22
+ for (const p of patterns) try {
23
+ compiled.push(new RegExp(p));
24
+ } catch {}
25
+ return compiled;
26
+ }
27
+ function matchesAny(value, list) {
28
+ return list.some((re) => re.test(value));
29
+ }
30
+ //#endregion
11
31
  //#region src/utils/extractors.ts
12
32
  /**
13
33
  * Preserves leading/trailing spaces in fixed class strings for template literals.
@@ -85,7 +105,7 @@ function getExtractorConfig(context) {
85
105
  attributes: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.attributes, tw.attributes, exclude?.attributes),
86
106
  callees: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.callees, tw.callees, exclude?.callees),
87
107
  tags: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.tags, tw.tags, exclude?.tags),
88
- variablePatterns: [...filteredPatterns, ...(tw.variablePatterns ?? []).map((p) => new RegExp(p))]
108
+ variablePatterns: [...filteredPatterns, ...compileRegexList(tw.variablePatterns)]
89
109
  };
90
110
  configCache.set(context, resolved);
91
111
  return resolved;
@@ -356,6 +376,9 @@ function getCalleeName(node) {
356
376
  }
357
377
  //#endregion
358
378
  //#region src/utils/class-splitter.ts
379
+ function isWhitespace(char) {
380
+ return char === " " || char === " " || char === "\n" || char === "\r" || char === "\f" || char === "\v";
381
+ }
359
382
  /**
360
383
  * Splits a Tailwind class string respecting:
361
384
  * - Nested brackets: bg-[url('...')], h-[calc(100%+2rem)]
@@ -378,9 +401,9 @@ function splitClasses(classString) {
378
401
  }
379
402
  if (!inSingleQuote && !inDoubleQuote) {
380
403
  if (char === "[") bracketDepth++;
381
- if (char === "]") bracketDepth--;
404
+ if (char === "]") bracketDepth = Math.max(0, bracketDepth - 1);
382
405
  }
383
- if (/\s/.test(char) && bracketDepth === 0) {
406
+ if (isWhitespace(char) && bracketDepth === 0) {
384
407
  if (current.length > 0) {
385
408
  classes.push(current);
386
409
  current = "";
@@ -407,9 +430,9 @@ function splitClassesWithSeparators(classString) {
407
430
  }
408
431
  if (!inSingleQuote && !inDoubleQuote) {
409
432
  if (char === "[") bracketDepth++;
410
- if (char === "]") bracketDepth--;
433
+ if (char === "]") bracketDepth = Math.max(0, bracketDepth - 1);
411
434
  }
412
- if (/\s/.test(char) && bracketDepth === 0) {
435
+ if (isWhitespace(char) && bracketDepth === 0) {
413
436
  if (current.length > 0) {
414
437
  classes.push(current);
415
438
  separators.push(currentSep);
@@ -695,6 +718,52 @@ function reattachImportant(bare, position) {
695
718
  if (position === "suffix") return `${bare}!`;
696
719
  return bare;
697
720
  }
721
+ /**
722
+ * Pseudo-element variants. They select a generated box (`::before`, `::marker`,
723
+ * …) rather than the element itself, so they must sit innermost in the variant
724
+ * chain (closest to the utility). Canonical home shared by
725
+ * `consistent-variant-order` (partitions them last) and
726
+ * `no-contradicting-variants` (they can't contradict a base class).
727
+ */
728
+ const PSEUDO_ELEMENT_VARIANTS = new Set([
729
+ "before",
730
+ "after",
731
+ "file",
732
+ "placeholder",
733
+ "selection",
734
+ "marker",
735
+ "backdrop",
736
+ "first-line",
737
+ "first-letter",
738
+ "details-content"
739
+ ]);
740
+ function isPseudoElementVariant(variant) {
741
+ return PSEUDO_ELEMENT_VARIANTS.has(variant);
742
+ }
743
+ /**
744
+ * Selector barriers: variants that re-point the selector at a *different*
745
+ * element than the ones around them — child (`*`), descendant (`**`),
746
+ * arbitrary selectors (`[&>svg]`) and compound child selectors (`*:data-[…]`).
747
+ *
748
+ * Unlike pseudo-elements, these are NOT free to move to the end of the chain:
749
+ * `hover:*:flex` (`&:hover > *`) and `*:hover:flex` (`& > *:hover`) target
750
+ * different elements. `consistent-variant-order` treats them as hard
751
+ * reordering barriers — variants never cross them.
752
+ */
753
+ function isSelectorBarrier(variant) {
754
+ if (variant === "*" || variant === "**") return true;
755
+ if (variant.startsWith("[") && variant.endsWith("]")) return true;
756
+ if (variant.startsWith("*:")) return true;
757
+ return false;
758
+ }
759
+ /**
760
+ * Whether a variant changes the selector target (pseudo-element OR selector
761
+ * barrier). Such variants don't impose a condition on the same element, so they
762
+ * can't make a variant class contradict/duplicate a base class.
763
+ */
764
+ function changesTarget(variant) {
765
+ return isPseudoElementVariant(variant) || isSelectorBarrier(variant);
766
+ }
698
767
  //#endregion
699
768
  //#region src/utils/floating-point.ts
700
769
  /**
@@ -1121,6 +1190,12 @@ function signalError(e) {
1121
1190
  Atomics.store(control, 2, -1);
1122
1191
  Atomics.notify(control, 2);
1123
1192
  }
1193
+ // Everything below — including the top-level require()s — runs inside this try
1194
+ // so any SYNCHRONOUS module-scope failure (a broken @tailwindcss/node install,
1195
+ // missing fs/path) is routed through signalError. Without it the worker would
1196
+ // die unsignaled and the main thread would block until the full timeout, then
1197
+ // report a misleading "timed out" instead of the real cause.
1198
+ try {
1124
1199
  // Resolve @tailwindcss/node via an absolute path passed in by the parent —
1125
1200
  // bare-specifier lookup from the worker's cwd fails under pnpm strict
1126
1201
  // workspaces (the module lives under node_modules/.pnpm/... which is not on the
@@ -1238,6 +1313,39 @@ async function main() {
1238
1313
  const dash = cls.lastIndexOf('-');
1239
1314
  if (dash > 0) knownPrefixes.add(cls.slice(0, dash));
1240
1315
  }
1316
+ // Curated static utilities valid in v4 but absent from getClassList() (#37).
1317
+ // These are special-cased in Tailwind's compiler, so they appear in neither
1318
+ // getClassList() NOR the utility registry (\`utilities.keys('static')\`) — only
1319
+ // an explicit probe surfaces them:
1320
+ // - \`@container-size\` (\`container-type: size\`) — sibling of the enumerated
1321
+ // \`@container\` / \`@container-normal\`; was flagged as a typo of \`contain-size\`.
1322
+ // - \`filter-none\` / \`backdrop-filter-none\` (\`filter: none\`) — the reset
1323
+ // utilities; their functional bases enumerate values but omit \`none\`.
1324
+ // - \`max-w-screen\` (\`max-width: 100vw\`).
1325
+ // Validated via candidatesToCss (self-prunes on any Tailwind version that doesn't
1326
+ // emit them) and their CSS is captured so the cssProps phase below treats them
1327
+ // exactly like their getClassList siblings — otherwise no-conflicting-classes
1328
+ // would flag \`@container @container-normal\` but silently accept
1329
+ // \`@container @container-size\`. Named forms (\`@container-size/main\`) are covered
1330
+ // by the slash-modifier path in cache.isValid once the base lands in validClasses.
1331
+ const staticExtras = [
1332
+ '@container-size',
1333
+ 'filter-none',
1334
+ 'backdrop-filter-none',
1335
+ 'max-w-screen',
1336
+ ].filter((c) => !validSet.has(c));
1337
+ const staticExtraCss = {};
1338
+ if (staticExtras.length > 0) {
1339
+ const staticResults = ds.candidatesToCss(staticExtras.map(pfx));
1340
+ for (let i = 0; i < staticExtras.length; i++) {
1341
+ if (staticResults[i] != null) {
1342
+ validClasses.push(staticExtras[i]);
1343
+ validSet.add(staticExtras[i]);
1344
+ staticExtraCss[staticExtras[i]] = staticResults[i];
1345
+ }
1346
+ }
1347
+ }
1348
+
1241
1349
  const extraCandidates = [];
1242
1350
  const breakpoints = ['sm', 'md', 'lg', 'xl', '2xl'];
1243
1351
  for (const prefix of knownPrefixes) {
@@ -1259,6 +1367,27 @@ async function main() {
1259
1367
  }
1260
1368
  }
1261
1369
 
1370
+ // Negative variants of utilities that support them (#37). getClassList()
1371
+ // enumerates negatives for most (\`-m-4\`, \`-translate-x-2\`) but omits a few
1372
+ // (\`-col-1\`, \`-row-1\`, \`-hue-rotate-45\`, \`-backdrop-hue-rotate-45\`). Probe
1373
+ // \`-<prefix>-1\` for every known prefix lacking negative coverage; candidatesToCss
1374
+ // self-prunes utilities that reject negatives (\`-p-1\` → null), so only genuinely
1375
+ // negative-capable prefixes land in validClasses, giving isValid's / getOrder's
1376
+ // numeric-prefix heuristic the \`-<prefix>\` it needs to accept any \`-<prefix>-<n>\`.
1377
+ const negativeProbes = [];
1378
+ for (const prefix of knownPrefixes) {
1379
+ if (!knownPrefixes.has('-' + prefix)) negativeProbes.push('-' + prefix + '-1');
1380
+ }
1381
+ if (negativeProbes.length > 0) {
1382
+ const negResults = ds.candidatesToCss(negativeProbes.map(pfx));
1383
+ for (let i = 0; i < negativeProbes.length; i++) {
1384
+ if (negResults[i] != null && !validSet.has(negativeProbes[i])) {
1385
+ validClasses.push(negativeProbes[i]);
1386
+ validSet.add(negativeProbes[i]);
1387
+ }
1388
+ }
1389
+ }
1390
+
1262
1391
  // Marker classes: group/peer don't produce CSS but enable group-hover:/peer-checked: variants
1263
1392
  const allVariants = ds.getVariants();
1264
1393
  for (const v of allVariants) {
@@ -1305,6 +1434,11 @@ async function main() {
1305
1434
  'decoration-clone', 'decoration-slice',
1306
1435
  'bg-gradient-to-t', 'bg-gradient-to-tr', 'bg-gradient-to-r', 'bg-gradient-to-br',
1307
1436
  'bg-gradient-to-b', 'bg-gradient-to-bl', 'bg-gradient-to-l', 'bg-gradient-to-tl',
1437
+ // v3 background/object-position spellings reordered in v4 (#37):
1438
+ // \`bg-left-top\` -> \`bg-top-left\`. canonicalizeCandidates rewrites them, so
1439
+ // enforce-canonical suggests the v4 form and no-unknown-classes accepts them.
1440
+ 'bg-left-top', 'bg-right-top', 'bg-left-bottom', 'bg-right-bottom',
1441
+ 'object-left-top', 'object-right-top', 'object-left-bottom', 'object-right-bottom',
1308
1442
  ];
1309
1443
  for (const cls of validClasses) {
1310
1444
  if (cls.startsWith('inset-s-')) legacyCandidates.push('start-' + cls.slice(8));
@@ -1433,6 +1567,14 @@ async function main() {
1433
1567
  }
1434
1568
  }
1435
1569
 
1570
+ // cssProps for the curated static extras (#37) so they participate in conflict
1571
+ // detection exactly like their getClassList siblings (e.g. \`@container-size\` and
1572
+ // \`@container\` both declaring \`container-type\`).
1573
+ for (const name in staticExtraCss) {
1574
+ const props = extractRootCssProps(staticExtraCss[name], pfx(name));
1575
+ if (props.length > 0) cssProps[name] = props;
1576
+ }
1577
+
1436
1578
  // Variant ordering from the design system
1437
1579
  const variantOrder = {};
1438
1580
  const variants = ds.getVariants();
@@ -1511,8 +1653,20 @@ async function main() {
1511
1653
  main()
1512
1654
  .then(() => { Atomics.store(control, 2, 1); Atomics.notify(control, 2); })
1513
1655
  .catch((e) => signalError(e));
1656
+ } catch (e) {
1657
+ signalError(e);
1658
+ }
1514
1659
  `;
1515
- const CACHE_DIR = join(tmpdir(), "oxlint-tailwindcss");
1660
+ function cacheDirName() {
1661
+ try {
1662
+ const info = userInfo();
1663
+ const id = typeof info.uid === "number" && info.uid >= 0 ? String(info.uid) : info.username;
1664
+ return `oxlint-tailwindcss-${String(id).replace(/[^a-zA-Z0-9_-]/g, "_")}`;
1665
+ } catch {
1666
+ return "oxlint-tailwindcss";
1667
+ }
1668
+ }
1669
+ const CACHE_DIR = join(tmpdir(), cacheDirName());
1516
1670
  /**
1517
1671
  * Cache key derived from:
1518
1672
  * - md5(PRECOMPUTE_SCRIPT): auto-invalidates when our precompute logic changes,
@@ -1531,17 +1685,73 @@ const CACHE_KEY = computeCacheKey(PRECOMPUTE_SCRIPT, TAILWIND_NODE_VERSION);
1531
1685
  function computeContentHash(content) {
1532
1686
  return createHash("md5").update(`${CACHE_KEY}:${content}`).digest("hex");
1533
1687
  }
1688
+ const IMPORT_RE = /@import\s+(?:url\(\s*)?['"]([^'"]+)['"]/g;
1689
+ /**
1690
+ * Concatenate the entry CSS with the content of its locally-imported files, so
1691
+ * the cache key invalidates when an `@import`'d file changes — not only when the
1692
+ * entry itself does (DS-A2). Without this, editing a `@theme`/component file
1693
+ * pulled in via `@import "./theme.css"` served a stale design system until the
1694
+ * entry was touched or the Tailwind version changed.
1695
+ *
1696
+ * Resolves RELATIVE imports (`./`, `../`) recursively up to a small depth;
1697
+ * package imports (`@import "tailwindcss"`, `tw-animate-css`) are already
1698
+ * covered by the `@tailwindcss/node` version baked into CACHE_KEY. Best-effort:
1699
+ * an unreadable import contributes nothing (it can't affect the DS either).
1700
+ */
1701
+ function hashableContent(entryPath, entryContent) {
1702
+ const parts = [entryContent];
1703
+ const seen = new Set([resolve(entryPath)]);
1704
+ const visit = (cssPath, content, depth) => {
1705
+ if (depth <= 0) return;
1706
+ const baseDir = dirname(cssPath);
1707
+ IMPORT_RE.lastIndex = 0;
1708
+ const specifiers = [];
1709
+ let m;
1710
+ while ((m = IMPORT_RE.exec(content)) !== null) if (m[1].startsWith(".")) specifiers.push(m[1]);
1711
+ for (const spec of specifiers) {
1712
+ const importPath = resolve(baseDir, spec.split("?")[0]);
1713
+ if (seen.has(importPath)) continue;
1714
+ seen.add(importPath);
1715
+ let importContent;
1716
+ try {
1717
+ importContent = readFileSync(importPath, "utf-8");
1718
+ } catch {
1719
+ continue;
1720
+ }
1721
+ parts.push(importContent);
1722
+ visit(importPath, importContent, depth - 1);
1723
+ }
1724
+ };
1725
+ visit(resolve(entryPath), entryContent, 4);
1726
+ return parts.join("\0");
1727
+ }
1534
1728
  function getContentCachePath(contentHash) {
1535
1729
  return join(CACHE_DIR, `${contentHash}.json`);
1536
1730
  }
1731
+ /**
1732
+ * Minimal shape check for a cache payload. Guards against (a) a poisoned file
1733
+ * planted by a local attacker and (b) a corrupt/half-written or version-skewed
1734
+ * file. A `{}` that is valid JSON but missing fields would otherwise blow up
1735
+ * later in `DesignSystemCache.fromPrecomputed` with a raw TypeError that isn't
1736
+ * plugin-fatal, breaking the lint with no diagnostic. We don't deep-validate
1737
+ * every entry — just enough that `fromPrecomputed` can rely on the fields.
1738
+ */
1739
+ function isPrecomputedData(data) {
1740
+ if (typeof data !== "object" || data === null) return false;
1741
+ const d = data;
1742
+ const isObject = (v) => typeof v === "object" && v !== null;
1743
+ return Array.isArray(d.validClasses) && Array.isArray(d.componentClasses) && typeof d.prefix === "string" && isObject(d.canonical) && isObject(d.order) && isObject(d.cssProps) && isObject(d.variantOrder) && isObject(d.arbitraryEquivalents);
1744
+ }
1537
1745
  function tryReadCache(cachePath) {
1538
1746
  const raw = tryReadRawCache(cachePath);
1539
1747
  if (raw === null) return null;
1748
+ let data;
1540
1749
  try {
1541
- return JSON.parse(raw);
1750
+ data = JSON.parse(raw);
1542
1751
  } catch {
1543
1752
  return null;
1544
1753
  }
1754
+ return isPrecomputedData(data) ? data : null;
1545
1755
  }
1546
1756
  function tryReadRawCache(cachePath) {
1547
1757
  try {
@@ -1568,6 +1778,23 @@ function tryUnlink(path) {
1568
1778
  unlinkSync(path);
1569
1779
  } catch {}
1570
1780
  }
1781
+ /**
1782
+ * Reclaim a stale lock by exclusive rename rather than unlink (DS-M1). Two
1783
+ * waiters that both judge the lock stale would otherwise both `unlink` it — and
1784
+ * the second unlink could delete a FRESH lock a third isolate just created,
1785
+ * letting two precomputes run in parallel (the very amplification the lock
1786
+ * exists to prevent, #24). `renameSync` moves the file atomically: only one
1787
+ * waiter wins the move; the loser gets ENOENT and loops back to re-check.
1788
+ */
1789
+ function reclaimStaleLock(lockPath) {
1790
+ const reclaimPath = `${lockPath}.reclaim.${process.pid}.${threadId}.${precomputeSeq++}`;
1791
+ try {
1792
+ renameSync(lockPath, reclaimPath);
1793
+ } catch {
1794
+ return;
1795
+ }
1796
+ tryUnlink(reclaimPath);
1797
+ }
1571
1798
  /** control[2] — the worker's ready/done signal (0=loading, 1=done, -1=error). */
1572
1799
  const PRECOMPUTE_SIGNAL_INDEX = 2;
1573
1800
  const ERR_BUFFER_SIZE = 64 * 1024;
@@ -1620,15 +1847,12 @@ function runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeo
1620
1847
  } catch (cause) {
1621
1848
  throw precomputeLoadError(resolvedPath, cause);
1622
1849
  }
1623
- let workerError;
1624
- worker.on("error", (err) => {
1625
- workerError = err;
1626
- });
1850
+ worker.on("error", () => {});
1627
1851
  try {
1628
1852
  if (Atomics.wait(control, PRECOMPUTE_SIGNAL_INDEX, 0, timeout) === "timed-out") throw new DesignSystemLoadError(`Timed out precomputing design system from "${resolvedPath}" after ${timeout}ms.`, "Raise `settings.tailwindcss.timeout` if your machine or CI runner is slow, or verify the CSS imports resolve.");
1629
1853
  if (control[PRECOMPUTE_SIGNAL_INDEX] === -1) {
1630
1854
  const len = errLengthView.getUint32(0);
1631
- throw precomputeLoadError(resolvedPath, len > 0 ? new Error(Buffer.from(errDataArea.slice(0, len)).toString("utf-8")) : workerError);
1855
+ throw precomputeLoadError(resolvedPath, len > 0 ? new Error(Buffer.from(errDataArea.slice(0, len)).toString("utf-8")) : /* @__PURE__ */ new Error("precompute worker exited without reporting a cause (it may have been killed by the OS, e.g. under memory pressure)"));
1632
1856
  }
1633
1857
  } finally {
1634
1858
  tryUnlink(tmpPath);
@@ -1636,14 +1860,17 @@ function runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeo
1636
1860
  }
1637
1861
  }
1638
1862
  /**
1639
- * Run the precompute worker, then read back the JSON it wrote to `cachePath`.
1640
- * Used by both the lock-winner path and the uncoordinated degrade path.
1863
+ * Run the precompute worker, then read back and validate the JSON it wrote to
1864
+ * `cachePath`. Used by both the lock-winner path and the uncoordinated degrade
1865
+ * path. Returns the validated `PrecomputedData` (never a raw string), so a
1866
+ * malformed payload surfaces as a clear diagnostic here instead of crashing
1867
+ * later in `DesignSystemCache.fromPrecomputed`.
1641
1868
  */
1642
1869
  function precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout) {
1643
1870
  runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeout);
1644
- const raw = tryReadRawCache(cachePath);
1645
- if (raw === null) throw new DesignSystemLoadError(`Precompute worker finished but wrote no cache file for "${resolvedPath}".`, "This usually means the system temp directory is not writable; check its permissions.");
1646
- return raw;
1871
+ const data = tryReadCache(cachePath);
1872
+ if (data === null) throw new DesignSystemLoadError(`Precompute worker finished but wrote no valid cache file for "${resolvedPath}".`, "This usually means the system temp directory is not writable, or the output was malformed; check its permissions and free space.");
1873
+ return data;
1647
1874
  }
1648
1875
  /**
1649
1876
  * Return the raw precompute JSON for `contentHash`, spawning at most one
@@ -1654,26 +1881,30 @@ function computeWithLock(resolvedPath, tailwindNodePath, contentHash, cachePath,
1654
1881
  const lockPath = join(CACHE_DIR, `${contentHash}.lock`);
1655
1882
  const staleMs = timeout + 3e4;
1656
1883
  try {
1657
- mkdirSync(CACHE_DIR, { recursive: true });
1884
+ mkdirSync(CACHE_DIR, {
1885
+ recursive: true,
1886
+ mode: 448
1887
+ });
1658
1888
  } catch {
1659
1889
  return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1660
1890
  }
1661
1891
  const start = Date.now();
1662
1892
  for (;;) {
1663
- const raw = tryReadRawCache(cachePath);
1664
- if (raw !== null) return raw;
1893
+ const cached = tryReadCache(cachePath);
1894
+ if (cached) return cached;
1665
1895
  let lockFd;
1666
1896
  try {
1667
1897
  lockFd = openSync(lockPath, "wx");
1668
1898
  } catch (cause) {
1669
1899
  if (cause.code === "EEXIST") {
1670
- if (lockAgeMs(lockPath) > staleMs || Date.now() - start > staleMs * 2) tryUnlink(lockPath);
1900
+ if (lockAgeMs(lockPath) > staleMs || Date.now() - start > staleMs * 2) reclaimStaleLock(lockPath);
1671
1901
  else syncSleep(LOCK_POLL_MS);
1672
1902
  continue;
1673
1903
  }
1674
1904
  return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1675
1905
  }
1676
1906
  try {
1907
+ tryUnlink(cachePath);
1677
1908
  return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1678
1909
  } finally {
1679
1910
  closeSync(lockFd);
@@ -1696,17 +1927,12 @@ function loadDesignSystemSync(cssPath, timeout) {
1696
1927
  } catch (cause) {
1697
1928
  throw new DesignSystemLoadError(`Could not read CSS entry point: ${resolvedPath}`, "Verify the path resolves from the oxlint working directory and the file is readable.", { cause: cause instanceof Error ? cause : void 0 });
1698
1929
  }
1699
- const contentHash = computeContentHash(content);
1930
+ const contentHash = computeContentHash(hashableContent(resolvedPath, content));
1700
1931
  const contentCachePath = getContentCachePath(contentHash);
1701
1932
  const cached = tryReadCache(contentCachePath);
1702
1933
  if (cached) return cached;
1703
1934
  if (TAILWIND_NODE_PATH === null) throw new DesignSystemLoadError(`Could not resolve '@tailwindcss/node' while loading "${resolvedPath}".`, "Install '@tailwindcss/node' (or upgrade oxlint-tailwindcss) and re-run.");
1704
- const raw = computeWithLock(resolvedPath, TAILWIND_NODE_PATH, contentHash, contentCachePath, timeout ?? 6e4);
1705
- try {
1706
- return JSON.parse(raw);
1707
- } catch (cause) {
1708
- throw new DesignSystemLoadError(`Precompute output for "${resolvedPath}" was not valid JSON.`, "This is likely a bug in oxlint-tailwindcss. Please open an issue with the CSS that triggered it.", { cause: cause instanceof Error ? cause : void 0 });
1709
- }
1935
+ return computeWithLock(resolvedPath, TAILWIND_NODE_PATH, contentHash, contentCachePath, timeout ?? 6e4);
1710
1936
  }
1711
1937
  //#endregion
1712
1938
  //#region src/design-system/debug.ts
@@ -2180,8 +2406,14 @@ const noUnknownClasses = defineRule({
2180
2406
  if (allowlist.has(className)) return true;
2181
2407
  return ignorePrefixes.some((prefix) => className.startsWith(prefix));
2182
2408
  }
2183
- function stripModifiers(className) {
2184
- return splitImportant(className).bare;
2409
+ function strippedUtility(className) {
2410
+ const { utility, variant } = splitUtilityAndVariant(className);
2411
+ const { bare, position } = splitImportant(utility);
2412
+ return {
2413
+ variant,
2414
+ bare,
2415
+ position
2416
+ };
2185
2417
  }
2186
2418
  function check(locations) {
2187
2419
  if (locations.length === 0) return;
@@ -2195,8 +2427,8 @@ const noUnknownClasses = defineRule({
2195
2427
  if (shouldIgnore(cls)) continue;
2196
2428
  const validity = cache.classValidity(cls);
2197
2429
  if (validity === "valid") continue;
2198
- const stripped = stripModifiers(cls);
2199
- if (DEPRECATED_MAP[stripped]) continue;
2430
+ const { variant, bare, position } = strippedUtility(cls);
2431
+ if (DEPRECATED_MAP[bare]) continue;
2200
2432
  if (validity === "missing-prefix") {
2201
2433
  const fixed = `${cache.prefix}:${cls}`;
2202
2434
  const fixedValue = rebuildClassString(split, classes.map((c) => c === cls ? fixed : c));
@@ -2221,7 +2453,8 @@ const noUnknownClasses = defineRule({
2221
2453
  });
2222
2454
  continue;
2223
2455
  }
2224
- const suggestion = findBestSuggestion(stripped, cache.validClasses);
2456
+ const suggestionBare = findBestSuggestion(bare, cache.validClasses);
2457
+ const suggestion = suggestionBare ? variant + reattachImportant(suggestionBare, position) : null;
2225
2458
  if (suggestion) {
2226
2459
  const fixedValue = rebuildClassString(split, classes.map((c) => c === cls ? suggestion : c));
2227
2460
  context.report({
@@ -2381,7 +2614,7 @@ const noConflictingClasses = defineRule({
2381
2614
  }],
2382
2615
  defaultOptions: [{}],
2383
2616
  messages: {
2384
- conflict: "\"{{classA}}\" and \"{{classB}}\" affect {{properties}}. \"{{winner}}\" takes precedence (appears later).",
2617
+ conflict: "\"{{classA}}\" and \"{{classB}}\" both affect {{properties}}. Only one applies — which wins depends on the generated stylesheet order, not the attribute order. Remove one.",
2385
2618
  ...DS_UNAVAILABLE_MESSAGE
2386
2619
  }
2387
2620
  },
@@ -2414,9 +2647,11 @@ const noConflictingClasses = defineRule({
2414
2647
  const propsA = propsMap.get(classA) ?? [];
2415
2648
  for (let j = i + 1; j < variantClasses.length; j++) {
2416
2649
  const classB = variantClasses[j];
2650
+ if (classA === classB) continue;
2417
2651
  const propsB = propsMap.get(classB) ?? [];
2418
2652
  if (shouldSkipPair(classA, classB, propsA, propsB)) continue;
2419
- const overlap = propsA.filter((p) => propsB.includes(p));
2653
+ const propsBSet = new Set(propsB);
2654
+ const overlap = propsA.filter((p) => propsBSet.has(p));
2420
2655
  if (overlap.length > 0) {
2421
2656
  const propList = overlap.length <= 3 ? `"${overlap.join("\", \"")}"` : `${overlap.length} CSS properties`;
2422
2657
  context.report({
@@ -2425,8 +2660,7 @@ const noConflictingClasses = defineRule({
2425
2660
  data: {
2426
2661
  classA,
2427
2662
  classB,
2428
- properties: propList,
2429
- winner: classB
2663
+ properties: propList
2430
2664
  }
2431
2665
  });
2432
2666
  }
@@ -2458,16 +2692,104 @@ const noConflictingClasses = defineRule({
2458
2692
  */
2459
2693
  const BUFFER_SIZE = 4 * 1024 * 1024;
2460
2694
  const HEADER_INTS = 4;
2695
+ const LENGTH_OFFSET = HEADER_INTS * 4;
2461
2696
  const DATA_OFFSET = 20;
2462
2697
  const INIT_TIMEOUT = 6e4;
2463
2698
  const REQUEST_TIMEOUT = 3e4;
2699
+ /**
2700
+ * Build the worker script shared by `sort-service` and `canonicalize-service`.
2701
+ * Owns the entire SharedArrayBuffer protocol (offsets derived from the same
2702
+ * constants the host uses, so they can't drift), the design-system load with
2703
+ * error propagation (DS-M4: the real cause is written into the buffer so the
2704
+ * host can surface it, not a generic "failed to load"), the ready signal, and
2705
+ * the request loop. `handlerExpr` is a function expression `(ds, request) =>
2706
+ * result` — the only part that differs between services.
2707
+ */
2708
+ function makeWorkerScript(handlerExpr) {
2709
+ return `
2710
+ const { workerData } = require('worker_threads');
2711
+ async function main() {
2712
+ const { sharedBuffer, cssPath } = workerData;
2713
+ const control = new Int32Array(sharedBuffer, 0, ${HEADER_INTS});
2714
+ const lengthView = new DataView(sharedBuffer, ${LENGTH_OFFSET}, 4);
2715
+ const dataArea = new Uint8Array(sharedBuffer, ${DATA_OFFSET});
2716
+
2717
+ // On load failure, write the real cause into the data region so the host can
2718
+ // report it instead of a bare "failed to load the design system".
2719
+ function signalLoadError(e) {
2720
+ try {
2721
+ const msg = Buffer.from(String((e && e.message) || e || 'unknown design-system load error'), 'utf-8');
2722
+ const n = Math.min(msg.length, dataArea.length);
2723
+ dataArea.set(msg.subarray(0, n), 0);
2724
+ lengthView.setUint32(0, n);
2725
+ } catch {}
2726
+ Atomics.store(control, 2, -1);
2727
+ Atomics.notify(control, 2);
2728
+ }
2729
+
2730
+ let ds;
2731
+ try {
2732
+ const { __unstable__loadDesignSystem } = require(workerData.tailwindNodePath);
2733
+ const { readFileSync } = require('fs');
2734
+ const { dirname } = require('path');
2735
+ const css = readFileSync(cssPath, 'utf-8');
2736
+ ds = await __unstable__loadDesignSystem(css, { base: dirname(cssPath) });
2737
+ } catch (e) {
2738
+ signalLoadError(e);
2739
+ return;
2740
+ }
2741
+
2742
+ Atomics.store(control, 2, 1);
2743
+ Atomics.notify(control, 2);
2744
+
2745
+ const handler = ${handlerExpr};
2746
+
2747
+ while (true) {
2748
+ Atomics.wait(control, 0, 0);
2749
+ const len = lengthView.getUint32(0);
2750
+ const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
2751
+ Atomics.store(control, 0, 0);
2752
+
2753
+ let response;
2754
+ try {
2755
+ const request = JSON.parse(requestStr);
2756
+ const result = handler(ds, request);
2757
+ response = Buffer.from(JSON.stringify(result), 'utf-8');
2758
+ } catch {
2759
+ response = Buffer.from('null', 'utf-8');
2760
+ }
2761
+
2762
+ // DS-M6: if the response doesn't fit the shared buffer, reply with a
2763
+ // sentinel the host reads as a rejected request, instead of letting
2764
+ // dataArea.set throw and kill the worker (which would hang the caller
2765
+ // until the request timeout and then report a misleading timeout).
2766
+ if (response.length > dataArea.length) {
2767
+ response = Buffer.from('null', 'utf-8');
2768
+ }
2769
+
2770
+ dataArea.set(response, 0);
2771
+ lengthView.setUint32(0, response.length);
2772
+ Atomics.store(control, 1, 1);
2773
+ Atomics.notify(control, 1);
2774
+ }
2775
+ }
2776
+ main().catch(() => {});
2777
+ `;
2778
+ }
2464
2779
  var DesignSystemWorker = class {
2465
2780
  opts;
2466
2781
  ready = null;
2467
2782
  lastError = null;
2783
+ lastErrorCssPath = null;
2468
2784
  constructor(opts) {
2469
2785
  this.opts = opts;
2470
2786
  }
2787
+ /** Record an error as sticky for `cssPath` and return it for `throw`. */
2788
+ remember(cssPath, err) {
2789
+ this.lastError = err;
2790
+ this.lastErrorCssPath = cssPath;
2791
+ return err;
2792
+ }
2471
2793
  /**
2472
2794
  * Ensure the worker is running and pointed at `cssPath`. Returns the
2473
2795
  * ready state. Throws `SortServiceError` on any failure (init timeout,
@@ -2475,14 +2797,12 @@ var DesignSystemWorker = class {
2475
2797
  * cssPath rethrow without retrying.
2476
2798
  */
2477
2799
  ensure(cssPath) {
2478
- if (this.lastError && this.ready?.cssPath === cssPath) throw this.lastError;
2800
+ if (this.lastError && this.lastErrorCssPath === cssPath) throw this.lastError;
2479
2801
  if (this.ready && this.ready.cssPath === cssPath) return this.ready;
2480
2802
  if (this.ready) this.cleanup();
2481
2803
  this.lastError = null;
2482
- if (TAILWIND_NODE_PATH === null) {
2483
- this.lastError = new SortServiceError(`Could not resolve '@tailwindcss/node' for the ${this.opts.serviceName} worker.`, "Install '@tailwindcss/node' (or upgrade oxlint-tailwindcss) and re-run.");
2484
- throw this.lastError;
2485
- }
2804
+ this.lastErrorCssPath = null;
2805
+ if (TAILWIND_NODE_PATH === null) throw this.remember(cssPath, new SortServiceError(`Could not resolve '@tailwindcss/node' for the ${this.opts.serviceName} worker.`, "Install '@tailwindcss/node' (or upgrade oxlint-tailwindcss) and re-run."));
2486
2806
  const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
2487
2807
  const controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
2488
2808
  const lengthView = new DataView(sharedBuffer, HEADER_INTS * 4, 4);
@@ -2498,22 +2818,22 @@ var DesignSystemWorker = class {
2498
2818
  }
2499
2819
  });
2500
2820
  } catch (cause) {
2501
- this.lastError = new SortServiceError(`Failed to spawn ${this.opts.serviceName} worker for "${cssPath}".`, "This is unexpected; please open an issue with the error details.", { cause: cause instanceof Error ? cause : void 0 });
2502
- throw this.lastError;
2821
+ throw this.remember(cssPath, new SortServiceError(`Failed to spawn ${this.opts.serviceName} worker for "${cssPath}".`, "This is unexpected; please open an issue with the error details.", { cause: cause instanceof Error ? cause : void 0 }));
2503
2822
  }
2504
2823
  worker.unref();
2505
2824
  worker.on("error", (err) => {
2506
2825
  this.lastError = new SortServiceError(`${this.opts.serviceName} worker died: ${err.message}`, "The worker will not be restarted in this process. Restart the lint session.", { cause: err });
2826
+ this.lastErrorCssPath = cssPath;
2507
2827
  });
2508
2828
  if (Atomics.wait(controlArray, 2, 0, INIT_TIMEOUT) === "timed-out") {
2509
- this.lastError = new SortServiceError(`${this.opts.serviceName} worker timed out loading the design system from "${cssPath}" after ${INIT_TIMEOUT}ms.`, "Raise settings.tailwindcss.timeout if your machine is slow, or verify the CSS imports resolve.");
2510
2829
  this.terminateWorker(worker);
2511
- throw this.lastError;
2830
+ throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker timed out loading the design system from "${cssPath}" after ${INIT_TIMEOUT}ms.`, "Verify the CSS imports resolve; this can also happen if the machine or CI runner is heavily loaded."));
2512
2831
  }
2513
2832
  if (controlArray[2] === -1) {
2514
- this.lastError = new SortServiceError(`${this.opts.serviceName} worker failed to load the design system from "${cssPath}".`, "Verify @tailwindcss/node is installed and the CSS file (and its imports) is valid.");
2833
+ const len = lengthView.getUint32(0);
2834
+ const detail = len > 0 ? Buffer.from(dataArea.slice(0, len)).toString("utf-8") : "";
2515
2835
  this.terminateWorker(worker);
2516
- throw this.lastError;
2836
+ throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker failed to load the design system from "${cssPath}".${detail ? ` ${detail}` : ""}`, "Verify @tailwindcss/node is installed and the CSS file (and its imports) is valid."));
2517
2837
  }
2518
2838
  this.ready = {
2519
2839
  worker,
@@ -2537,9 +2857,8 @@ var DesignSystemWorker = class {
2537
2857
  Atomics.store(state.controlArray, 0, 1);
2538
2858
  Atomics.notify(state.controlArray, 0);
2539
2859
  if (Atomics.wait(state.controlArray, 1, 0, REQUEST_TIMEOUT) === "timed-out") {
2540
- this.lastError = new SortServiceError(`${this.opts.serviceName} worker request timed out after ${REQUEST_TIMEOUT}ms.`, "Raise settings.tailwindcss.timeout if your machine is slow.");
2541
2860
  this.cleanup();
2542
- throw this.lastError;
2861
+ throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker request timed out after ${REQUEST_TIMEOUT}ms.`, "This is unexpected for typical class lists; please open an issue if it persists."));
2543
2862
  }
2544
2863
  const responseLen = state.lengthView.getUint32(0);
2545
2864
  const responseStr = Buffer.from(state.dataArea.slice(0, responseLen)).toString("utf-8");
@@ -2548,20 +2867,19 @@ var DesignSystemWorker = class {
2548
2867
  try {
2549
2868
  parsed = JSON.parse(responseStr);
2550
2869
  } catch (cause) {
2551
- this.lastError = new SortServiceError(`${this.opts.serviceName} worker returned non-JSON response.`, "This is a bug; please open an issue.", { cause: cause instanceof Error ? cause : void 0 });
2552
2870
  this.cleanup();
2553
- throw this.lastError;
2871
+ throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker returned non-JSON response.`, "This is a bug; please open an issue.", { cause: cause instanceof Error ? cause : void 0 }));
2554
2872
  }
2555
2873
  if (parsed === null) {
2556
- this.lastError = new SortServiceError(`${this.opts.serviceName} worker returned null — request body was rejected.`, "This is a bug; please open an issue with the input that triggered it.");
2557
2874
  this.cleanup();
2558
- throw this.lastError;
2875
+ 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."));
2559
2876
  }
2560
2877
  return parsed;
2561
2878
  }
2562
2879
  reset() {
2563
2880
  this.cleanup();
2564
2881
  this.lastError = null;
2882
+ this.lastErrorCssPath = null;
2565
2883
  }
2566
2884
  cleanup() {
2567
2885
  if (this.ready) {
@@ -2593,60 +2911,14 @@ var DesignSystemWorker = class {
2593
2911
  * subsequent lookup is O(1).
2594
2912
  */
2595
2913
  const canonWorker = new DesignSystemWorker({
2596
- workerScript: `
2597
- const { workerData } = require('worker_threads');
2598
-
2599
- async function main() {
2600
- const { sharedBuffer, cssPath } = workerData;
2601
- const control = new Int32Array(sharedBuffer, 0, 4);
2602
- const lengthView = new DataView(sharedBuffer, 4 * 4, 4);
2603
- const dataArea = new Uint8Array(sharedBuffer, 4 * 4 + 4);
2604
-
2605
- let ds;
2606
- try {
2607
- const { __unstable__loadDesignSystem } = require(workerData.tailwindNodePath);
2608
- const { readFileSync } = require('fs');
2609
- const { dirname } = require('path');
2610
- const css = readFileSync(cssPath, 'utf-8');
2611
- ds = await __unstable__loadDesignSystem(css, { base: dirname(cssPath) });
2612
- } catch {
2613
- Atomics.store(control, 2, -1);
2614
- Atomics.notify(control, 2);
2615
- return;
2616
- }
2617
-
2618
- Atomics.store(control, 2, 1);
2619
- Atomics.notify(control, 2);
2620
-
2621
- while (true) {
2622
- Atomics.wait(control, 0, 0);
2623
- const len = lengthView.getUint32(0);
2624
- const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
2625
- Atomics.store(control, 0, 0);
2626
-
2627
- let response;
2628
- try {
2629
- const { classes, rem } = JSON.parse(requestStr);
2630
- const options = rem ? { rem } : undefined;
2631
- // canonicalizeCandidates deduplicates its input, so we must call it
2632
- // one class at a time to preserve order/length. See sync-loader.ts.
2633
- const result = classes.map((cls) => {
2634
- const r = ds.canonicalizeCandidates([cls], options);
2635
- return r[0] ?? cls;
2636
- });
2637
- response = Buffer.from(JSON.stringify(result), 'utf-8');
2638
- } catch {
2639
- response = Buffer.from('null', 'utf-8');
2640
- }
2641
-
2642
- dataArea.set(response, 0);
2643
- lengthView.setUint32(0, response.length);
2644
- Atomics.store(control, 1, 1);
2645
- Atomics.notify(control, 1);
2646
- }
2647
- }
2648
- main();
2649
- `,
2914
+ workerScript: makeWorkerScript(`(ds, request) => {
2915
+ const { classes, rem } = request;
2916
+ const options = rem ? { rem } : undefined;
2917
+ return classes.map((cls) => {
2918
+ const r = ds.canonicalizeCandidates([cls], options);
2919
+ return r[0] ?? cls;
2920
+ });
2921
+ }`),
2650
2922
  serviceName: "canonicalize"
2651
2923
  });
2652
2924
  /**
@@ -2691,7 +2963,7 @@ function canonicalizeClassesSync(cssPath, classes, rem) {
2691
2963
  for (let k = 0; k < uniqueMissing.length; k++) freshByClass.set(uniqueMissing[k], fresh[k]);
2692
2964
  for (let j = 0; j < missing.length; j++) {
2693
2965
  const cls = missing[j];
2694
- const value = freshByClass.get(cls) ?? cls;
2966
+ const value = roundRemValue(freshByClass.get(cls) ?? cls);
2695
2967
  canonCache.set(cachePrefix + cls, value);
2696
2968
  out[missingIdx[j]] = value;
2697
2969
  }
@@ -2783,62 +3055,17 @@ const enforceCanonical = defineRule({
2783
3055
  * Atomics.wait, fail-loud, sticky lastError) lives in `./ds-worker.ts`.
2784
3056
  */
2785
3057
  const sortWorker = new DesignSystemWorker({
2786
- workerScript: `
2787
- const { workerData } = require('worker_threads');
2788
-
2789
- async function main() {
2790
- const { sharedBuffer, cssPath } = workerData;
2791
- const control = new Int32Array(sharedBuffer, 0, 4);
2792
- const lengthView = new DataView(sharedBuffer, 4 * 4, 4);
2793
- const dataArea = new Uint8Array(sharedBuffer, 4 * 4 + 4);
2794
-
2795
- let ds;
2796
- try {
2797
- const { __unstable__loadDesignSystem } = require(workerData.tailwindNodePath);
2798
- const { readFileSync } = require('fs');
2799
- const { dirname } = require('path');
2800
- const css = readFileSync(cssPath, 'utf-8');
2801
- ds = await __unstable__loadDesignSystem(css, { base: dirname(cssPath) });
2802
- } catch {
2803
- Atomics.store(control, 2, -1);
2804
- Atomics.notify(control, 2);
2805
- return;
2806
- }
2807
-
2808
- Atomics.store(control, 2, 1);
2809
- Atomics.notify(control, 2);
2810
-
2811
- while (true) {
2812
- Atomics.wait(control, 0, 0);
2813
- const len = lengthView.getUint32(0);
2814
- const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
2815
- Atomics.store(control, 0, 0);
2816
-
2817
- let response;
2818
- try {
2819
- const classes = JSON.parse(requestStr);
2820
- const ordered = ds.getClassOrder(classes);
2821
- const sorted = [...ordered]
2822
- .sort((a, b) => {
2823
- if (a[1] === null && b[1] === null) return 0;
2824
- if (a[1] === null) return -1;
2825
- if (b[1] === null) return 1;
2826
- return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0;
2827
- })
2828
- .map(([name]) => name);
2829
- response = Buffer.from(JSON.stringify(sorted), 'utf-8');
2830
- } catch {
2831
- response = Buffer.from('null', 'utf-8');
2832
- }
2833
-
2834
- dataArea.set(response, 0);
2835
- lengthView.setUint32(0, response.length);
2836
- Atomics.store(control, 1, 1);
2837
- Atomics.notify(control, 1);
2838
- }
2839
- }
2840
- main();
2841
- `,
3058
+ workerScript: makeWorkerScript(`(ds, classes) => {
3059
+ const ordered = ds.getClassOrder(classes);
3060
+ return [...ordered]
3061
+ .sort((a, b) => {
3062
+ if (a[1] === null && b[1] === null) return 0;
3063
+ if (a[1] === null) return -1;
3064
+ if (b[1] === null) return 1;
3065
+ return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0;
3066
+ })
3067
+ .map(([name]) => name);
3068
+ }`),
2842
3069
  serviceName: "sort"
2843
3070
  });
2844
3071
  /**
@@ -2890,13 +3117,9 @@ const enforceSortOrder = defineRule({
2890
3117
  }
2891
3118
  function sortStrict(classes) {
2892
3119
  const groups = /* @__PURE__ */ new Map();
2893
- const groupOrder = [];
2894
3120
  for (const cls of classes) {
2895
3121
  const { variant } = splitUtilityAndVariant(cls);
2896
- if (!groups.has(variant)) {
2897
- groups.set(variant, []);
2898
- groupOrder.push(variant);
2899
- }
3122
+ if (!groups.has(variant)) groups.set(variant, []);
2900
3123
  groups.get(variant).push(cls);
2901
3124
  }
2902
3125
  for (const [, groupClasses] of groups) {
@@ -3078,26 +3301,6 @@ const enforceShorthand = defineRule({
3078
3301
  }
3079
3302
  });
3080
3303
  //#endregion
3081
- //#region src/utils/allowlist.ts
3082
- /**
3083
- * Shared regex-allowlist helpers used by rules that accept an `allowlist`
3084
- * option of regex source strings (currently enforce-logical / enforce-physical).
3085
- *
3086
- * Invalid regex sources are skipped rather than thrown so a typo in one
3087
- * pattern doesn't blow up the entire lint run.
3088
- */
3089
- function compileRegexList(patterns) {
3090
- if (!patterns || patterns.length === 0) return [];
3091
- const compiled = [];
3092
- for (const p of patterns) try {
3093
- compiled.push(new RegExp(p));
3094
- } catch {}
3095
- return compiled;
3096
- }
3097
- function matchesAny(value, list) {
3098
- return list.some((re) => re.test(value));
3099
- }
3100
- //#endregion
3101
3304
  //#region src/rules/enforce-logical.ts
3102
3305
  const LOGICAL_PHYSICAL_SCHEMA = {
3103
3306
  type: "object",
@@ -3238,9 +3441,14 @@ function createDirectionalMapper(context, opts) {
3238
3441
  if (matchesAny(cls, allowlist)) return null;
3239
3442
  const { utility, variant } = splitUtilityAndVariant(cls);
3240
3443
  const { bare: bareUtility, position } = splitImportant(utility);
3444
+ const negative = bareUtility.startsWith("-");
3445
+ const core = negative ? bareUtility.slice(1) : bareUtility;
3241
3446
  for (const { from, to, axis } of opts.mappings) {
3242
3447
  if (direction !== "both" && direction !== axis) continue;
3243
- if (bareUtility === from || bareUtility.startsWith(`${from}-`)) return `${variant}${reattachImportant(to + bareUtility.slice(from.length), position)}`;
3448
+ if (core === from || core.startsWith(`${from}-`)) {
3449
+ const suffix = core.slice(from.length);
3450
+ return `${variant}${reattachImportant(`${negative ? "-" : ""}${to}${suffix}`, position)}`;
3451
+ }
3244
3452
  }
3245
3453
  return null;
3246
3454
  }
@@ -3383,10 +3591,16 @@ const noRestrictedClasses = defineRule({
3383
3591
  createOnce(context) {
3384
3592
  const getConfig = createLazyOptions(context, (o) => ({
3385
3593
  restrictedClasses: new Set(o?.classes ?? []),
3386
- patterns: (o?.patterns ?? []).map((p) => ({
3387
- regex: new RegExp(p.pattern),
3388
- message: p.message
3389
- }))
3594
+ patterns: (o?.patterns ?? []).flatMap((p) => {
3595
+ try {
3596
+ return [{
3597
+ regex: new RegExp(p.pattern),
3598
+ message: p.message
3599
+ }];
3600
+ } catch {
3601
+ return [];
3602
+ }
3603
+ })
3390
3604
  }));
3391
3605
  function check(locations) {
3392
3606
  const { restrictedClasses, patterns } = getConfig();
@@ -3515,6 +3729,7 @@ const enforceConsistentImportantPosition = defineRule({
3515
3729
  });
3516
3730
  //#endregion
3517
3731
  //#region src/rules/enforce-negative-arbitrary-values.ts
3732
+ const SIMPLE_DIMENSION = /^\d*\.?\d+[a-z%]*$/;
3518
3733
  function fixClass(cls) {
3519
3734
  const { utility, variant } = splitUtilityAndVariant(cls);
3520
3735
  const hasImportantPrefix = utility.startsWith("!");
@@ -3527,6 +3742,7 @@ function fixClass(cls) {
3527
3742
  if (bracketClose === -1 || bracketClose < bracketOpen) return null;
3528
3743
  const innerValue = bare.slice(bracketOpen + 1, bracketClose);
3529
3744
  if (innerValue.startsWith("-")) return null;
3745
+ if (!SIMPLE_DIMENSION.test(innerValue)) return null;
3530
3746
  const baseUtility = bare.slice(1, bracketOpen);
3531
3747
  return `${variant}${hasImportantPrefix ? "!" : ""}${baseUtility}[-${innerValue}]${hasImportantSuffix ? "!" : ""}`;
3532
3748
  }
@@ -3661,13 +3877,48 @@ const KNOWN_PREFIXES = [
3661
3877
  "via",
3662
3878
  "to"
3663
3879
  ];
3880
+ const PROPERTY_GROUP_BY_UTILITY = {};
3881
+ for (const u of [
3882
+ "block",
3883
+ "inline-block",
3884
+ "inline",
3885
+ "flex",
3886
+ "inline-flex",
3887
+ "grid",
3888
+ "inline-grid",
3889
+ "flow-root",
3890
+ "contents",
3891
+ "table",
3892
+ "inline-table",
3893
+ "table-caption",
3894
+ "table-cell",
3895
+ "table-row",
3896
+ "table-row-group",
3897
+ "table-header-group",
3898
+ "table-footer-group",
3899
+ "table-column",
3900
+ "table-column-group",
3901
+ "list-item",
3902
+ "hidden"
3903
+ ]) PROPERTY_GROUP_BY_UTILITY[u] = "display";
3904
+ for (const u of [
3905
+ "static",
3906
+ "fixed",
3907
+ "absolute",
3908
+ "relative",
3909
+ "sticky"
3910
+ ]) PROPERTY_GROUP_BY_UTILITY[u] = "position";
3664
3911
  /**
3665
- * Extracts the utility prefix (e.g. "bg" from "bg-gray-900", "text" from "text-white").
3666
- * Used to group utilities by their property type.
3912
+ * Maps a utility to a key identifying the CSS property it sets, so a base and a
3913
+ * variant class for the same property group together. Exact-match equivalence
3914
+ * groups (display, position) win; otherwise fall back to the prefix heuristic
3915
+ * (e.g. "bg" from "bg-gray-900", "text" from "text-white").
3667
3916
  */
3668
3917
  function getUtilityPrefix(utility) {
3669
3918
  let u = splitImportant(utility).bare;
3670
3919
  if (u.startsWith("-")) u = u.slice(1);
3920
+ const group = PROPERTY_GROUP_BY_UTILITY[u];
3921
+ if (group) return group;
3671
3922
  for (const prefix of KNOWN_PREFIXES) if (u === prefix || u.startsWith(`${prefix}-`)) return prefix;
3672
3923
  const dashIdx = u.indexOf("-");
3673
3924
  return dashIdx >= 0 ? u.slice(0, dashIdx) : u;
@@ -3775,13 +4026,10 @@ const noHardcodedColors = defineRule({
3775
4026
  docs: { description: "Disallow hardcoded color values in Tailwind CSS classes" },
3776
4027
  schema: [{
3777
4028
  type: "object",
3778
- properties: {
3779
- entryPoint: { type: "string" },
3780
- allow: {
3781
- type: "array",
3782
- items: { type: "string" }
3783
- }
3784
- },
4029
+ properties: { allow: {
4030
+ type: "array",
4031
+ items: { type: "string" }
4032
+ } },
3785
4033
  additionalProperties: false
3786
4034
  }],
3787
4035
  defaultOptions: [{ allow: [] }],
@@ -3813,24 +4061,6 @@ const noHardcodedColors = defineRule({
3813
4061
  });
3814
4062
  //#endregion
3815
4063
  //#region src/rules/no-contradicting-variants.ts
3816
- const TARGET_CHANGING_VARIANTS = new Set([
3817
- "after",
3818
- "before",
3819
- "file",
3820
- "placeholder",
3821
- "marker",
3822
- "backdrop",
3823
- "selection",
3824
- "first-line",
3825
- "first-letter"
3826
- ]);
3827
- function changesTarget(variant) {
3828
- if (TARGET_CHANGING_VARIANTS.has(variant)) return true;
3829
- if (variant === "*" || variant === "**") return true;
3830
- if (variant.startsWith("[") && variant.endsWith("]")) return true;
3831
- if (variant.startsWith("*:")) return true;
3832
- return false;
3833
- }
3834
4064
  const noContradictingVariants = defineRule({
3835
4065
  meta: {
3836
4066
  type: "suggestion",
@@ -3865,18 +4095,6 @@ const noContradictingVariants = defineRule({
3865
4095
  });
3866
4096
  //#endregion
3867
4097
  //#region src/rules/consistent-variant-order.ts
3868
- const PSEUDO_ELEMENTS = new Set([
3869
- "before",
3870
- "after",
3871
- "file",
3872
- "placeholder",
3873
- "selection",
3874
- "marker",
3875
- "backdrop",
3876
- "first-line",
3877
- "first-letter",
3878
- "details-content"
3879
- ]);
3880
4098
  const DEFAULT_VARIANT_ORDER = [
3881
4099
  "*",
3882
4100
  "**",
@@ -3975,17 +4193,12 @@ const consistentVariantOrder = defineRule({
3975
4193
  },
3976
4194
  createOnce(context) {
3977
4195
  const getDS = createLazyLoader(context);
3978
- const getPriority = createLazyOptions(context, (o) => {
3979
- let dsCache = null;
3980
- try {
3981
- dsCache = getDS().cache;
3982
- } catch (err) {
3983
- if (!isFatalError(err)) throw err;
3984
- }
3985
- if (o?.order) {
4196
+ const getOptions = createLazyOptions(context, (o) => ({ order: o?.order }));
4197
+ function buildPriority(order, dsCache) {
4198
+ if (order) {
3986
4199
  const map = /* @__PURE__ */ new Map();
3987
- for (let i = 0; i < o.order.length; i++) map.set(o.order[i], i);
3988
- const fallback = o.order.length;
4200
+ for (let i = 0; i < order.length; i++) map.set(order[i], i);
4201
+ const fallback = order.length;
3989
4202
  return (v) => map.get(v) ?? fallback;
3990
4203
  }
3991
4204
  if (dsCache && dsCache.hasVariantOrder()) {
@@ -3996,17 +4209,36 @@ const consistentVariantOrder = defineRule({
3996
4209
  for (let i = 0; i < DEFAULT_VARIANT_ORDER.length; i++) map.set(DEFAULT_VARIANT_ORDER[i], i);
3997
4210
  const fallback = DEFAULT_VARIANT_ORDER.length;
3998
4211
  return (v) => map.get(v) ?? fallback;
3999
- });
4000
- const getPrefix = createLazyOptions(context, () => {
4212
+ }
4213
+ const priorityByEntry = /* @__PURE__ */ new Map();
4214
+ const prefixByEntry = /* @__PURE__ */ new Map();
4215
+ function resolveForFile() {
4216
+ let dsCache = null;
4217
+ let entryKey = "";
4001
4218
  try {
4002
- return getDS().cache.prefix;
4219
+ const ds = getDS();
4220
+ dsCache = ds.cache;
4221
+ entryKey = ds.entryPoint;
4003
4222
  } catch (err) {
4004
4223
  if (!isFatalError(err)) throw err;
4005
- return "";
4006
4224
  }
4007
- });
4225
+ let priorityOf = priorityByEntry.get(entryKey);
4226
+ if (!priorityOf) {
4227
+ priorityOf = buildPriority(getOptions().order, dsCache);
4228
+ priorityByEntry.set(entryKey, priorityOf);
4229
+ }
4230
+ let prefix = prefixByEntry.get(entryKey);
4231
+ if (prefix === void 0) {
4232
+ prefix = dsCache?.prefix ?? "";
4233
+ prefixByEntry.set(entryKey, prefix);
4234
+ }
4235
+ return {
4236
+ priorityOf,
4237
+ prefix
4238
+ };
4239
+ }
4008
4240
  function reorderClass(cls) {
4009
- const prefix = getPrefix();
4241
+ const { priorityOf, prefix } = resolveForFile();
4010
4242
  let pfx = "";
4011
4243
  let body = cls;
4012
4244
  if (prefix && cls.startsWith(prefix + ":")) {
@@ -4015,13 +4247,25 @@ const consistentVariantOrder = defineRule({
4015
4247
  }
4016
4248
  const variants = extractVariants(body);
4017
4249
  if (variants.length < 2) return null;
4018
- const priorityOf = getPriority();
4019
- const sorted = [...variants].sort((a, b) => priorityOf(a) - priorityOf(b));
4020
- const nonPseudo = [];
4021
4250
  const pseudo = [];
4022
- for (const v of sorted) if (PSEUDO_ELEMENTS.has(v)) pseudo.push(v);
4023
- else nonPseudo.push(v);
4024
- const final = nonPseudo.length > 0 && pseudo.length > 0 ? [...nonPseudo, ...pseudo] : sorted;
4251
+ const rest = [];
4252
+ for (const v of variants) if (isPseudoElementVariant(v)) pseudo.push(v);
4253
+ else rest.push(v);
4254
+ const reorderedRest = [];
4255
+ let segment = [];
4256
+ const flushSegment = () => {
4257
+ if (segment.length === 0) return;
4258
+ segment.sort((a, b) => priorityOf(a) - priorityOf(b));
4259
+ reorderedRest.push(...segment);
4260
+ segment = [];
4261
+ };
4262
+ for (const v of rest) if (isSelectorBarrier(v)) {
4263
+ flushSegment();
4264
+ reorderedRest.push(v);
4265
+ } else segment.push(v);
4266
+ flushSegment();
4267
+ pseudo.sort((a, b) => priorityOf(a) - priorityOf(b));
4268
+ const final = [...reorderedRest, ...pseudo];
4025
4269
  if (variants.every((v, i) => v === final[i])) return null;
4026
4270
  const utility = extractUtility(body);
4027
4271
  return pfx + final.join(":") + ":" + utility;
@@ -4298,5 +4542,3 @@ const plugin = definePlugin({
4298
4542
  });
4299
4543
  //#endregion
4300
4544
  export { plugin as default };
4301
-
4302
- //# sourceMappingURL=index.mjs.map