oxlint-tailwindcss 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -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
@@ -1511,8 +1586,20 @@ async function main() {
1511
1586
  main()
1512
1587
  .then(() => { Atomics.store(control, 2, 1); Atomics.notify(control, 2); })
1513
1588
  .catch((e) => signalError(e));
1589
+ } catch (e) {
1590
+ signalError(e);
1591
+ }
1514
1592
  `;
1515
- const CACHE_DIR = join(tmpdir(), "oxlint-tailwindcss");
1593
+ function cacheDirName() {
1594
+ try {
1595
+ const info = userInfo();
1596
+ const id = typeof info.uid === "number" && info.uid >= 0 ? String(info.uid) : info.username;
1597
+ return `oxlint-tailwindcss-${String(id).replace(/[^a-zA-Z0-9_-]/g, "_")}`;
1598
+ } catch {
1599
+ return "oxlint-tailwindcss";
1600
+ }
1601
+ }
1602
+ const CACHE_DIR = join(tmpdir(), cacheDirName());
1516
1603
  /**
1517
1604
  * Cache key derived from:
1518
1605
  * - md5(PRECOMPUTE_SCRIPT): auto-invalidates when our precompute logic changes,
@@ -1531,17 +1618,73 @@ const CACHE_KEY = computeCacheKey(PRECOMPUTE_SCRIPT, TAILWIND_NODE_VERSION);
1531
1618
  function computeContentHash(content) {
1532
1619
  return createHash("md5").update(`${CACHE_KEY}:${content}`).digest("hex");
1533
1620
  }
1621
+ const IMPORT_RE = /@import\s+(?:url\(\s*)?['"]([^'"]+)['"]/g;
1622
+ /**
1623
+ * Concatenate the entry CSS with the content of its locally-imported files, so
1624
+ * the cache key invalidates when an `@import`'d file changes — not only when the
1625
+ * entry itself does (DS-A2). Without this, editing a `@theme`/component file
1626
+ * pulled in via `@import "./theme.css"` served a stale design system until the
1627
+ * entry was touched or the Tailwind version changed.
1628
+ *
1629
+ * Resolves RELATIVE imports (`./`, `../`) recursively up to a small depth;
1630
+ * package imports (`@import "tailwindcss"`, `tw-animate-css`) are already
1631
+ * covered by the `@tailwindcss/node` version baked into CACHE_KEY. Best-effort:
1632
+ * an unreadable import contributes nothing (it can't affect the DS either).
1633
+ */
1634
+ function hashableContent(entryPath, entryContent) {
1635
+ const parts = [entryContent];
1636
+ const seen = new Set([resolve(entryPath)]);
1637
+ const visit = (cssPath, content, depth) => {
1638
+ if (depth <= 0) return;
1639
+ const baseDir = dirname(cssPath);
1640
+ IMPORT_RE.lastIndex = 0;
1641
+ const specifiers = [];
1642
+ let m;
1643
+ while ((m = IMPORT_RE.exec(content)) !== null) if (m[1].startsWith(".")) specifiers.push(m[1]);
1644
+ for (const spec of specifiers) {
1645
+ const importPath = resolve(baseDir, spec.split("?")[0]);
1646
+ if (seen.has(importPath)) continue;
1647
+ seen.add(importPath);
1648
+ let importContent;
1649
+ try {
1650
+ importContent = readFileSync(importPath, "utf-8");
1651
+ } catch {
1652
+ continue;
1653
+ }
1654
+ parts.push(importContent);
1655
+ visit(importPath, importContent, depth - 1);
1656
+ }
1657
+ };
1658
+ visit(resolve(entryPath), entryContent, 4);
1659
+ return parts.join("\0");
1660
+ }
1534
1661
  function getContentCachePath(contentHash) {
1535
1662
  return join(CACHE_DIR, `${contentHash}.json`);
1536
1663
  }
1664
+ /**
1665
+ * Minimal shape check for a cache payload. Guards against (a) a poisoned file
1666
+ * planted by a local attacker and (b) a corrupt/half-written or version-skewed
1667
+ * file. A `{}` that is valid JSON but missing fields would otherwise blow up
1668
+ * later in `DesignSystemCache.fromPrecomputed` with a raw TypeError that isn't
1669
+ * plugin-fatal, breaking the lint with no diagnostic. We don't deep-validate
1670
+ * every entry — just enough that `fromPrecomputed` can rely on the fields.
1671
+ */
1672
+ function isPrecomputedData(data) {
1673
+ if (typeof data !== "object" || data === null) return false;
1674
+ const d = data;
1675
+ const isObject = (v) => typeof v === "object" && v !== null;
1676
+ 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);
1677
+ }
1537
1678
  function tryReadCache(cachePath) {
1538
1679
  const raw = tryReadRawCache(cachePath);
1539
1680
  if (raw === null) return null;
1681
+ let data;
1540
1682
  try {
1541
- return JSON.parse(raw);
1683
+ data = JSON.parse(raw);
1542
1684
  } catch {
1543
1685
  return null;
1544
1686
  }
1687
+ return isPrecomputedData(data) ? data : null;
1545
1688
  }
1546
1689
  function tryReadRawCache(cachePath) {
1547
1690
  try {
@@ -1568,6 +1711,23 @@ function tryUnlink(path) {
1568
1711
  unlinkSync(path);
1569
1712
  } catch {}
1570
1713
  }
1714
+ /**
1715
+ * Reclaim a stale lock by exclusive rename rather than unlink (DS-M1). Two
1716
+ * waiters that both judge the lock stale would otherwise both `unlink` it — and
1717
+ * the second unlink could delete a FRESH lock a third isolate just created,
1718
+ * letting two precomputes run in parallel (the very amplification the lock
1719
+ * exists to prevent, #24). `renameSync` moves the file atomically: only one
1720
+ * waiter wins the move; the loser gets ENOENT and loops back to re-check.
1721
+ */
1722
+ function reclaimStaleLock(lockPath) {
1723
+ const reclaimPath = `${lockPath}.reclaim.${process.pid}.${threadId}.${precomputeSeq++}`;
1724
+ try {
1725
+ renameSync(lockPath, reclaimPath);
1726
+ } catch {
1727
+ return;
1728
+ }
1729
+ tryUnlink(reclaimPath);
1730
+ }
1571
1731
  /** control[2] — the worker's ready/done signal (0=loading, 1=done, -1=error). */
1572
1732
  const PRECOMPUTE_SIGNAL_INDEX = 2;
1573
1733
  const ERR_BUFFER_SIZE = 64 * 1024;
@@ -1620,15 +1780,12 @@ function runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeo
1620
1780
  } catch (cause) {
1621
1781
  throw precomputeLoadError(resolvedPath, cause);
1622
1782
  }
1623
- let workerError;
1624
- worker.on("error", (err) => {
1625
- workerError = err;
1626
- });
1783
+ worker.on("error", () => {});
1627
1784
  try {
1628
1785
  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
1786
  if (control[PRECOMPUTE_SIGNAL_INDEX] === -1) {
1630
1787
  const len = errLengthView.getUint32(0);
1631
- throw precomputeLoadError(resolvedPath, len > 0 ? new Error(Buffer.from(errDataArea.slice(0, len)).toString("utf-8")) : workerError);
1788
+ 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
1789
  }
1633
1790
  } finally {
1634
1791
  tryUnlink(tmpPath);
@@ -1636,14 +1793,17 @@ function runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeo
1636
1793
  }
1637
1794
  }
1638
1795
  /**
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.
1796
+ * Run the precompute worker, then read back and validate the JSON it wrote to
1797
+ * `cachePath`. Used by both the lock-winner path and the uncoordinated degrade
1798
+ * path. Returns the validated `PrecomputedData` (never a raw string), so a
1799
+ * malformed payload surfaces as a clear diagnostic here instead of crashing
1800
+ * later in `DesignSystemCache.fromPrecomputed`.
1641
1801
  */
1642
1802
  function precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout) {
1643
1803
  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;
1804
+ const data = tryReadCache(cachePath);
1805
+ 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.");
1806
+ return data;
1647
1807
  }
1648
1808
  /**
1649
1809
  * Return the raw precompute JSON for `contentHash`, spawning at most one
@@ -1654,26 +1814,30 @@ function computeWithLock(resolvedPath, tailwindNodePath, contentHash, cachePath,
1654
1814
  const lockPath = join(CACHE_DIR, `${contentHash}.lock`);
1655
1815
  const staleMs = timeout + 3e4;
1656
1816
  try {
1657
- mkdirSync(CACHE_DIR, { recursive: true });
1817
+ mkdirSync(CACHE_DIR, {
1818
+ recursive: true,
1819
+ mode: 448
1820
+ });
1658
1821
  } catch {
1659
1822
  return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1660
1823
  }
1661
1824
  const start = Date.now();
1662
1825
  for (;;) {
1663
- const raw = tryReadRawCache(cachePath);
1664
- if (raw !== null) return raw;
1826
+ const cached = tryReadCache(cachePath);
1827
+ if (cached) return cached;
1665
1828
  let lockFd;
1666
1829
  try {
1667
1830
  lockFd = openSync(lockPath, "wx");
1668
1831
  } catch (cause) {
1669
1832
  if (cause.code === "EEXIST") {
1670
- if (lockAgeMs(lockPath) > staleMs || Date.now() - start > staleMs * 2) tryUnlink(lockPath);
1833
+ if (lockAgeMs(lockPath) > staleMs || Date.now() - start > staleMs * 2) reclaimStaleLock(lockPath);
1671
1834
  else syncSleep(LOCK_POLL_MS);
1672
1835
  continue;
1673
1836
  }
1674
1837
  return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1675
1838
  }
1676
1839
  try {
1840
+ tryUnlink(cachePath);
1677
1841
  return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1678
1842
  } finally {
1679
1843
  closeSync(lockFd);
@@ -1696,17 +1860,12 @@ function loadDesignSystemSync(cssPath, timeout) {
1696
1860
  } catch (cause) {
1697
1861
  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
1862
  }
1699
- const contentHash = computeContentHash(content);
1863
+ const contentHash = computeContentHash(hashableContent(resolvedPath, content));
1700
1864
  const contentCachePath = getContentCachePath(contentHash);
1701
1865
  const cached = tryReadCache(contentCachePath);
1702
1866
  if (cached) return cached;
1703
1867
  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
- }
1868
+ return computeWithLock(resolvedPath, TAILWIND_NODE_PATH, contentHash, contentCachePath, timeout ?? 6e4);
1710
1869
  }
1711
1870
  //#endregion
1712
1871
  //#region src/design-system/debug.ts
@@ -2180,8 +2339,14 @@ const noUnknownClasses = defineRule({
2180
2339
  if (allowlist.has(className)) return true;
2181
2340
  return ignorePrefixes.some((prefix) => className.startsWith(prefix));
2182
2341
  }
2183
- function stripModifiers(className) {
2184
- return splitImportant(className).bare;
2342
+ function strippedUtility(className) {
2343
+ const { utility, variant } = splitUtilityAndVariant(className);
2344
+ const { bare, position } = splitImportant(utility);
2345
+ return {
2346
+ variant,
2347
+ bare,
2348
+ position
2349
+ };
2185
2350
  }
2186
2351
  function check(locations) {
2187
2352
  if (locations.length === 0) return;
@@ -2195,8 +2360,8 @@ const noUnknownClasses = defineRule({
2195
2360
  if (shouldIgnore(cls)) continue;
2196
2361
  const validity = cache.classValidity(cls);
2197
2362
  if (validity === "valid") continue;
2198
- const stripped = stripModifiers(cls);
2199
- if (DEPRECATED_MAP[stripped]) continue;
2363
+ const { variant, bare, position } = strippedUtility(cls);
2364
+ if (DEPRECATED_MAP[bare]) continue;
2200
2365
  if (validity === "missing-prefix") {
2201
2366
  const fixed = `${cache.prefix}:${cls}`;
2202
2367
  const fixedValue = rebuildClassString(split, classes.map((c) => c === cls ? fixed : c));
@@ -2221,7 +2386,8 @@ const noUnknownClasses = defineRule({
2221
2386
  });
2222
2387
  continue;
2223
2388
  }
2224
- const suggestion = findBestSuggestion(stripped, cache.validClasses);
2389
+ const suggestionBare = findBestSuggestion(bare, cache.validClasses);
2390
+ const suggestion = suggestionBare ? variant + reattachImportant(suggestionBare, position) : null;
2225
2391
  if (suggestion) {
2226
2392
  const fixedValue = rebuildClassString(split, classes.map((c) => c === cls ? suggestion : c));
2227
2393
  context.report({
@@ -2381,7 +2547,7 @@ const noConflictingClasses = defineRule({
2381
2547
  }],
2382
2548
  defaultOptions: [{}],
2383
2549
  messages: {
2384
- conflict: "\"{{classA}}\" and \"{{classB}}\" affect {{properties}}. \"{{winner}}\" takes precedence (appears later).",
2550
+ 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
2551
  ...DS_UNAVAILABLE_MESSAGE
2386
2552
  }
2387
2553
  },
@@ -2414,9 +2580,11 @@ const noConflictingClasses = defineRule({
2414
2580
  const propsA = propsMap.get(classA) ?? [];
2415
2581
  for (let j = i + 1; j < variantClasses.length; j++) {
2416
2582
  const classB = variantClasses[j];
2583
+ if (classA === classB) continue;
2417
2584
  const propsB = propsMap.get(classB) ?? [];
2418
2585
  if (shouldSkipPair(classA, classB, propsA, propsB)) continue;
2419
- const overlap = propsA.filter((p) => propsB.includes(p));
2586
+ const propsBSet = new Set(propsB);
2587
+ const overlap = propsA.filter((p) => propsBSet.has(p));
2420
2588
  if (overlap.length > 0) {
2421
2589
  const propList = overlap.length <= 3 ? `"${overlap.join("\", \"")}"` : `${overlap.length} CSS properties`;
2422
2590
  context.report({
@@ -2425,8 +2593,7 @@ const noConflictingClasses = defineRule({
2425
2593
  data: {
2426
2594
  classA,
2427
2595
  classB,
2428
- properties: propList,
2429
- winner: classB
2596
+ properties: propList
2430
2597
  }
2431
2598
  });
2432
2599
  }
@@ -2458,16 +2625,104 @@ const noConflictingClasses = defineRule({
2458
2625
  */
2459
2626
  const BUFFER_SIZE = 4 * 1024 * 1024;
2460
2627
  const HEADER_INTS = 4;
2628
+ const LENGTH_OFFSET = HEADER_INTS * 4;
2461
2629
  const DATA_OFFSET = 20;
2462
2630
  const INIT_TIMEOUT = 6e4;
2463
2631
  const REQUEST_TIMEOUT = 3e4;
2632
+ /**
2633
+ * Build the worker script shared by `sort-service` and `canonicalize-service`.
2634
+ * Owns the entire SharedArrayBuffer protocol (offsets derived from the same
2635
+ * constants the host uses, so they can't drift), the design-system load with
2636
+ * error propagation (DS-M4: the real cause is written into the buffer so the
2637
+ * host can surface it, not a generic "failed to load"), the ready signal, and
2638
+ * the request loop. `handlerExpr` is a function expression `(ds, request) =>
2639
+ * result` — the only part that differs between services.
2640
+ */
2641
+ function makeWorkerScript(handlerExpr) {
2642
+ return `
2643
+ const { workerData } = require('worker_threads');
2644
+ async function main() {
2645
+ const { sharedBuffer, cssPath } = workerData;
2646
+ const control = new Int32Array(sharedBuffer, 0, ${HEADER_INTS});
2647
+ const lengthView = new DataView(sharedBuffer, ${LENGTH_OFFSET}, 4);
2648
+ const dataArea = new Uint8Array(sharedBuffer, ${DATA_OFFSET});
2649
+
2650
+ // On load failure, write the real cause into the data region so the host can
2651
+ // report it instead of a bare "failed to load the design system".
2652
+ function signalLoadError(e) {
2653
+ try {
2654
+ const msg = Buffer.from(String((e && e.message) || e || 'unknown design-system load error'), 'utf-8');
2655
+ const n = Math.min(msg.length, dataArea.length);
2656
+ dataArea.set(msg.subarray(0, n), 0);
2657
+ lengthView.setUint32(0, n);
2658
+ } catch {}
2659
+ Atomics.store(control, 2, -1);
2660
+ Atomics.notify(control, 2);
2661
+ }
2662
+
2663
+ let ds;
2664
+ try {
2665
+ const { __unstable__loadDesignSystem } = require(workerData.tailwindNodePath);
2666
+ const { readFileSync } = require('fs');
2667
+ const { dirname } = require('path');
2668
+ const css = readFileSync(cssPath, 'utf-8');
2669
+ ds = await __unstable__loadDesignSystem(css, { base: dirname(cssPath) });
2670
+ } catch (e) {
2671
+ signalLoadError(e);
2672
+ return;
2673
+ }
2674
+
2675
+ Atomics.store(control, 2, 1);
2676
+ Atomics.notify(control, 2);
2677
+
2678
+ const handler = ${handlerExpr};
2679
+
2680
+ while (true) {
2681
+ Atomics.wait(control, 0, 0);
2682
+ const len = lengthView.getUint32(0);
2683
+ const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
2684
+ Atomics.store(control, 0, 0);
2685
+
2686
+ let response;
2687
+ try {
2688
+ const request = JSON.parse(requestStr);
2689
+ const result = handler(ds, request);
2690
+ response = Buffer.from(JSON.stringify(result), 'utf-8');
2691
+ } catch {
2692
+ response = Buffer.from('null', 'utf-8');
2693
+ }
2694
+
2695
+ // DS-M6: if the response doesn't fit the shared buffer, reply with a
2696
+ // sentinel the host reads as a rejected request, instead of letting
2697
+ // dataArea.set throw and kill the worker (which would hang the caller
2698
+ // until the request timeout and then report a misleading timeout).
2699
+ if (response.length > dataArea.length) {
2700
+ response = Buffer.from('null', 'utf-8');
2701
+ }
2702
+
2703
+ dataArea.set(response, 0);
2704
+ lengthView.setUint32(0, response.length);
2705
+ Atomics.store(control, 1, 1);
2706
+ Atomics.notify(control, 1);
2707
+ }
2708
+ }
2709
+ main().catch(() => {});
2710
+ `;
2711
+ }
2464
2712
  var DesignSystemWorker = class {
2465
2713
  opts;
2466
2714
  ready = null;
2467
2715
  lastError = null;
2716
+ lastErrorCssPath = null;
2468
2717
  constructor(opts) {
2469
2718
  this.opts = opts;
2470
2719
  }
2720
+ /** Record an error as sticky for `cssPath` and return it for `throw`. */
2721
+ remember(cssPath, err) {
2722
+ this.lastError = err;
2723
+ this.lastErrorCssPath = cssPath;
2724
+ return err;
2725
+ }
2471
2726
  /**
2472
2727
  * Ensure the worker is running and pointed at `cssPath`. Returns the
2473
2728
  * ready state. Throws `SortServiceError` on any failure (init timeout,
@@ -2475,14 +2730,12 @@ var DesignSystemWorker = class {
2475
2730
  * cssPath rethrow without retrying.
2476
2731
  */
2477
2732
  ensure(cssPath) {
2478
- if (this.lastError && this.ready?.cssPath === cssPath) throw this.lastError;
2733
+ if (this.lastError && this.lastErrorCssPath === cssPath) throw this.lastError;
2479
2734
  if (this.ready && this.ready.cssPath === cssPath) return this.ready;
2480
2735
  if (this.ready) this.cleanup();
2481
2736
  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
- }
2737
+ this.lastErrorCssPath = null;
2738
+ 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
2739
  const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
2487
2740
  const controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
2488
2741
  const lengthView = new DataView(sharedBuffer, HEADER_INTS * 4, 4);
@@ -2498,22 +2751,22 @@ var DesignSystemWorker = class {
2498
2751
  }
2499
2752
  });
2500
2753
  } 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;
2754
+ 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
2755
  }
2504
2756
  worker.unref();
2505
2757
  worker.on("error", (err) => {
2506
2758
  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 });
2759
+ this.lastErrorCssPath = cssPath;
2507
2760
  });
2508
2761
  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
2762
  this.terminateWorker(worker);
2511
- throw this.lastError;
2763
+ 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
2764
  }
2513
2765
  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.");
2766
+ const len = lengthView.getUint32(0);
2767
+ const detail = len > 0 ? Buffer.from(dataArea.slice(0, len)).toString("utf-8") : "";
2515
2768
  this.terminateWorker(worker);
2516
- throw this.lastError;
2769
+ 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
2770
  }
2518
2771
  this.ready = {
2519
2772
  worker,
@@ -2537,9 +2790,8 @@ var DesignSystemWorker = class {
2537
2790
  Atomics.store(state.controlArray, 0, 1);
2538
2791
  Atomics.notify(state.controlArray, 0);
2539
2792
  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
2793
  this.cleanup();
2542
- throw this.lastError;
2794
+ 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
2795
  }
2544
2796
  const responseLen = state.lengthView.getUint32(0);
2545
2797
  const responseStr = Buffer.from(state.dataArea.slice(0, responseLen)).toString("utf-8");
@@ -2548,20 +2800,19 @@ var DesignSystemWorker = class {
2548
2800
  try {
2549
2801
  parsed = JSON.parse(responseStr);
2550
2802
  } 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
2803
  this.cleanup();
2553
- throw this.lastError;
2804
+ 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
2805
  }
2555
2806
  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
2807
  this.cleanup();
2558
- throw this.lastError;
2808
+ 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
2809
  }
2560
2810
  return parsed;
2561
2811
  }
2562
2812
  reset() {
2563
2813
  this.cleanup();
2564
2814
  this.lastError = null;
2815
+ this.lastErrorCssPath = null;
2565
2816
  }
2566
2817
  cleanup() {
2567
2818
  if (this.ready) {
@@ -2593,60 +2844,14 @@ var DesignSystemWorker = class {
2593
2844
  * subsequent lookup is O(1).
2594
2845
  */
2595
2846
  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
- `,
2847
+ workerScript: makeWorkerScript(`(ds, request) => {
2848
+ const { classes, rem } = request;
2849
+ const options = rem ? { rem } : undefined;
2850
+ return classes.map((cls) => {
2851
+ const r = ds.canonicalizeCandidates([cls], options);
2852
+ return r[0] ?? cls;
2853
+ });
2854
+ }`),
2650
2855
  serviceName: "canonicalize"
2651
2856
  });
2652
2857
  /**
@@ -2691,7 +2896,7 @@ function canonicalizeClassesSync(cssPath, classes, rem) {
2691
2896
  for (let k = 0; k < uniqueMissing.length; k++) freshByClass.set(uniqueMissing[k], fresh[k]);
2692
2897
  for (let j = 0; j < missing.length; j++) {
2693
2898
  const cls = missing[j];
2694
- const value = freshByClass.get(cls) ?? cls;
2899
+ const value = roundRemValue(freshByClass.get(cls) ?? cls);
2695
2900
  canonCache.set(cachePrefix + cls, value);
2696
2901
  out[missingIdx[j]] = value;
2697
2902
  }
@@ -2783,62 +2988,17 @@ const enforceCanonical = defineRule({
2783
2988
  * Atomics.wait, fail-loud, sticky lastError) lives in `./ds-worker.ts`.
2784
2989
  */
2785
2990
  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
- `,
2991
+ workerScript: makeWorkerScript(`(ds, classes) => {
2992
+ const ordered = ds.getClassOrder(classes);
2993
+ return [...ordered]
2994
+ .sort((a, b) => {
2995
+ if (a[1] === null && b[1] === null) return 0;
2996
+ if (a[1] === null) return -1;
2997
+ if (b[1] === null) return 1;
2998
+ return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0;
2999
+ })
3000
+ .map(([name]) => name);
3001
+ }`),
2842
3002
  serviceName: "sort"
2843
3003
  });
2844
3004
  /**
@@ -2890,13 +3050,9 @@ const enforceSortOrder = defineRule({
2890
3050
  }
2891
3051
  function sortStrict(classes) {
2892
3052
  const groups = /* @__PURE__ */ new Map();
2893
- const groupOrder = [];
2894
3053
  for (const cls of classes) {
2895
3054
  const { variant } = splitUtilityAndVariant(cls);
2896
- if (!groups.has(variant)) {
2897
- groups.set(variant, []);
2898
- groupOrder.push(variant);
2899
- }
3055
+ if (!groups.has(variant)) groups.set(variant, []);
2900
3056
  groups.get(variant).push(cls);
2901
3057
  }
2902
3058
  for (const [, groupClasses] of groups) {
@@ -3078,26 +3234,6 @@ const enforceShorthand = defineRule({
3078
3234
  }
3079
3235
  });
3080
3236
  //#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
3237
  //#region src/rules/enforce-logical.ts
3102
3238
  const LOGICAL_PHYSICAL_SCHEMA = {
3103
3239
  type: "object",
@@ -3238,9 +3374,14 @@ function createDirectionalMapper(context, opts) {
3238
3374
  if (matchesAny(cls, allowlist)) return null;
3239
3375
  const { utility, variant } = splitUtilityAndVariant(cls);
3240
3376
  const { bare: bareUtility, position } = splitImportant(utility);
3377
+ const negative = bareUtility.startsWith("-");
3378
+ const core = negative ? bareUtility.slice(1) : bareUtility;
3241
3379
  for (const { from, to, axis } of opts.mappings) {
3242
3380
  if (direction !== "both" && direction !== axis) continue;
3243
- if (bareUtility === from || bareUtility.startsWith(`${from}-`)) return `${variant}${reattachImportant(to + bareUtility.slice(from.length), position)}`;
3381
+ if (core === from || core.startsWith(`${from}-`)) {
3382
+ const suffix = core.slice(from.length);
3383
+ return `${variant}${reattachImportant(`${negative ? "-" : ""}${to}${suffix}`, position)}`;
3384
+ }
3244
3385
  }
3245
3386
  return null;
3246
3387
  }
@@ -3383,10 +3524,16 @@ const noRestrictedClasses = defineRule({
3383
3524
  createOnce(context) {
3384
3525
  const getConfig = createLazyOptions(context, (o) => ({
3385
3526
  restrictedClasses: new Set(o?.classes ?? []),
3386
- patterns: (o?.patterns ?? []).map((p) => ({
3387
- regex: new RegExp(p.pattern),
3388
- message: p.message
3389
- }))
3527
+ patterns: (o?.patterns ?? []).flatMap((p) => {
3528
+ try {
3529
+ return [{
3530
+ regex: new RegExp(p.pattern),
3531
+ message: p.message
3532
+ }];
3533
+ } catch {
3534
+ return [];
3535
+ }
3536
+ })
3390
3537
  }));
3391
3538
  function check(locations) {
3392
3539
  const { restrictedClasses, patterns } = getConfig();
@@ -3515,6 +3662,7 @@ const enforceConsistentImportantPosition = defineRule({
3515
3662
  });
3516
3663
  //#endregion
3517
3664
  //#region src/rules/enforce-negative-arbitrary-values.ts
3665
+ const SIMPLE_DIMENSION = /^\d*\.?\d+[a-z%]*$/;
3518
3666
  function fixClass(cls) {
3519
3667
  const { utility, variant } = splitUtilityAndVariant(cls);
3520
3668
  const hasImportantPrefix = utility.startsWith("!");
@@ -3527,6 +3675,7 @@ function fixClass(cls) {
3527
3675
  if (bracketClose === -1 || bracketClose < bracketOpen) return null;
3528
3676
  const innerValue = bare.slice(bracketOpen + 1, bracketClose);
3529
3677
  if (innerValue.startsWith("-")) return null;
3678
+ if (!SIMPLE_DIMENSION.test(innerValue)) return null;
3530
3679
  const baseUtility = bare.slice(1, bracketOpen);
3531
3680
  return `${variant}${hasImportantPrefix ? "!" : ""}${baseUtility}[-${innerValue}]${hasImportantSuffix ? "!" : ""}`;
3532
3681
  }
@@ -3661,13 +3810,48 @@ const KNOWN_PREFIXES = [
3661
3810
  "via",
3662
3811
  "to"
3663
3812
  ];
3813
+ const PROPERTY_GROUP_BY_UTILITY = {};
3814
+ for (const u of [
3815
+ "block",
3816
+ "inline-block",
3817
+ "inline",
3818
+ "flex",
3819
+ "inline-flex",
3820
+ "grid",
3821
+ "inline-grid",
3822
+ "flow-root",
3823
+ "contents",
3824
+ "table",
3825
+ "inline-table",
3826
+ "table-caption",
3827
+ "table-cell",
3828
+ "table-row",
3829
+ "table-row-group",
3830
+ "table-header-group",
3831
+ "table-footer-group",
3832
+ "table-column",
3833
+ "table-column-group",
3834
+ "list-item",
3835
+ "hidden"
3836
+ ]) PROPERTY_GROUP_BY_UTILITY[u] = "display";
3837
+ for (const u of [
3838
+ "static",
3839
+ "fixed",
3840
+ "absolute",
3841
+ "relative",
3842
+ "sticky"
3843
+ ]) PROPERTY_GROUP_BY_UTILITY[u] = "position";
3664
3844
  /**
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.
3845
+ * Maps a utility to a key identifying the CSS property it sets, so a base and a
3846
+ * variant class for the same property group together. Exact-match equivalence
3847
+ * groups (display, position) win; otherwise fall back to the prefix heuristic
3848
+ * (e.g. "bg" from "bg-gray-900", "text" from "text-white").
3667
3849
  */
3668
3850
  function getUtilityPrefix(utility) {
3669
3851
  let u = splitImportant(utility).bare;
3670
3852
  if (u.startsWith("-")) u = u.slice(1);
3853
+ const group = PROPERTY_GROUP_BY_UTILITY[u];
3854
+ if (group) return group;
3671
3855
  for (const prefix of KNOWN_PREFIXES) if (u === prefix || u.startsWith(`${prefix}-`)) return prefix;
3672
3856
  const dashIdx = u.indexOf("-");
3673
3857
  return dashIdx >= 0 ? u.slice(0, dashIdx) : u;
@@ -3775,13 +3959,10 @@ const noHardcodedColors = defineRule({
3775
3959
  docs: { description: "Disallow hardcoded color values in Tailwind CSS classes" },
3776
3960
  schema: [{
3777
3961
  type: "object",
3778
- properties: {
3779
- entryPoint: { type: "string" },
3780
- allow: {
3781
- type: "array",
3782
- items: { type: "string" }
3783
- }
3784
- },
3962
+ properties: { allow: {
3963
+ type: "array",
3964
+ items: { type: "string" }
3965
+ } },
3785
3966
  additionalProperties: false
3786
3967
  }],
3787
3968
  defaultOptions: [{ allow: [] }],
@@ -3813,24 +3994,6 @@ const noHardcodedColors = defineRule({
3813
3994
  });
3814
3995
  //#endregion
3815
3996
  //#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
3997
  const noContradictingVariants = defineRule({
3835
3998
  meta: {
3836
3999
  type: "suggestion",
@@ -3865,18 +4028,6 @@ const noContradictingVariants = defineRule({
3865
4028
  });
3866
4029
  //#endregion
3867
4030
  //#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
4031
  const DEFAULT_VARIANT_ORDER = [
3881
4032
  "*",
3882
4033
  "**",
@@ -3975,17 +4126,12 @@ const consistentVariantOrder = defineRule({
3975
4126
  },
3976
4127
  createOnce(context) {
3977
4128
  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) {
4129
+ const getOptions = createLazyOptions(context, (o) => ({ order: o?.order }));
4130
+ function buildPriority(order, dsCache) {
4131
+ if (order) {
3986
4132
  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;
4133
+ for (let i = 0; i < order.length; i++) map.set(order[i], i);
4134
+ const fallback = order.length;
3989
4135
  return (v) => map.get(v) ?? fallback;
3990
4136
  }
3991
4137
  if (dsCache && dsCache.hasVariantOrder()) {
@@ -3996,17 +4142,36 @@ const consistentVariantOrder = defineRule({
3996
4142
  for (let i = 0; i < DEFAULT_VARIANT_ORDER.length; i++) map.set(DEFAULT_VARIANT_ORDER[i], i);
3997
4143
  const fallback = DEFAULT_VARIANT_ORDER.length;
3998
4144
  return (v) => map.get(v) ?? fallback;
3999
- });
4000
- const getPrefix = createLazyOptions(context, () => {
4145
+ }
4146
+ const priorityByEntry = /* @__PURE__ */ new Map();
4147
+ const prefixByEntry = /* @__PURE__ */ new Map();
4148
+ function resolveForFile() {
4149
+ let dsCache = null;
4150
+ let entryKey = "";
4001
4151
  try {
4002
- return getDS().cache.prefix;
4152
+ const ds = getDS();
4153
+ dsCache = ds.cache;
4154
+ entryKey = ds.entryPoint;
4003
4155
  } catch (err) {
4004
4156
  if (!isFatalError(err)) throw err;
4005
- return "";
4006
4157
  }
4007
- });
4158
+ let priorityOf = priorityByEntry.get(entryKey);
4159
+ if (!priorityOf) {
4160
+ priorityOf = buildPriority(getOptions().order, dsCache);
4161
+ priorityByEntry.set(entryKey, priorityOf);
4162
+ }
4163
+ let prefix = prefixByEntry.get(entryKey);
4164
+ if (prefix === void 0) {
4165
+ prefix = dsCache?.prefix ?? "";
4166
+ prefixByEntry.set(entryKey, prefix);
4167
+ }
4168
+ return {
4169
+ priorityOf,
4170
+ prefix
4171
+ };
4172
+ }
4008
4173
  function reorderClass(cls) {
4009
- const prefix = getPrefix();
4174
+ const { priorityOf, prefix } = resolveForFile();
4010
4175
  let pfx = "";
4011
4176
  let body = cls;
4012
4177
  if (prefix && cls.startsWith(prefix + ":")) {
@@ -4015,13 +4180,25 @@ const consistentVariantOrder = defineRule({
4015
4180
  }
4016
4181
  const variants = extractVariants(body);
4017
4182
  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
4183
  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;
4184
+ const rest = [];
4185
+ for (const v of variants) if (isPseudoElementVariant(v)) pseudo.push(v);
4186
+ else rest.push(v);
4187
+ const reorderedRest = [];
4188
+ let segment = [];
4189
+ const flushSegment = () => {
4190
+ if (segment.length === 0) return;
4191
+ segment.sort((a, b) => priorityOf(a) - priorityOf(b));
4192
+ reorderedRest.push(...segment);
4193
+ segment = [];
4194
+ };
4195
+ for (const v of rest) if (isSelectorBarrier(v)) {
4196
+ flushSegment();
4197
+ reorderedRest.push(v);
4198
+ } else segment.push(v);
4199
+ flushSegment();
4200
+ pseudo.sort((a, b) => priorityOf(a) - priorityOf(b));
4201
+ const final = [...reorderedRest, ...pseudo];
4025
4202
  if (variants.every((v, i) => v === final[i])) return null;
4026
4203
  const utility = extractUtility(body);
4027
4204
  return pfx + final.join(":") + ":" + utility;
@@ -4298,5 +4475,3 @@ const plugin = definePlugin({
4298
4475
  });
4299
4476
  //#endregion
4300
4477
  export { plugin as default };
4301
-
4302
- //# sourceMappingURL=index.mjs.map