oxlint-tailwindcss 1.1.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.cjs CHANGED
@@ -4,6 +4,26 @@ let node_crypto = require("node:crypto");
4
4
  let node_fs = require("node:fs");
5
5
  let node_path = require("node:path");
6
6
  let node_os = require("node:os");
7
+ //#region src/utils/allowlist.ts
8
+ /**
9
+ * Shared regex-allowlist helpers used by rules that accept an `allowlist`
10
+ * option of regex source strings (currently enforce-logical / enforce-physical).
11
+ *
12
+ * Invalid regex sources are skipped rather than thrown so a typo in one
13
+ * pattern doesn't blow up the entire lint run.
14
+ */
15
+ function compileRegexList(patterns) {
16
+ if (!patterns || patterns.length === 0) return [];
17
+ const compiled = [];
18
+ for (const p of patterns) try {
19
+ compiled.push(new RegExp(p));
20
+ } catch {}
21
+ return compiled;
22
+ }
23
+ function matchesAny(value, list) {
24
+ return list.some((re) => re.test(value));
25
+ }
26
+ //#endregion
7
27
  //#region src/utils/extractors.ts
8
28
  /**
9
29
  * Preserves leading/trailing spaces in fixed class strings for template literals.
@@ -81,7 +101,7 @@ function getExtractorConfig(context) {
81
101
  attributes: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.attributes, tw.attributes, exclude?.attributes),
82
102
  callees: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.callees, tw.callees, exclude?.callees),
83
103
  tags: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.tags, tw.tags, exclude?.tags),
84
- variablePatterns: [...filteredPatterns, ...(tw.variablePatterns ?? []).map((p) => new RegExp(p))]
104
+ variablePatterns: [...filteredPatterns, ...compileRegexList(tw.variablePatterns)]
85
105
  };
86
106
  configCache.set(context, resolved);
87
107
  return resolved;
@@ -352,6 +372,9 @@ function getCalleeName(node) {
352
372
  }
353
373
  //#endregion
354
374
  //#region src/utils/class-splitter.ts
375
+ function isWhitespace(char) {
376
+ return char === " " || char === " " || char === "\n" || char === "\r" || char === "\f" || char === "\v";
377
+ }
355
378
  /**
356
379
  * Splits a Tailwind class string respecting:
357
380
  * - Nested brackets: bg-[url('...')], h-[calc(100%+2rem)]
@@ -374,9 +397,9 @@ function splitClasses(classString) {
374
397
  }
375
398
  if (!inSingleQuote && !inDoubleQuote) {
376
399
  if (char === "[") bracketDepth++;
377
- if (char === "]") bracketDepth--;
400
+ if (char === "]") bracketDepth = Math.max(0, bracketDepth - 1);
378
401
  }
379
- if (/\s/.test(char) && bracketDepth === 0) {
402
+ if (isWhitespace(char) && bracketDepth === 0) {
380
403
  if (current.length > 0) {
381
404
  classes.push(current);
382
405
  current = "";
@@ -403,9 +426,9 @@ function splitClassesWithSeparators(classString) {
403
426
  }
404
427
  if (!inSingleQuote && !inDoubleQuote) {
405
428
  if (char === "[") bracketDepth++;
406
- if (char === "]") bracketDepth--;
429
+ if (char === "]") bracketDepth = Math.max(0, bracketDepth - 1);
407
430
  }
408
- if (/\s/.test(char) && bracketDepth === 0) {
431
+ if (isWhitespace(char) && bracketDepth === 0) {
409
432
  if (current.length > 0) {
410
433
  classes.push(current);
411
434
  separators.push(currentSep);
@@ -691,6 +714,52 @@ function reattachImportant(bare, position) {
691
714
  if (position === "suffix") return `${bare}!`;
692
715
  return bare;
693
716
  }
717
+ /**
718
+ * Pseudo-element variants. They select a generated box (`::before`, `::marker`,
719
+ * …) rather than the element itself, so they must sit innermost in the variant
720
+ * chain (closest to the utility). Canonical home shared by
721
+ * `consistent-variant-order` (partitions them last) and
722
+ * `no-contradicting-variants` (they can't contradict a base class).
723
+ */
724
+ const PSEUDO_ELEMENT_VARIANTS = new Set([
725
+ "before",
726
+ "after",
727
+ "file",
728
+ "placeholder",
729
+ "selection",
730
+ "marker",
731
+ "backdrop",
732
+ "first-line",
733
+ "first-letter",
734
+ "details-content"
735
+ ]);
736
+ function isPseudoElementVariant(variant) {
737
+ return PSEUDO_ELEMENT_VARIANTS.has(variant);
738
+ }
739
+ /**
740
+ * Selector barriers: variants that re-point the selector at a *different*
741
+ * element than the ones around them — child (`*`), descendant (`**`),
742
+ * arbitrary selectors (`[&>svg]`) and compound child selectors (`*:data-[…]`).
743
+ *
744
+ * Unlike pseudo-elements, these are NOT free to move to the end of the chain:
745
+ * `hover:*:flex` (`&:hover > *`) and `*:hover:flex` (`& > *:hover`) target
746
+ * different elements. `consistent-variant-order` treats them as hard
747
+ * reordering barriers — variants never cross them.
748
+ */
749
+ function isSelectorBarrier(variant) {
750
+ if (variant === "*" || variant === "**") return true;
751
+ if (variant.startsWith("[") && variant.endsWith("]")) return true;
752
+ if (variant.startsWith("*:")) return true;
753
+ return false;
754
+ }
755
+ /**
756
+ * Whether a variant changes the selector target (pseudo-element OR selector
757
+ * barrier). Such variants don't impose a condition on the same element, so they
758
+ * can't make a variant class contradict/duplicate a base class.
759
+ */
760
+ function changesTarget(variant) {
761
+ return isPseudoElementVariant(variant) || isSelectorBarrier(variant);
762
+ }
694
763
  //#endregion
695
764
  //#region src/utils/floating-point.ts
696
765
  /**
@@ -718,6 +787,8 @@ var DesignSystemCache = class DesignSystemCache {
718
787
  _validClasses = [];
719
788
  _knownPrefixes = null;
720
789
  _maxOrder = 0n;
790
+ _prefix = "";
791
+ componentSet = /* @__PURE__ */ new Set();
721
792
  static fromPrecomputed(data) {
722
793
  const cache = new DesignSystemCache();
723
794
  cache._validClasses = data.validClasses;
@@ -730,7 +801,11 @@ var DesignSystemCache = class DesignSystemCache {
730
801
  }
731
802
  for (const [cls, props] of Object.entries(data.cssProps)) cache.cssPropsMap.set(cls, props);
732
803
  if (data.variantOrder) for (const [name, index] of Object.entries(data.variantOrder)) cache.variantOrderMap.set(name, index);
733
- if (data.componentClasses) for (const cls of data.componentClasses) cache.validitySet.add(cls);
804
+ if (data.componentClasses) for (const cls of data.componentClasses) {
805
+ cache.validitySet.add(cls);
806
+ cache.componentSet.add(cls);
807
+ }
808
+ cache._prefix = data.prefix ?? "";
734
809
  if (data.arbitraryEquivalents) for (const [arb, named] of Object.entries(data.arbitraryEquivalents)) cache.arbitraryEquivMap.set(arb, named);
735
810
  return cache;
736
811
  }
@@ -740,6 +815,10 @@ var DesignSystemCache = class DesignSystemCache {
740
815
  get maxOrder() {
741
816
  return this._maxOrder;
742
817
  }
818
+ /** Tailwind v4 project prefix (e.g. 'tw'); '' when none is configured. */
819
+ get prefix() {
820
+ return this._prefix;
821
+ }
743
822
  canonicalize(className) {
744
823
  const cached = this.canonicalMap.get(className);
745
824
  if (cached !== void 0) return cached;
@@ -838,7 +917,32 @@ var DesignSystemCache = class DesignSystemCache {
838
917
  if (bare.includes("(") && bare.includes(")")) return true;
839
918
  return false;
840
919
  }
920
+ /**
921
+ * Strict validity for `no-unknown-classes`, prefix-aware.
922
+ *
923
+ * - `'valid'` — usable as written.
924
+ * - `'missing-prefix'`— a real Tailwind utility written WITHOUT the required
925
+ * project prefix (`flex` under `prefix(tw)`); generates no CSS.
926
+ * - `'unknown'` — not a recognized class.
927
+ *
928
+ * When no prefix is configured this collapses to the tolerant `isValid`
929
+ * behavior. `isValid` itself stays tolerant (other rules call it with
930
+ * prefix-free candidates), so the strict check lives here.
931
+ */
932
+ classValidity(className) {
933
+ if (!this._prefix) return this.isValid(className) ? "valid" : "unknown";
934
+ const tag = this._prefix + ":";
935
+ const hadPrefix = className.startsWith(tag);
936
+ const body = hadPrefix ? className.slice(tag.length) : className;
937
+ let baseUtility = splitImportant(extractUtility(body)).bare;
938
+ const slashIdx = baseUtility.lastIndexOf("/");
939
+ if (slashIdx > 0) baseUtility = baseUtility.slice(0, slashIdx);
940
+ if (this.componentSet.has(baseUtility)) return "valid";
941
+ if (this.isValid(body)) return hadPrefix ? "valid" : "missing-prefix";
942
+ return "unknown";
943
+ }
841
944
  getOrder(className) {
945
+ if (this._prefix && className.startsWith(this._prefix + ":")) className = className.slice(this._prefix.length + 1);
842
946
  const cached = this.orderMap.get(className);
843
947
  if (cached !== void 0) return cached;
844
948
  const utility = extractUtility(className);
@@ -1082,6 +1186,12 @@ function signalError(e) {
1082
1186
  Atomics.store(control, 2, -1);
1083
1187
  Atomics.notify(control, 2);
1084
1188
  }
1189
+ // Everything below — including the top-level require()s — runs inside this try
1190
+ // so any SYNCHRONOUS module-scope failure (a broken @tailwindcss/node install,
1191
+ // missing fs/path) is routed through signalError. Without it the worker would
1192
+ // die unsignaled and the main thread would block until the full timeout, then
1193
+ // report a misleading "timed out" instead of the real cause.
1194
+ try {
1085
1195
  // Resolve @tailwindcss/node via an absolute path passed in by the parent —
1086
1196
  // bare-specifier lookup from the worker's cwd fails under pnpm strict
1087
1197
  // workspaces (the module lives under node_modules/.pnpm/... which is not on the
@@ -1169,6 +1279,16 @@ async function main() {
1169
1279
  const base = dirname(cssPath);
1170
1280
  const ds = await __unstable__loadDesignSystem(css, { base });
1171
1281
 
1282
+ // Tailwind v4 project prefix (\`@import "tailwindcss" prefix(tw)\`). getClassList()
1283
+ // returns names WITHOUT the prefix, but candidatesToCss/getClassOrder/
1284
+ // canonicalizeCandidates only resolve the PREFIXED form (\`tw:flex\`). We apply
1285
+ // the prefix only when calling the DS and strip it back off before storing, so
1286
+ // every structure stays prefix-free. The prefix is alphanumeric (no ':' '-' '['
1287
+ // ']' '/'), so \`prefix + ':'\` is an unambiguous separator.
1288
+ const prefix = (ds.theme && ds.theme.prefix) || '';
1289
+ const pfx = (c) => prefix ? prefix + ':' + c : c;
1290
+ const unpfx = (c) => (prefix && c.startsWith(prefix + ':')) ? c.slice(prefix.length + 1) : c;
1291
+
1172
1292
  const entries = ds.getClassList();
1173
1293
  const classNames = entries.map(e => e[0]);
1174
1294
 
@@ -1176,8 +1296,10 @@ async function main() {
1176
1296
  const classNameIndex = new Map();
1177
1297
  for (let i = 0; i < classNames.length; i++) classNameIndex.set(classNames[i], i);
1178
1298
 
1179
- // Validity: which classes produce CSS
1180
- const cssResults = ds.candidatesToCss(classNames);
1299
+ // Validity: which classes produce CSS. Validate the prefixed form, but keep
1300
+ // cssResults aligned positionally to the unprefixed classNames so the later
1301
+ // cssProps / arbitraryEquivalents phases keep indexing by position.
1302
+ const cssResults = ds.candidatesToCss(classNames.map(pfx));
1181
1303
  const validClasses = classNames.filter((_, i) => cssResults[i] != null);
1182
1304
 
1183
1305
  // Expand: validate extra candidates not in getClassList() but valid in v4
@@ -1199,7 +1321,7 @@ async function main() {
1199
1321
  }
1200
1322
  }
1201
1323
  if (extraCandidates.length > 0) {
1202
- const extraResults = ds.candidatesToCss(extraCandidates);
1324
+ const extraResults = ds.candidatesToCss(extraCandidates.map(pfx));
1203
1325
  for (let i = 0; i < extraCandidates.length; i++) {
1204
1326
  if (extraResults[i] != null) {
1205
1327
  validClasses.push(extraCandidates[i]);
@@ -1228,9 +1350,11 @@ async function main() {
1228
1350
  // NOTE: canonicalizeCandidates deduplicates, so we must call it one class at a time
1229
1351
  const canonical = {};
1230
1352
  for (const cls of classNames) {
1231
- const result = ds.canonicalizeCandidates([cls]);
1232
- if (result[0] && result[0] !== cls) {
1233
- canonical[cls] = result[0];
1353
+ const result = ds.canonicalizeCandidates([pfx(cls)]);
1354
+ const canon = result[0] ? unpfx(result[0]) : null;
1355
+ // Compare unprefixed-vs-unprefixed so the prefix itself never reads as a change.
1356
+ if (canon && canon !== cls) {
1357
+ canonical[cls] = canon;
1234
1358
  }
1235
1359
  }
1236
1360
 
@@ -1261,13 +1385,14 @@ async function main() {
1261
1385
  }
1262
1386
  const legacyToProcess = legacyCandidates.filter(cls => !validSet.has(cls));
1263
1387
  if (legacyToProcess.length > 0) {
1264
- const legacyCssResults = ds.candidatesToCss(legacyToProcess);
1388
+ const legacyCssResults = ds.candidatesToCss(legacyToProcess.map(pfx));
1265
1389
  for (let i = 0; i < legacyToProcess.length; i++) {
1266
1390
  if (legacyCssResults[i] == null) continue;
1267
1391
  const cls = legacyToProcess[i];
1268
- const result = ds.canonicalizeCandidates([cls]);
1269
- if (result[0] && result[0] !== cls) {
1270
- canonical[cls] = result[0];
1392
+ const result = ds.canonicalizeCandidates([pfx(cls)]);
1393
+ const canon = result[0] ? unpfx(result[0]) : null;
1394
+ if (canon && canon !== cls) {
1395
+ canonical[cls] = canon;
1271
1396
  }
1272
1397
  // Mark as valid so no-unknown-classes doesn't flag legacy spellings.
1273
1398
  validClasses.push(cls);
@@ -1281,9 +1406,9 @@ async function main() {
1281
1406
  if (!classNameIndex.has(cls)) allForOrder.push(cls);
1282
1407
  }
1283
1408
  const order = {};
1284
- const orderResults = ds.getClassOrder(allForOrder);
1409
+ const orderResults = ds.getClassOrder(allForOrder.map(pfx));
1285
1410
  for (const [name, val] of orderResults) {
1286
- if (val !== null) order[name] = val.toString();
1411
+ if (val !== null) order[unpfx(name)] = val.toString();
1287
1412
  }
1288
1413
 
1289
1414
  // CSS properties per class — extract only from the ROOT selector, not descendant selectors.
@@ -1372,7 +1497,9 @@ async function main() {
1372
1497
 
1373
1498
  for (let i = 0; i < classNames.length; i++) {
1374
1499
  if (cssResults[i]) {
1375
- const props = extractRootCssProps(cssResults[i], classNames[i]);
1500
+ // Match against the prefixed selector (the CSS emits \`.tw\\:flex\`), but
1501
+ // store under the unprefixed key. extractRootCssProps CSS-escapes the ':'.
1502
+ const props = extractRootCssProps(cssResults[i], pfx(classNames[i]));
1376
1503
  if (props.length > 0) cssProps[classNames[i]] = props;
1377
1504
  }
1378
1505
  }
@@ -1398,7 +1525,8 @@ async function main() {
1398
1525
  let acm;
1399
1526
  attrClassRe.lastIndex = 0;
1400
1527
  while ((acm = attrClassRe.exec(cssResults[i])) !== null) {
1401
- componentClasses.push(acm[1]);
1528
+ // Typography-style plugins emit \`[class~="tw:not-prose"]\` under a prefix.
1529
+ componentClasses.push(unpfx(acm[1]));
1402
1530
  }
1403
1531
  }
1404
1532
  }
@@ -1433,7 +1561,10 @@ async function main() {
1433
1561
  }
1434
1562
  if (candidates.length > 0) {
1435
1563
  const arbForms = candidates.map(c => c.arbitraryForm);
1436
- const arbResults = ds.candidatesToCss(arbForms);
1564
+ // Prefix only the validation; keys/values stored stay prefix-free. The
1565
+ // declaration block extractDeclarations compares is identical with or
1566
+ // without the prefix (the prefix only affects the selector).
1567
+ const arbResults = ds.candidatesToCss(arbForms.map(pfx));
1437
1568
  for (let i = 0; i < candidates.length; i++) {
1438
1569
  if (!arbResults[i]) continue;
1439
1570
  if (extractDeclarations(arbResults[i]) === extractDeclarations(candidates[i].namedCss)) {
@@ -1442,7 +1573,7 @@ async function main() {
1442
1573
  }
1443
1574
  }
1444
1575
 
1445
- const json = JSON.stringify({ validClasses, canonical, order, cssProps, variantOrder, componentClasses, arbitraryEquivalents });
1576
+ const json = JSON.stringify({ validClasses, canonical, order, cssProps, variantOrder, componentClasses, arbitraryEquivalents, prefix });
1446
1577
  // Atomic write: write to a unique temp path then rename, so a peer isolate
1447
1578
  // busy-waiting on the cache file never observes a half-written JSON.
1448
1579
  writeFileSync(WD_TMP_PATH, json);
@@ -1451,8 +1582,20 @@ async function main() {
1451
1582
  main()
1452
1583
  .then(() => { Atomics.store(control, 2, 1); Atomics.notify(control, 2); })
1453
1584
  .catch((e) => signalError(e));
1585
+ } catch (e) {
1586
+ signalError(e);
1587
+ }
1454
1588
  `;
1455
- const CACHE_DIR = (0, node_path.join)((0, node_os.tmpdir)(), "oxlint-tailwindcss");
1589
+ function cacheDirName() {
1590
+ try {
1591
+ const info = (0, node_os.userInfo)();
1592
+ const id = typeof info.uid === "number" && info.uid >= 0 ? String(info.uid) : info.username;
1593
+ return `oxlint-tailwindcss-${String(id).replace(/[^a-zA-Z0-9_-]/g, "_")}`;
1594
+ } catch {
1595
+ return "oxlint-tailwindcss";
1596
+ }
1597
+ }
1598
+ const CACHE_DIR = (0, node_path.join)((0, node_os.tmpdir)(), cacheDirName());
1456
1599
  /**
1457
1600
  * Cache key derived from:
1458
1601
  * - md5(PRECOMPUTE_SCRIPT): auto-invalidates when our precompute logic changes,
@@ -1471,17 +1614,73 @@ const CACHE_KEY = computeCacheKey(PRECOMPUTE_SCRIPT, TAILWIND_NODE_VERSION);
1471
1614
  function computeContentHash(content) {
1472
1615
  return (0, node_crypto.createHash)("md5").update(`${CACHE_KEY}:${content}`).digest("hex");
1473
1616
  }
1617
+ const IMPORT_RE = /@import\s+(?:url\(\s*)?['"]([^'"]+)['"]/g;
1618
+ /**
1619
+ * Concatenate the entry CSS with the content of its locally-imported files, so
1620
+ * the cache key invalidates when an `@import`'d file changes — not only when the
1621
+ * entry itself does (DS-A2). Without this, editing a `@theme`/component file
1622
+ * pulled in via `@import "./theme.css"` served a stale design system until the
1623
+ * entry was touched or the Tailwind version changed.
1624
+ *
1625
+ * Resolves RELATIVE imports (`./`, `../`) recursively up to a small depth;
1626
+ * package imports (`@import "tailwindcss"`, `tw-animate-css`) are already
1627
+ * covered by the `@tailwindcss/node` version baked into CACHE_KEY. Best-effort:
1628
+ * an unreadable import contributes nothing (it can't affect the DS either).
1629
+ */
1630
+ function hashableContent(entryPath, entryContent) {
1631
+ const parts = [entryContent];
1632
+ const seen = new Set([(0, node_path.resolve)(entryPath)]);
1633
+ const visit = (cssPath, content, depth) => {
1634
+ if (depth <= 0) return;
1635
+ const baseDir = (0, node_path.dirname)(cssPath);
1636
+ IMPORT_RE.lastIndex = 0;
1637
+ const specifiers = [];
1638
+ let m;
1639
+ while ((m = IMPORT_RE.exec(content)) !== null) if (m[1].startsWith(".")) specifiers.push(m[1]);
1640
+ for (const spec of specifiers) {
1641
+ const importPath = (0, node_path.resolve)(baseDir, spec.split("?")[0]);
1642
+ if (seen.has(importPath)) continue;
1643
+ seen.add(importPath);
1644
+ let importContent;
1645
+ try {
1646
+ importContent = (0, node_fs.readFileSync)(importPath, "utf-8");
1647
+ } catch {
1648
+ continue;
1649
+ }
1650
+ parts.push(importContent);
1651
+ visit(importPath, importContent, depth - 1);
1652
+ }
1653
+ };
1654
+ visit((0, node_path.resolve)(entryPath), entryContent, 4);
1655
+ return parts.join("\0");
1656
+ }
1474
1657
  function getContentCachePath(contentHash) {
1475
1658
  return (0, node_path.join)(CACHE_DIR, `${contentHash}.json`);
1476
1659
  }
1660
+ /**
1661
+ * Minimal shape check for a cache payload. Guards against (a) a poisoned file
1662
+ * planted by a local attacker and (b) a corrupt/half-written or version-skewed
1663
+ * file. A `{}` that is valid JSON but missing fields would otherwise blow up
1664
+ * later in `DesignSystemCache.fromPrecomputed` with a raw TypeError that isn't
1665
+ * plugin-fatal, breaking the lint with no diagnostic. We don't deep-validate
1666
+ * every entry — just enough that `fromPrecomputed` can rely on the fields.
1667
+ */
1668
+ function isPrecomputedData(data) {
1669
+ if (typeof data !== "object" || data === null) return false;
1670
+ const d = data;
1671
+ const isObject = (v) => typeof v === "object" && v !== null;
1672
+ 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);
1673
+ }
1477
1674
  function tryReadCache(cachePath) {
1478
1675
  const raw = tryReadRawCache(cachePath);
1479
1676
  if (raw === null) return null;
1677
+ let data;
1480
1678
  try {
1481
- return JSON.parse(raw);
1679
+ data = JSON.parse(raw);
1482
1680
  } catch {
1483
1681
  return null;
1484
1682
  }
1683
+ return isPrecomputedData(data) ? data : null;
1485
1684
  }
1486
1685
  function tryReadRawCache(cachePath) {
1487
1686
  try {
@@ -1508,6 +1707,23 @@ function tryUnlink(path) {
1508
1707
  (0, node_fs.unlinkSync)(path);
1509
1708
  } catch {}
1510
1709
  }
1710
+ /**
1711
+ * Reclaim a stale lock by exclusive rename rather than unlink (DS-M1). Two
1712
+ * waiters that both judge the lock stale would otherwise both `unlink` it — and
1713
+ * the second unlink could delete a FRESH lock a third isolate just created,
1714
+ * letting two precomputes run in parallel (the very amplification the lock
1715
+ * exists to prevent, #24). `renameSync` moves the file atomically: only one
1716
+ * waiter wins the move; the loser gets ENOENT and loops back to re-check.
1717
+ */
1718
+ function reclaimStaleLock(lockPath) {
1719
+ const reclaimPath = `${lockPath}.reclaim.${process.pid}.${node_worker_threads.threadId}.${precomputeSeq++}`;
1720
+ try {
1721
+ (0, node_fs.renameSync)(lockPath, reclaimPath);
1722
+ } catch {
1723
+ return;
1724
+ }
1725
+ tryUnlink(reclaimPath);
1726
+ }
1511
1727
  /** control[2] — the worker's ready/done signal (0=loading, 1=done, -1=error). */
1512
1728
  const PRECOMPUTE_SIGNAL_INDEX = 2;
1513
1729
  const ERR_BUFFER_SIZE = 64 * 1024;
@@ -1560,15 +1776,12 @@ function runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeo
1560
1776
  } catch (cause) {
1561
1777
  throw precomputeLoadError(resolvedPath, cause);
1562
1778
  }
1563
- let workerError;
1564
- worker.on("error", (err) => {
1565
- workerError = err;
1566
- });
1779
+ worker.on("error", () => {});
1567
1780
  try {
1568
1781
  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.");
1569
1782
  if (control[PRECOMPUTE_SIGNAL_INDEX] === -1) {
1570
1783
  const len = errLengthView.getUint32(0);
1571
- throw precomputeLoadError(resolvedPath, len > 0 ? new Error(Buffer.from(errDataArea.slice(0, len)).toString("utf-8")) : workerError);
1784
+ 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)"));
1572
1785
  }
1573
1786
  } finally {
1574
1787
  tryUnlink(tmpPath);
@@ -1576,14 +1789,17 @@ function runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeo
1576
1789
  }
1577
1790
  }
1578
1791
  /**
1579
- * Run the precompute worker, then read back the JSON it wrote to `cachePath`.
1580
- * Used by both the lock-winner path and the uncoordinated degrade path.
1792
+ * Run the precompute worker, then read back and validate the JSON it wrote to
1793
+ * `cachePath`. Used by both the lock-winner path and the uncoordinated degrade
1794
+ * path. Returns the validated `PrecomputedData` (never a raw string), so a
1795
+ * malformed payload surfaces as a clear diagnostic here instead of crashing
1796
+ * later in `DesignSystemCache.fromPrecomputed`.
1581
1797
  */
1582
1798
  function precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout) {
1583
1799
  runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeout);
1584
- const raw = tryReadRawCache(cachePath);
1585
- 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.");
1586
- return raw;
1800
+ const data = tryReadCache(cachePath);
1801
+ 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.");
1802
+ return data;
1587
1803
  }
1588
1804
  /**
1589
1805
  * Return the raw precompute JSON for `contentHash`, spawning at most one
@@ -1594,26 +1810,30 @@ function computeWithLock(resolvedPath, tailwindNodePath, contentHash, cachePath,
1594
1810
  const lockPath = (0, node_path.join)(CACHE_DIR, `${contentHash}.lock`);
1595
1811
  const staleMs = timeout + 3e4;
1596
1812
  try {
1597
- (0, node_fs.mkdirSync)(CACHE_DIR, { recursive: true });
1813
+ (0, node_fs.mkdirSync)(CACHE_DIR, {
1814
+ recursive: true,
1815
+ mode: 448
1816
+ });
1598
1817
  } catch {
1599
1818
  return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1600
1819
  }
1601
1820
  const start = Date.now();
1602
1821
  for (;;) {
1603
- const raw = tryReadRawCache(cachePath);
1604
- if (raw !== null) return raw;
1822
+ const cached = tryReadCache(cachePath);
1823
+ if (cached) return cached;
1605
1824
  let lockFd;
1606
1825
  try {
1607
1826
  lockFd = (0, node_fs.openSync)(lockPath, "wx");
1608
1827
  } catch (cause) {
1609
1828
  if (cause.code === "EEXIST") {
1610
- if (lockAgeMs(lockPath) > staleMs || Date.now() - start > staleMs * 2) tryUnlink(lockPath);
1829
+ if (lockAgeMs(lockPath) > staleMs || Date.now() - start > staleMs * 2) reclaimStaleLock(lockPath);
1611
1830
  else syncSleep(LOCK_POLL_MS);
1612
1831
  continue;
1613
1832
  }
1614
1833
  return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1615
1834
  }
1616
1835
  try {
1836
+ tryUnlink(cachePath);
1617
1837
  return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1618
1838
  } finally {
1619
1839
  (0, node_fs.closeSync)(lockFd);
@@ -1636,17 +1856,12 @@ function loadDesignSystemSync(cssPath, timeout) {
1636
1856
  } catch (cause) {
1637
1857
  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 });
1638
1858
  }
1639
- const contentHash = computeContentHash(content);
1859
+ const contentHash = computeContentHash(hashableContent(resolvedPath, content));
1640
1860
  const contentCachePath = getContentCachePath(contentHash);
1641
1861
  const cached = tryReadCache(contentCachePath);
1642
1862
  if (cached) return cached;
1643
1863
  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.");
1644
- const raw = computeWithLock(resolvedPath, TAILWIND_NODE_PATH, contentHash, contentCachePath, timeout ?? 6e4);
1645
- try {
1646
- return JSON.parse(raw);
1647
- } catch (cause) {
1648
- 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 });
1649
- }
1864
+ return computeWithLock(resolvedPath, TAILWIND_NODE_PATH, contentHash, contentCachePath, timeout ?? 6e4);
1650
1865
  }
1651
1866
  //#endregion
1652
1867
  //#region src/design-system/debug.ts
@@ -2104,6 +2319,7 @@ const noUnknownClasses = (0, _oxlint_plugins.defineRule)({
2104
2319
  messages: {
2105
2320
  unknown: "\"{{className}}\" is not a valid Tailwind class.",
2106
2321
  unknownWithSuggestion: "\"{{className}}\" is not a valid Tailwind class. Did you mean \"{{suggestion}}\"?",
2322
+ missingPrefix: "\"{{className}}\" needs the \"{{prefix}}:\" prefix to produce CSS. Did you mean \"{{suggestion}}\"?",
2107
2323
  suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
2108
2324
  ...DS_UNAVAILABLE_MESSAGE
2109
2325
  }
@@ -2119,8 +2335,14 @@ const noUnknownClasses = (0, _oxlint_plugins.defineRule)({
2119
2335
  if (allowlist.has(className)) return true;
2120
2336
  return ignorePrefixes.some((prefix) => className.startsWith(prefix));
2121
2337
  }
2122
- function stripModifiers(className) {
2123
- return splitImportant(className).bare;
2338
+ function strippedUtility(className) {
2339
+ const { utility, variant } = splitUtilityAndVariant(className);
2340
+ const { bare, position } = splitImportant(utility);
2341
+ return {
2342
+ variant,
2343
+ bare,
2344
+ position
2345
+ };
2124
2346
  }
2125
2347
  function check(locations) {
2126
2348
  if (locations.length === 0) return;
@@ -2132,10 +2354,36 @@ const noUnknownClasses = (0, _oxlint_plugins.defineRule)({
2132
2354
  const classes = split.classes;
2133
2355
  for (const cls of classes) {
2134
2356
  if (shouldIgnore(cls)) continue;
2135
- const stripped = stripModifiers(cls);
2136
- if (cache.isValid(stripped)) continue;
2137
- if (DEPRECATED_MAP[stripped]) continue;
2138
- const suggestion = findBestSuggestion(stripped, cache.validClasses);
2357
+ const validity = cache.classValidity(cls);
2358
+ if (validity === "valid") continue;
2359
+ const { variant, bare, position } = strippedUtility(cls);
2360
+ if (DEPRECATED_MAP[bare]) continue;
2361
+ if (validity === "missing-prefix") {
2362
+ const fixed = `${cache.prefix}:${cls}`;
2363
+ const fixedValue = rebuildClassString(split, classes.map((c) => c === cls ? fixed : c));
2364
+ context.report({
2365
+ node: loc.node,
2366
+ messageId: "missingPrefix",
2367
+ data: {
2368
+ className: cls,
2369
+ prefix: cache.prefix,
2370
+ suggestion: fixed
2371
+ },
2372
+ suggest: [{
2373
+ messageId: "suggestReplace",
2374
+ data: {
2375
+ className: cls,
2376
+ replacement: fixed
2377
+ },
2378
+ fix(fixer) {
2379
+ return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2380
+ }
2381
+ }]
2382
+ });
2383
+ continue;
2384
+ }
2385
+ const suggestionBare = findBestSuggestion(bare, cache.validClasses);
2386
+ const suggestion = suggestionBare ? variant + reattachImportant(suggestionBare, position) : null;
2139
2387
  if (suggestion) {
2140
2388
  const fixedValue = rebuildClassString(split, classes.map((c) => c === cls ? suggestion : c));
2141
2389
  context.report({
@@ -2295,7 +2543,7 @@ const noConflictingClasses = (0, _oxlint_plugins.defineRule)({
2295
2543
  }],
2296
2544
  defaultOptions: [{}],
2297
2545
  messages: {
2298
- conflict: "\"{{classA}}\" and \"{{classB}}\" affect {{properties}}. \"{{winner}}\" takes precedence (appears later).",
2546
+ conflict: "\"{{classA}}\" and \"{{classB}}\" both affect {{properties}}. Only one applies — which wins depends on the generated stylesheet order, not the attribute order. Remove one.",
2299
2547
  ...DS_UNAVAILABLE_MESSAGE
2300
2548
  }
2301
2549
  },
@@ -2328,9 +2576,11 @@ const noConflictingClasses = (0, _oxlint_plugins.defineRule)({
2328
2576
  const propsA = propsMap.get(classA) ?? [];
2329
2577
  for (let j = i + 1; j < variantClasses.length; j++) {
2330
2578
  const classB = variantClasses[j];
2579
+ if (classA === classB) continue;
2331
2580
  const propsB = propsMap.get(classB) ?? [];
2332
2581
  if (shouldSkipPair(classA, classB, propsA, propsB)) continue;
2333
- const overlap = propsA.filter((p) => propsB.includes(p));
2582
+ const propsBSet = new Set(propsB);
2583
+ const overlap = propsA.filter((p) => propsBSet.has(p));
2334
2584
  if (overlap.length > 0) {
2335
2585
  const propList = overlap.length <= 3 ? `"${overlap.join("\", \"")}"` : `${overlap.length} CSS properties`;
2336
2586
  context.report({
@@ -2339,8 +2589,7 @@ const noConflictingClasses = (0, _oxlint_plugins.defineRule)({
2339
2589
  data: {
2340
2590
  classA,
2341
2591
  classB,
2342
- properties: propList,
2343
- winner: classB
2592
+ properties: propList
2344
2593
  }
2345
2594
  });
2346
2595
  }
@@ -2372,16 +2621,104 @@ const noConflictingClasses = (0, _oxlint_plugins.defineRule)({
2372
2621
  */
2373
2622
  const BUFFER_SIZE = 4 * 1024 * 1024;
2374
2623
  const HEADER_INTS = 4;
2624
+ const LENGTH_OFFSET = HEADER_INTS * 4;
2375
2625
  const DATA_OFFSET = 20;
2376
2626
  const INIT_TIMEOUT = 6e4;
2377
2627
  const REQUEST_TIMEOUT = 3e4;
2628
+ /**
2629
+ * Build the worker script shared by `sort-service` and `canonicalize-service`.
2630
+ * Owns the entire SharedArrayBuffer protocol (offsets derived from the same
2631
+ * constants the host uses, so they can't drift), the design-system load with
2632
+ * error propagation (DS-M4: the real cause is written into the buffer so the
2633
+ * host can surface it, not a generic "failed to load"), the ready signal, and
2634
+ * the request loop. `handlerExpr` is a function expression `(ds, request) =>
2635
+ * result` — the only part that differs between services.
2636
+ */
2637
+ function makeWorkerScript(handlerExpr) {
2638
+ return `
2639
+ const { workerData } = require('worker_threads');
2640
+ async function main() {
2641
+ const { sharedBuffer, cssPath } = workerData;
2642
+ const control = new Int32Array(sharedBuffer, 0, ${HEADER_INTS});
2643
+ const lengthView = new DataView(sharedBuffer, ${LENGTH_OFFSET}, 4);
2644
+ const dataArea = new Uint8Array(sharedBuffer, ${DATA_OFFSET});
2645
+
2646
+ // On load failure, write the real cause into the data region so the host can
2647
+ // report it instead of a bare "failed to load the design system".
2648
+ function signalLoadError(e) {
2649
+ try {
2650
+ const msg = Buffer.from(String((e && e.message) || e || 'unknown design-system load error'), 'utf-8');
2651
+ const n = Math.min(msg.length, dataArea.length);
2652
+ dataArea.set(msg.subarray(0, n), 0);
2653
+ lengthView.setUint32(0, n);
2654
+ } catch {}
2655
+ Atomics.store(control, 2, -1);
2656
+ Atomics.notify(control, 2);
2657
+ }
2658
+
2659
+ let ds;
2660
+ try {
2661
+ const { __unstable__loadDesignSystem } = require(workerData.tailwindNodePath);
2662
+ const { readFileSync } = require('fs');
2663
+ const { dirname } = require('path');
2664
+ const css = readFileSync(cssPath, 'utf-8');
2665
+ ds = await __unstable__loadDesignSystem(css, { base: dirname(cssPath) });
2666
+ } catch (e) {
2667
+ signalLoadError(e);
2668
+ return;
2669
+ }
2670
+
2671
+ Atomics.store(control, 2, 1);
2672
+ Atomics.notify(control, 2);
2673
+
2674
+ const handler = ${handlerExpr};
2675
+
2676
+ while (true) {
2677
+ Atomics.wait(control, 0, 0);
2678
+ const len = lengthView.getUint32(0);
2679
+ const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
2680
+ Atomics.store(control, 0, 0);
2681
+
2682
+ let response;
2683
+ try {
2684
+ const request = JSON.parse(requestStr);
2685
+ const result = handler(ds, request);
2686
+ response = Buffer.from(JSON.stringify(result), 'utf-8');
2687
+ } catch {
2688
+ response = Buffer.from('null', 'utf-8');
2689
+ }
2690
+
2691
+ // DS-M6: if the response doesn't fit the shared buffer, reply with a
2692
+ // sentinel the host reads as a rejected request, instead of letting
2693
+ // dataArea.set throw and kill the worker (which would hang the caller
2694
+ // until the request timeout and then report a misleading timeout).
2695
+ if (response.length > dataArea.length) {
2696
+ response = Buffer.from('null', 'utf-8');
2697
+ }
2698
+
2699
+ dataArea.set(response, 0);
2700
+ lengthView.setUint32(0, response.length);
2701
+ Atomics.store(control, 1, 1);
2702
+ Atomics.notify(control, 1);
2703
+ }
2704
+ }
2705
+ main().catch(() => {});
2706
+ `;
2707
+ }
2378
2708
  var DesignSystemWorker = class {
2379
2709
  opts;
2380
2710
  ready = null;
2381
2711
  lastError = null;
2712
+ lastErrorCssPath = null;
2382
2713
  constructor(opts) {
2383
2714
  this.opts = opts;
2384
2715
  }
2716
+ /** Record an error as sticky for `cssPath` and return it for `throw`. */
2717
+ remember(cssPath, err) {
2718
+ this.lastError = err;
2719
+ this.lastErrorCssPath = cssPath;
2720
+ return err;
2721
+ }
2385
2722
  /**
2386
2723
  * Ensure the worker is running and pointed at `cssPath`. Returns the
2387
2724
  * ready state. Throws `SortServiceError` on any failure (init timeout,
@@ -2389,14 +2726,12 @@ var DesignSystemWorker = class {
2389
2726
  * cssPath rethrow without retrying.
2390
2727
  */
2391
2728
  ensure(cssPath) {
2392
- if (this.lastError && this.ready?.cssPath === cssPath) throw this.lastError;
2729
+ if (this.lastError && this.lastErrorCssPath === cssPath) throw this.lastError;
2393
2730
  if (this.ready && this.ready.cssPath === cssPath) return this.ready;
2394
2731
  if (this.ready) this.cleanup();
2395
2732
  this.lastError = null;
2396
- if (TAILWIND_NODE_PATH === null) {
2397
- 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.");
2398
- throw this.lastError;
2399
- }
2733
+ this.lastErrorCssPath = null;
2734
+ 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."));
2400
2735
  const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
2401
2736
  const controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
2402
2737
  const lengthView = new DataView(sharedBuffer, HEADER_INTS * 4, 4);
@@ -2412,22 +2747,22 @@ var DesignSystemWorker = class {
2412
2747
  }
2413
2748
  });
2414
2749
  } catch (cause) {
2415
- 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 });
2416
- throw this.lastError;
2750
+ 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 }));
2417
2751
  }
2418
2752
  worker.unref();
2419
2753
  worker.on("error", (err) => {
2420
2754
  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 });
2755
+ this.lastErrorCssPath = cssPath;
2421
2756
  });
2422
2757
  if (Atomics.wait(controlArray, 2, 0, INIT_TIMEOUT) === "timed-out") {
2423
- 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.");
2424
2758
  this.terminateWorker(worker);
2425
- throw this.lastError;
2759
+ 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."));
2426
2760
  }
2427
2761
  if (controlArray[2] === -1) {
2428
- 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.");
2762
+ const len = lengthView.getUint32(0);
2763
+ const detail = len > 0 ? Buffer.from(dataArea.slice(0, len)).toString("utf-8") : "";
2429
2764
  this.terminateWorker(worker);
2430
- throw this.lastError;
2765
+ 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."));
2431
2766
  }
2432
2767
  this.ready = {
2433
2768
  worker,
@@ -2451,9 +2786,8 @@ var DesignSystemWorker = class {
2451
2786
  Atomics.store(state.controlArray, 0, 1);
2452
2787
  Atomics.notify(state.controlArray, 0);
2453
2788
  if (Atomics.wait(state.controlArray, 1, 0, REQUEST_TIMEOUT) === "timed-out") {
2454
- this.lastError = new SortServiceError(`${this.opts.serviceName} worker request timed out after ${REQUEST_TIMEOUT}ms.`, "Raise settings.tailwindcss.timeout if your machine is slow.");
2455
2789
  this.cleanup();
2456
- throw this.lastError;
2790
+ 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."));
2457
2791
  }
2458
2792
  const responseLen = state.lengthView.getUint32(0);
2459
2793
  const responseStr = Buffer.from(state.dataArea.slice(0, responseLen)).toString("utf-8");
@@ -2462,20 +2796,19 @@ var DesignSystemWorker = class {
2462
2796
  try {
2463
2797
  parsed = JSON.parse(responseStr);
2464
2798
  } catch (cause) {
2465
- 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 });
2466
2799
  this.cleanup();
2467
- throw this.lastError;
2800
+ 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 }));
2468
2801
  }
2469
2802
  if (parsed === null) {
2470
- 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.");
2471
2803
  this.cleanup();
2472
- throw this.lastError;
2804
+ 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."));
2473
2805
  }
2474
2806
  return parsed;
2475
2807
  }
2476
2808
  reset() {
2477
2809
  this.cleanup();
2478
2810
  this.lastError = null;
2811
+ this.lastErrorCssPath = null;
2479
2812
  }
2480
2813
  cleanup() {
2481
2814
  if (this.ready) {
@@ -2507,60 +2840,14 @@ var DesignSystemWorker = class {
2507
2840
  * subsequent lookup is O(1).
2508
2841
  */
2509
2842
  const canonWorker = new DesignSystemWorker({
2510
- workerScript: `
2511
- const { workerData } = require('worker_threads');
2512
-
2513
- async function main() {
2514
- const { sharedBuffer, cssPath } = workerData;
2515
- const control = new Int32Array(sharedBuffer, 0, 4);
2516
- const lengthView = new DataView(sharedBuffer, 4 * 4, 4);
2517
- const dataArea = new Uint8Array(sharedBuffer, 4 * 4 + 4);
2518
-
2519
- let ds;
2520
- try {
2521
- const { __unstable__loadDesignSystem } = require(workerData.tailwindNodePath);
2522
- const { readFileSync } = require('fs');
2523
- const { dirname } = require('path');
2524
- const css = readFileSync(cssPath, 'utf-8');
2525
- ds = await __unstable__loadDesignSystem(css, { base: dirname(cssPath) });
2526
- } catch {
2527
- Atomics.store(control, 2, -1);
2528
- Atomics.notify(control, 2);
2529
- return;
2530
- }
2531
-
2532
- Atomics.store(control, 2, 1);
2533
- Atomics.notify(control, 2);
2534
-
2535
- while (true) {
2536
- Atomics.wait(control, 0, 0);
2537
- const len = lengthView.getUint32(0);
2538
- const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
2539
- Atomics.store(control, 0, 0);
2540
-
2541
- let response;
2542
- try {
2543
- const { classes, rem } = JSON.parse(requestStr);
2544
- const options = rem ? { rem } : undefined;
2545
- // canonicalizeCandidates deduplicates its input, so we must call it
2546
- // one class at a time to preserve order/length. See sync-loader.ts.
2547
- const result = classes.map((cls) => {
2548
- const r = ds.canonicalizeCandidates([cls], options);
2549
- return r[0] ?? cls;
2550
- });
2551
- response = Buffer.from(JSON.stringify(result), 'utf-8');
2552
- } catch {
2553
- response = Buffer.from('null', 'utf-8');
2554
- }
2555
-
2556
- dataArea.set(response, 0);
2557
- lengthView.setUint32(0, response.length);
2558
- Atomics.store(control, 1, 1);
2559
- Atomics.notify(control, 1);
2560
- }
2561
- }
2562
- main();
2563
- `,
2843
+ workerScript: makeWorkerScript(`(ds, request) => {
2844
+ const { classes, rem } = request;
2845
+ const options = rem ? { rem } : undefined;
2846
+ return classes.map((cls) => {
2847
+ const r = ds.canonicalizeCandidates([cls], options);
2848
+ return r[0] ?? cls;
2849
+ });
2850
+ }`),
2564
2851
  serviceName: "canonicalize"
2565
2852
  });
2566
2853
  /**
@@ -2605,7 +2892,7 @@ function canonicalizeClassesSync(cssPath, classes, rem) {
2605
2892
  for (let k = 0; k < uniqueMissing.length; k++) freshByClass.set(uniqueMissing[k], fresh[k]);
2606
2893
  for (let j = 0; j < missing.length; j++) {
2607
2894
  const cls = missing[j];
2608
- const value = freshByClass.get(cls) ?? cls;
2895
+ const value = roundRemValue(freshByClass.get(cls) ?? cls);
2609
2896
  canonCache.set(cachePrefix + cls, value);
2610
2897
  out[missingIdx[j]] = value;
2611
2898
  }
@@ -2697,62 +2984,17 @@ const enforceCanonical = (0, _oxlint_plugins.defineRule)({
2697
2984
  * Atomics.wait, fail-loud, sticky lastError) lives in `./ds-worker.ts`.
2698
2985
  */
2699
2986
  const sortWorker = new DesignSystemWorker({
2700
- workerScript: `
2701
- const { workerData } = require('worker_threads');
2702
-
2703
- async function main() {
2704
- const { sharedBuffer, cssPath } = workerData;
2705
- const control = new Int32Array(sharedBuffer, 0, 4);
2706
- const lengthView = new DataView(sharedBuffer, 4 * 4, 4);
2707
- const dataArea = new Uint8Array(sharedBuffer, 4 * 4 + 4);
2708
-
2709
- let ds;
2710
- try {
2711
- const { __unstable__loadDesignSystem } = require(workerData.tailwindNodePath);
2712
- const { readFileSync } = require('fs');
2713
- const { dirname } = require('path');
2714
- const css = readFileSync(cssPath, 'utf-8');
2715
- ds = await __unstable__loadDesignSystem(css, { base: dirname(cssPath) });
2716
- } catch {
2717
- Atomics.store(control, 2, -1);
2718
- Atomics.notify(control, 2);
2719
- return;
2720
- }
2721
-
2722
- Atomics.store(control, 2, 1);
2723
- Atomics.notify(control, 2);
2724
-
2725
- while (true) {
2726
- Atomics.wait(control, 0, 0);
2727
- const len = lengthView.getUint32(0);
2728
- const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
2729
- Atomics.store(control, 0, 0);
2730
-
2731
- let response;
2732
- try {
2733
- const classes = JSON.parse(requestStr);
2734
- const ordered = ds.getClassOrder(classes);
2735
- const sorted = [...ordered]
2736
- .sort((a, b) => {
2737
- if (a[1] === null && b[1] === null) return 0;
2738
- if (a[1] === null) return -1;
2739
- if (b[1] === null) return 1;
2740
- return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0;
2741
- })
2742
- .map(([name]) => name);
2743
- response = Buffer.from(JSON.stringify(sorted), 'utf-8');
2744
- } catch {
2745
- response = Buffer.from('null', 'utf-8');
2746
- }
2747
-
2748
- dataArea.set(response, 0);
2749
- lengthView.setUint32(0, response.length);
2750
- Atomics.store(control, 1, 1);
2751
- Atomics.notify(control, 1);
2752
- }
2753
- }
2754
- main();
2755
- `,
2987
+ workerScript: makeWorkerScript(`(ds, classes) => {
2988
+ const ordered = ds.getClassOrder(classes);
2989
+ return [...ordered]
2990
+ .sort((a, b) => {
2991
+ if (a[1] === null && b[1] === null) return 0;
2992
+ if (a[1] === null) return -1;
2993
+ if (b[1] === null) return 1;
2994
+ return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0;
2995
+ })
2996
+ .map(([name]) => name);
2997
+ }`),
2756
2998
  serviceName: "sort"
2757
2999
  });
2758
3000
  /**
@@ -2804,13 +3046,9 @@ const enforceSortOrder = (0, _oxlint_plugins.defineRule)({
2804
3046
  }
2805
3047
  function sortStrict(classes) {
2806
3048
  const groups = /* @__PURE__ */ new Map();
2807
- const groupOrder = [];
2808
3049
  for (const cls of classes) {
2809
3050
  const { variant } = splitUtilityAndVariant(cls);
2810
- if (!groups.has(variant)) {
2811
- groups.set(variant, []);
2812
- groupOrder.push(variant);
2813
- }
3051
+ if (!groups.has(variant)) groups.set(variant, []);
2814
3052
  groups.get(variant).push(cls);
2815
3053
  }
2816
3054
  for (const [, groupClasses] of groups) {
@@ -2826,7 +3064,10 @@ const enforceSortOrder = (0, _oxlint_plugins.defineRule)({
2826
3064
  groupClasses.length = 0;
2827
3065
  for (const [name] of ordered) groupClasses.push(name);
2828
3066
  }
2829
- const sortedGroupKeys = [...groups.keys()].sort((a, b) => {
3067
+ const stripKey = (k) => cache.prefix && k.startsWith(cache.prefix + ":") ? k.slice(cache.prefix.length + 1) : k;
3068
+ const sortedGroupKeys = [...groups.keys()].sort((ka, kb) => {
3069
+ const a = stripKey(ka);
3070
+ const b = stripKey(kb);
2830
3071
  if (a === "" && b !== "") return -1;
2831
3072
  if (a !== "" && b === "") return 1;
2832
3073
  if (a === "" && b === "") return 0;
@@ -2989,26 +3230,6 @@ const enforceShorthand = (0, _oxlint_plugins.defineRule)({
2989
3230
  }
2990
3231
  });
2991
3232
  //#endregion
2992
- //#region src/utils/allowlist.ts
2993
- /**
2994
- * Shared regex-allowlist helpers used by rules that accept an `allowlist`
2995
- * option of regex source strings (currently enforce-logical / enforce-physical).
2996
- *
2997
- * Invalid regex sources are skipped rather than thrown so a typo in one
2998
- * pattern doesn't blow up the entire lint run.
2999
- */
3000
- function compileRegexList(patterns) {
3001
- if (!patterns || patterns.length === 0) return [];
3002
- const compiled = [];
3003
- for (const p of patterns) try {
3004
- compiled.push(new RegExp(p));
3005
- } catch {}
3006
- return compiled;
3007
- }
3008
- function matchesAny(value, list) {
3009
- return list.some((re) => re.test(value));
3010
- }
3011
- //#endregion
3012
3233
  //#region src/rules/enforce-logical.ts
3013
3234
  const LOGICAL_PHYSICAL_SCHEMA = {
3014
3235
  type: "object",
@@ -3149,9 +3370,14 @@ function createDirectionalMapper(context, opts) {
3149
3370
  if (matchesAny(cls, allowlist)) return null;
3150
3371
  const { utility, variant } = splitUtilityAndVariant(cls);
3151
3372
  const { bare: bareUtility, position } = splitImportant(utility);
3373
+ const negative = bareUtility.startsWith("-");
3374
+ const core = negative ? bareUtility.slice(1) : bareUtility;
3152
3375
  for (const { from, to, axis } of opts.mappings) {
3153
3376
  if (direction !== "both" && direction !== axis) continue;
3154
- if (bareUtility === from || bareUtility.startsWith(`${from}-`)) return `${variant}${reattachImportant(to + bareUtility.slice(from.length), position)}`;
3377
+ if (core === from || core.startsWith(`${from}-`)) {
3378
+ const suffix = core.slice(from.length);
3379
+ return `${variant}${reattachImportant(`${negative ? "-" : ""}${to}${suffix}`, position)}`;
3380
+ }
3155
3381
  }
3156
3382
  return null;
3157
3383
  }
@@ -3294,10 +3520,16 @@ const noRestrictedClasses = (0, _oxlint_plugins.defineRule)({
3294
3520
  createOnce(context) {
3295
3521
  const getConfig = createLazyOptions(context, (o) => ({
3296
3522
  restrictedClasses: new Set(o?.classes ?? []),
3297
- patterns: (o?.patterns ?? []).map((p) => ({
3298
- regex: new RegExp(p.pattern),
3299
- message: p.message
3300
- }))
3523
+ patterns: (o?.patterns ?? []).flatMap((p) => {
3524
+ try {
3525
+ return [{
3526
+ regex: new RegExp(p.pattern),
3527
+ message: p.message
3528
+ }];
3529
+ } catch {
3530
+ return [];
3531
+ }
3532
+ })
3301
3533
  }));
3302
3534
  function check(locations) {
3303
3535
  const { restrictedClasses, patterns } = getConfig();
@@ -3426,6 +3658,7 @@ const enforceConsistentImportantPosition = (0, _oxlint_plugins.defineRule)({
3426
3658
  });
3427
3659
  //#endregion
3428
3660
  //#region src/rules/enforce-negative-arbitrary-values.ts
3661
+ const SIMPLE_DIMENSION = /^\d*\.?\d+[a-z%]*$/;
3429
3662
  function fixClass(cls) {
3430
3663
  const { utility, variant } = splitUtilityAndVariant(cls);
3431
3664
  const hasImportantPrefix = utility.startsWith("!");
@@ -3438,6 +3671,7 @@ function fixClass(cls) {
3438
3671
  if (bracketClose === -1 || bracketClose < bracketOpen) return null;
3439
3672
  const innerValue = bare.slice(bracketOpen + 1, bracketClose);
3440
3673
  if (innerValue.startsWith("-")) return null;
3674
+ if (!SIMPLE_DIMENSION.test(innerValue)) return null;
3441
3675
  const baseUtility = bare.slice(1, bracketOpen);
3442
3676
  return `${variant}${hasImportantPrefix ? "!" : ""}${baseUtility}[-${innerValue}]${hasImportantSuffix ? "!" : ""}`;
3443
3677
  }
@@ -3572,13 +3806,48 @@ const KNOWN_PREFIXES = [
3572
3806
  "via",
3573
3807
  "to"
3574
3808
  ];
3809
+ const PROPERTY_GROUP_BY_UTILITY = {};
3810
+ for (const u of [
3811
+ "block",
3812
+ "inline-block",
3813
+ "inline",
3814
+ "flex",
3815
+ "inline-flex",
3816
+ "grid",
3817
+ "inline-grid",
3818
+ "flow-root",
3819
+ "contents",
3820
+ "table",
3821
+ "inline-table",
3822
+ "table-caption",
3823
+ "table-cell",
3824
+ "table-row",
3825
+ "table-row-group",
3826
+ "table-header-group",
3827
+ "table-footer-group",
3828
+ "table-column",
3829
+ "table-column-group",
3830
+ "list-item",
3831
+ "hidden"
3832
+ ]) PROPERTY_GROUP_BY_UTILITY[u] = "display";
3833
+ for (const u of [
3834
+ "static",
3835
+ "fixed",
3836
+ "absolute",
3837
+ "relative",
3838
+ "sticky"
3839
+ ]) PROPERTY_GROUP_BY_UTILITY[u] = "position";
3575
3840
  /**
3576
- * Extracts the utility prefix (e.g. "bg" from "bg-gray-900", "text" from "text-white").
3577
- * Used to group utilities by their property type.
3841
+ * Maps a utility to a key identifying the CSS property it sets, so a base and a
3842
+ * variant class for the same property group together. Exact-match equivalence
3843
+ * groups (display, position) win; otherwise fall back to the prefix heuristic
3844
+ * (e.g. "bg" from "bg-gray-900", "text" from "text-white").
3578
3845
  */
3579
3846
  function getUtilityPrefix(utility) {
3580
3847
  let u = splitImportant(utility).bare;
3581
3848
  if (u.startsWith("-")) u = u.slice(1);
3849
+ const group = PROPERTY_GROUP_BY_UTILITY[u];
3850
+ if (group) return group;
3582
3851
  for (const prefix of KNOWN_PREFIXES) if (u === prefix || u.startsWith(`${prefix}-`)) return prefix;
3583
3852
  const dashIdx = u.indexOf("-");
3584
3853
  return dashIdx >= 0 ? u.slice(0, dashIdx) : u;
@@ -3686,13 +3955,10 @@ const noHardcodedColors = (0, _oxlint_plugins.defineRule)({
3686
3955
  docs: { description: "Disallow hardcoded color values in Tailwind CSS classes" },
3687
3956
  schema: [{
3688
3957
  type: "object",
3689
- properties: {
3690
- entryPoint: { type: "string" },
3691
- allow: {
3692
- type: "array",
3693
- items: { type: "string" }
3694
- }
3695
- },
3958
+ properties: { allow: {
3959
+ type: "array",
3960
+ items: { type: "string" }
3961
+ } },
3696
3962
  additionalProperties: false
3697
3963
  }],
3698
3964
  defaultOptions: [{ allow: [] }],
@@ -3724,24 +3990,6 @@ const noHardcodedColors = (0, _oxlint_plugins.defineRule)({
3724
3990
  });
3725
3991
  //#endregion
3726
3992
  //#region src/rules/no-contradicting-variants.ts
3727
- const TARGET_CHANGING_VARIANTS = new Set([
3728
- "after",
3729
- "before",
3730
- "file",
3731
- "placeholder",
3732
- "marker",
3733
- "backdrop",
3734
- "selection",
3735
- "first-line",
3736
- "first-letter"
3737
- ]);
3738
- function changesTarget(variant) {
3739
- if (TARGET_CHANGING_VARIANTS.has(variant)) return true;
3740
- if (variant === "*" || variant === "**") return true;
3741
- if (variant.startsWith("[") && variant.endsWith("]")) return true;
3742
- if (variant.startsWith("*:")) return true;
3743
- return false;
3744
- }
3745
3993
  const noContradictingVariants = (0, _oxlint_plugins.defineRule)({
3746
3994
  meta: {
3747
3995
  type: "suggestion",
@@ -3776,18 +4024,6 @@ const noContradictingVariants = (0, _oxlint_plugins.defineRule)({
3776
4024
  });
3777
4025
  //#endregion
3778
4026
  //#region src/rules/consistent-variant-order.ts
3779
- const PSEUDO_ELEMENTS = new Set([
3780
- "before",
3781
- "after",
3782
- "file",
3783
- "placeholder",
3784
- "selection",
3785
- "marker",
3786
- "backdrop",
3787
- "first-line",
3788
- "first-letter",
3789
- "details-content"
3790
- ]);
3791
4027
  const DEFAULT_VARIANT_ORDER = [
3792
4028
  "*",
3793
4029
  "**",
@@ -3886,17 +4122,12 @@ const consistentVariantOrder = (0, _oxlint_plugins.defineRule)({
3886
4122
  },
3887
4123
  createOnce(context) {
3888
4124
  const getDS = createLazyLoader(context);
3889
- const getPriority = createLazyOptions(context, (o) => {
3890
- let dsCache = null;
3891
- try {
3892
- dsCache = getDS().cache;
3893
- } catch (err) {
3894
- if (!isFatalError(err)) throw err;
3895
- }
3896
- if (o?.order) {
4125
+ const getOptions = createLazyOptions(context, (o) => ({ order: o?.order }));
4126
+ function buildPriority(order, dsCache) {
4127
+ if (order) {
3897
4128
  const map = /* @__PURE__ */ new Map();
3898
- for (let i = 0; i < o.order.length; i++) map.set(o.order[i], i);
3899
- const fallback = o.order.length;
4129
+ for (let i = 0; i < order.length; i++) map.set(order[i], i);
4130
+ const fallback = order.length;
3900
4131
  return (v) => map.get(v) ?? fallback;
3901
4132
  }
3902
4133
  if (dsCache && dsCache.hasVariantOrder()) {
@@ -3907,20 +4138,66 @@ const consistentVariantOrder = (0, _oxlint_plugins.defineRule)({
3907
4138
  for (let i = 0; i < DEFAULT_VARIANT_ORDER.length; i++) map.set(DEFAULT_VARIANT_ORDER[i], i);
3908
4139
  const fallback = DEFAULT_VARIANT_ORDER.length;
3909
4140
  return (v) => map.get(v) ?? fallback;
3910
- });
4141
+ }
4142
+ const priorityByEntry = /* @__PURE__ */ new Map();
4143
+ const prefixByEntry = /* @__PURE__ */ new Map();
4144
+ function resolveForFile() {
4145
+ let dsCache = null;
4146
+ let entryKey = "";
4147
+ try {
4148
+ const ds = getDS();
4149
+ dsCache = ds.cache;
4150
+ entryKey = ds.entryPoint;
4151
+ } catch (err) {
4152
+ if (!isFatalError(err)) throw err;
4153
+ }
4154
+ let priorityOf = priorityByEntry.get(entryKey);
4155
+ if (!priorityOf) {
4156
+ priorityOf = buildPriority(getOptions().order, dsCache);
4157
+ priorityByEntry.set(entryKey, priorityOf);
4158
+ }
4159
+ let prefix = prefixByEntry.get(entryKey);
4160
+ if (prefix === void 0) {
4161
+ prefix = dsCache?.prefix ?? "";
4162
+ prefixByEntry.set(entryKey, prefix);
4163
+ }
4164
+ return {
4165
+ priorityOf,
4166
+ prefix
4167
+ };
4168
+ }
3911
4169
  function reorderClass(cls) {
3912
- const variants = extractVariants(cls);
4170
+ const { priorityOf, prefix } = resolveForFile();
4171
+ let pfx = "";
4172
+ let body = cls;
4173
+ if (prefix && cls.startsWith(prefix + ":")) {
4174
+ pfx = prefix + ":";
4175
+ body = cls.slice(prefix.length + 1);
4176
+ }
4177
+ const variants = extractVariants(body);
3913
4178
  if (variants.length < 2) return null;
3914
- const priorityOf = getPriority();
3915
- const sorted = [...variants].sort((a, b) => priorityOf(a) - priorityOf(b));
3916
- const nonPseudo = [];
3917
4179
  const pseudo = [];
3918
- for (const v of sorted) if (PSEUDO_ELEMENTS.has(v)) pseudo.push(v);
3919
- else nonPseudo.push(v);
3920
- const final = nonPseudo.length > 0 && pseudo.length > 0 ? [...nonPseudo, ...pseudo] : sorted;
4180
+ const rest = [];
4181
+ for (const v of variants) if (isPseudoElementVariant(v)) pseudo.push(v);
4182
+ else rest.push(v);
4183
+ const reorderedRest = [];
4184
+ let segment = [];
4185
+ const flushSegment = () => {
4186
+ if (segment.length === 0) return;
4187
+ segment.sort((a, b) => priorityOf(a) - priorityOf(b));
4188
+ reorderedRest.push(...segment);
4189
+ segment = [];
4190
+ };
4191
+ for (const v of rest) if (isSelectorBarrier(v)) {
4192
+ flushSegment();
4193
+ reorderedRest.push(v);
4194
+ } else segment.push(v);
4195
+ flushSegment();
4196
+ pseudo.sort((a, b) => priorityOf(a) - priorityOf(b));
4197
+ const final = [...reorderedRest, ...pseudo];
3921
4198
  if (variants.every((v, i) => v === final[i])) return null;
3922
- const utility = extractUtility(cls);
3923
- return final.join(":") + ":" + utility;
4199
+ const utility = extractUtility(body);
4200
+ return pfx + final.join(":") + ":" + utility;
3924
4201
  }
3925
4202
  function check(locations) {
3926
4203
  for (const loc of locations) {