oxlint-tailwindcss 1.7.1 → 1.9.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
@@ -1,13 +1,13 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { Worker, threadId } from "node:worker_threads";
3
3
  import { createHash } from "node:crypto";
4
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
6
6
  import { tmpdir, userInfo } from "node:os";
7
7
  //#region \0rolldown/runtime.js
8
8
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
9
9
  //#endregion
10
- //#region ../../node_modules/.pnpm/@oxlint+plugins@1.77.0/node_modules/@oxlint/plugins/index.js
10
+ //#region ../../node_modules/.pnpm/@oxlint+plugins@1.78.0/node_modules/@oxlint/plugins/index.js
11
11
  /**
12
12
  * Define a plugin.
13
13
  *
@@ -518,24 +518,58 @@ function splitClassesWithSeparators(classString) {
518
518
  };
519
519
  }
520
520
  /**
521
+ * The separator to place before an output class whose source class sits at
522
+ * original index `si`, given the previous output class came from `sPrev`.
523
+ *
524
+ * - **forward move** (`si > sPrev`): the classes between them were dropped, so
525
+ * the effective separator is the LAST newline-bearing separator in that gap
526
+ * (it carries the correct indent), else the separator immediately preceding
527
+ * `si`. This transfers a line break forward when the class that opened a line
528
+ * is removed, so the next survivor keeps its own line.
529
+ * - **non-forward move** (append / reorder — e.g. `enforce-shorthand` pushes the
530
+ * merged replacement to the end): reuse `si`'s own preceding separator if it
531
+ * carries a newline, else a single space — never the (possibly empty) leader,
532
+ * so output classes never glue together.
533
+ */
534
+ function pickSeparator(separators, sPrev, si) {
535
+ if (si > sPrev) {
536
+ let chosen = separators[si] ?? " ";
537
+ for (let k = sPrev + 1; k <= si; k++) if (separators[k]?.includes("\n")) chosen = separators[k];
538
+ return chosen;
539
+ }
540
+ const own = separators[si];
541
+ return own && own.includes("\n") ? own : " ";
542
+ }
543
+ /**
521
544
  * Reconstruct a class string from a `ClassSplit` and a (possibly transformed)
522
545
  * array of classes.
523
546
  *
524
- * - If `newClasses.length === split.classes.length` (1-to-1 transformation:
525
- * canonicalize, sort, variant-order, etc.) every separator is preserved
526
- * verbatim. This keeps multiline indentation intact.
527
- * - If lengths differ (shorthand collapses pairs, no-duplicate removes dupes)
528
- * the helper degrades gracefully: leading and trailing whitespace are
529
- * preserved; classes are joined by the first internal separator that
530
- * contains a newline, or a single space if none does.
531
- */
532
- function rebuildClassString(split, newClasses) {
547
+ * - If `newClasses.length === split.classes.length` and no `sourceIndices` are
548
+ * given (1-to-1 transformation: canonicalize, sort, variant-order, etc.)
549
+ * every separator is preserved verbatim. This keeps multiline indentation
550
+ * intact.
551
+ * - If `sourceIndices` is given (count-changing transforms that know where each
552
+ * output class came from: no-duplicate removes dupes, shorthand collapses
553
+ * pairs) the layout is preserved structurally — leader and trailing stay
554
+ * verbatim (edge-safe) and each interior separator is recovered from the
555
+ * source via `pickSeparator`, so a multiline block keeps its per-line grouping
556
+ * instead of reflowing to one class per line.
557
+ * - Otherwise (count differs, no mapping) it degrades gracefully: leading and
558
+ * trailing whitespace are preserved; classes are joined by the first internal
559
+ * separator that contains a newline, or a single space if none does.
560
+ */
561
+ function rebuildClassString(split, newClasses, sourceIndices) {
533
562
  const { classes, separators } = split;
534
- if (newClasses.length === classes.length) {
563
+ if (!sourceIndices && newClasses.length === classes.length) {
535
564
  let result = separators[0];
536
565
  for (let i = 0; i < newClasses.length; i++) result += newClasses[i] + separators[i + 1];
537
566
  return result;
538
567
  }
568
+ if (sourceIndices && sourceIndices.length === newClasses.length && newClasses.length > 0) {
569
+ let result = separators[0] + newClasses[0];
570
+ for (let i = 1; i < newClasses.length; i++) result += pickSeparator(separators, sourceIndices[i - 1], sourceIndices[i]) + newClasses[i];
571
+ return result + separators[separators.length - 1];
572
+ }
539
573
  const join = separators.slice(1, -1).find((s) => s.includes("\n")) ?? " ";
540
574
  return separators[0] + newClasses.join(join) + separators[separators.length - 1];
541
575
  }
@@ -559,7 +593,12 @@ const noDuplicateClasses = defineRule({
559
593
  for (const cls of classes) if (seen.has(cls)) duplicates.push(cls);
560
594
  else seen.add(cls);
561
595
  if (duplicates.length > 0) {
562
- const fixed = rebuildClassString(split, [...new Set(classes)]);
596
+ const firstIdx = /* @__PURE__ */ new Map();
597
+ classes.forEach((c, i) => {
598
+ if (!firstIdx.has(c)) firstIdx.set(c, i);
599
+ });
600
+ const unique = [...firstIdx.keys()];
601
+ const fixed = rebuildClassString(split, unique, unique.map((c) => firstIdx.get(c)));
563
602
  for (const dup of duplicates) context.report({
564
603
  node: loc.node,
565
604
  messageId: "duplicate",
@@ -594,7 +633,9 @@ const noUnnecessaryWhitespace = defineRule({
594
633
  return m[1] + m[2].replace(/[ \t]+/g, " ");
595
634
  }).join("\n");
596
635
  if (normalized.startsWith(" ") && !loc.preserveLeadingSpace) normalized = normalized.slice(1);
597
- if (normalized.endsWith(" ") && !loc.preserveTrailingSpace) normalized = normalized.slice(0, -1);
636
+ const lastNl = normalized.lastIndexOf("\n");
637
+ const trailingIsClosingIndent = lastNl !== -1 && /^[ \t]*$/.test(normalized.slice(lastNl + 1));
638
+ if (normalized.endsWith(" ") && !loc.preserveTrailingSpace && !trailingIsClosingIndent) normalized = normalized.slice(0, -1);
598
639
  if (normalized !== loc.value) context.report({
599
640
  node: loc.node,
600
641
  messageId: "unnecessaryWhitespace",
@@ -1540,6 +1581,14 @@ var DeprecatedEntryPointShapeError = class extends OxlintTailwindError {};
1540
1581
  var DesignSystemLoadError = class extends OxlintTailwindError {};
1541
1582
  /** The sort or canonicalize worker thread failed to initialize or timed out. */
1542
1583
  var SortServiceError = class extends OxlintTailwindError {};
1584
+ /**
1585
+ * The resolved Tailwind engine version is outside the range this plugin
1586
+ * supports: older than v4, a future major (v5+) the plugin was not built for,
1587
+ * or a major-version drift from the version the consumer's build compiles
1588
+ * with. Fail-loud rather than lint against semantics that don't match the
1589
+ * build. See `design-system/engine-guard.ts` for the decision table.
1590
+ */
1591
+ var UnsupportedEngineError = class extends OxlintTailwindError {};
1543
1592
  /** Type-guard: did this error originate from the plugin's fail-loud infrastructure? */
1544
1593
  function isFatalError(err) {
1545
1594
  return err instanceof OxlintTailwindError;
@@ -1610,28 +1659,54 @@ function softGetDS(getDS) {
1610
1659
  //#endregion
1611
1660
  //#region src/design-system/tailwind-node.ts
1612
1661
  /**
1613
- * Single source of truth for the resolved `@tailwindcss/node` entry path
1614
- * and its installed version. Three call sites (sync-loader, sort-service,
1615
- * canonicalize-service) used to each call `require.resolve` independently
1616
- * — this module resolves once at load and exposes the results.
1662
+ * Resolves the Tailwind engine (`@tailwindcss/node`) the plugin runs against.
1663
+ *
1664
+ * Two layers:
1665
+ *
1666
+ * 1. **Bundled fallback** — `TAILWIND_NODE_PATH` / `TAILWIND_NODE_VERSION`,
1667
+ * resolved ONCE at module load from the plugin's own location. This is the
1668
+ * copy shipped as a dependency; used only when the consumer's engine can't
1669
+ * be found.
1670
+ * 2. **Per-entry-point resolution** — `resolveTailwindNodeFor(cssPath)`
1671
+ * resolves the engine from the CONSUMER's project (the `node_modules` around
1672
+ * the resolved CSS entry point), so the linter analyzes with the same
1673
+ * Tailwind the build compiles with (issue #114). Memoized per CSS directory;
1674
+ * a pure function of the on-disk module topology, so every layer
1675
+ * (precompute, live worker services, disk-cache key) that is handed the same
1676
+ * `cssPath` independently agrees on the same engine — no cross-layer
1677
+ * threading required.
1617
1678
  *
1618
- * The version is read from `dist/../package.json` (the published layout)
1619
- * with a walk-up fallback for unconventional installs.
1679
+ * Versions are read from the resolved entry's `package.json` (walk-up
1680
+ * fallback for unconventional layouts).
1620
1681
  */
1621
- function resolveTailwindNodePath() {
1682
+ function tryResolveFrom(specifier, fromDir) {
1622
1683
  try {
1623
- return __require.resolve("@tailwindcss/node");
1684
+ return __require.resolve(specifier, { paths: [fromDir] });
1624
1685
  } catch {
1625
1686
  return null;
1626
1687
  }
1627
1688
  }
1628
- function readVersionFromEntry(entryPath) {
1689
+ function realpathOr(p) {
1690
+ try {
1691
+ return realpathSync(p);
1692
+ } catch {
1693
+ return p;
1694
+ }
1695
+ }
1696
+ /**
1697
+ * Read the `version` from the `package.json` for `name`, starting at
1698
+ * `dirname(entryPath)` and walking up a few levels (packages ship their entry
1699
+ * as `dist/index.{cjs,mjs}` next to the `package.json`, but layouts vary).
1700
+ * The `pkg.name === name` guard backstops a wrong `package.json` found mid-walk
1701
+ * (e.g. through a pnpm symlink). Returns `'unknown'` if nothing matches.
1702
+ */
1703
+ function readVersionFromEntry(entryPath, name) {
1629
1704
  let dir = dirname(entryPath);
1630
1705
  for (let i = 0; i < 5; i++) {
1631
1706
  const pkgJson = join(dir, "package.json");
1632
1707
  if (existsSync(pkgJson)) try {
1633
1708
  const pkg = JSON.parse(readFileSync(pkgJson, "utf-8"));
1634
- if (pkg.name === "@tailwindcss/node" && pkg.version) return pkg.version;
1709
+ if (pkg.name === name && pkg.version) return pkg.version;
1635
1710
  } catch {}
1636
1711
  const parent = dirname(dir);
1637
1712
  if (parent === dir) break;
@@ -1639,21 +1714,93 @@ function readVersionFromEntry(entryPath) {
1639
1714
  }
1640
1715
  return "unknown";
1641
1716
  }
1642
- const entryPath = resolveTailwindNodePath();
1717
+ const bundledEntry = resolveBundledEntry();
1718
+ function resolveBundledEntry() {
1719
+ try {
1720
+ return __require.resolve("@tailwindcss/node");
1721
+ } catch {
1722
+ return null;
1723
+ }
1724
+ }
1725
+ /**
1726
+ * Absolute entry of the plugin's own bundled `@tailwindcss/node`, or `null`
1727
+ * if not installed. Used as the last-resort fallback by
1728
+ * `resolveTailwindNodeFor` and passed to workers, which resolve the bare
1729
+ * specifier from a tmp-dir `eval` context (where it would otherwise fail).
1730
+ */
1731
+ const TAILWIND_NODE_PATH = bundledEntry;
1643
1732
  /**
1644
- * Absolute path to `@tailwindcss/node`'s main entry, or `null` if not
1645
- * installed. Workers receive this path via workerData; the parent does
1646
- * the resolution because module resolution from a child process's `eval`
1647
- * context (with cwd inside a tmp dir or under pnpm strict workspaces) can
1648
- * fail to find the bare specifier.
1733
+ * Installed version of the plugin's bundled `@tailwindcss/node`, or
1734
+ * `'unknown'`. This is the version the plugin was built and tested against;
1735
+ * `engine-guard` uses it as the "tested ceiling".
1649
1736
  */
1650
- const TAILWIND_NODE_PATH = entryPath;
1737
+ const TAILWIND_NODE_VERSION = bundledEntry !== null ? readVersionFromEntry(bundledEntry, "@tailwindcss/node") : "unknown";
1738
+ const BUILD_TOOL_SPECIFIERS = [
1739
+ "@tailwindcss/postcss",
1740
+ "@tailwindcss/vite",
1741
+ "@tailwindcss/cli"
1742
+ ];
1651
1743
  /**
1652
- * Installed `@tailwindcss/node` version, or `'unknown'`. Used as part of
1653
- * the disk-cache key in sync-loader so cached precompute output is
1654
- * invalidated when the consumer upgrades.
1744
+ * The real directories of the consumer's Tailwind build tools, resolved from
1745
+ * the CSS dir. Under pnpm's strict layout `@tailwindcss/node` is only a
1746
+ * transitive dep (not symlinked into the package's `node_modules`), so it is
1747
+ * unreachable from the CSS dir directly — but it IS reachable from the build
1748
+ * tool's own real directory. `realpathSync` follows the pnpm symlink to the
1749
+ * virtual store before we resolve `@tailwindcss/node` relative to it.
1655
1750
  */
1656
- const TAILWIND_NODE_VERSION = entryPath !== null ? readVersionFromEntry(entryPath) : "unknown";
1751
+ function buildToolAnchorDirs(cssDir) {
1752
+ const dirs = [];
1753
+ for (const spec of BUILD_TOOL_SPECIFIERS) {
1754
+ const entry = tryResolveFrom(spec, cssDir);
1755
+ if (entry) dirs.push(dirname(realpathOr(entry)));
1756
+ }
1757
+ return dirs;
1758
+ }
1759
+ const resolutionCache = /* @__PURE__ */ new Map();
1760
+ /**
1761
+ * Resolve the Tailwind engine to run for a given resolved CSS entry point,
1762
+ * anchored on the consumer's project. Memoized per CSS directory.
1763
+ *
1764
+ * Cascade:
1765
+ * 1. `buildVersion` (B) — the consumer's `tailwindcss` resolved from the CSS
1766
+ * dir. Always a direct dep, so it resolves under npm (hoisted) and pnpm
1767
+ * (symlinked into the package). `'unknown'` if the project has no Tailwind.
1768
+ * 2. `nodePath` (E) — the first `@tailwindcss/node` resolvable from
1769
+ * `[cssDir, ...buildToolAnchorDirs]`, preferring the copy whose version
1770
+ * equals `buildVersion` so a hoisted plugin copy can't shadow the
1771
+ * consumer's engine (R2). Falls back to the bundled copy.
1772
+ *
1773
+ * Never throws; degrades to `'unknown'` / bundled so the version guard (not
1774
+ * this function) owns the fail-loud decision.
1775
+ */
1776
+ function resolveTailwindNodeFor(cssPath) {
1777
+ const cssDir = dirname(resolve(cssPath));
1778
+ const cached = resolutionCache.get(cssDir);
1779
+ if (cached) return cached;
1780
+ const twEntry = tryResolveFrom("tailwindcss", cssDir);
1781
+ const buildVersion = twEntry ? readVersionFromEntry(twEntry, "tailwindcss") : "unknown";
1782
+ const candidates = [];
1783
+ for (const dir of [cssDir, ...buildToolAnchorDirs(cssDir)]) {
1784
+ const found = tryResolveFrom("@tailwindcss/node", dir);
1785
+ if (!found) continue;
1786
+ const real = realpathOr(found);
1787
+ if (!candidates.includes(real)) candidates.push(real);
1788
+ }
1789
+ let nodePath = null;
1790
+ if (buildVersion !== "unknown") nodePath = candidates.find((c) => readVersionFromEntry(c, "@tailwindcss/node") === buildVersion) ?? null;
1791
+ if (nodePath === null) nodePath = candidates[0] ?? null;
1792
+ if (nodePath === null) nodePath = TAILWIND_NODE_PATH;
1793
+ const usedBundled = nodePath !== null && TAILWIND_NODE_PATH !== null && realpathOr(nodePath) === realpathOr(TAILWIND_NODE_PATH);
1794
+ const nodeVersion = nodePath !== null ? readVersionFromEntry(realpathOr(nodePath), "@tailwindcss/node") : "unknown";
1795
+ const result = {
1796
+ nodePath,
1797
+ nodeVersion,
1798
+ buildVersion,
1799
+ usedBundled
1800
+ };
1801
+ resolutionCache.set(cssDir, result);
1802
+ return result;
1803
+ }
1657
1804
  //#endregion
1658
1805
  //#region src/design-system/sync-loader.ts
1659
1806
  /**
@@ -1681,7 +1828,7 @@ const TAILWIND_NODE_VERSION = entryPath !== null ? readVersionFromEntry(entryPat
1681
1828
  * `tests/benchmarks/precompute-phases.test.ts` used to keep a hand-copied
1682
1829
  * duplicate of the extractor that silently drifted from the real one, and it is
1683
1830
  * interpolated (not concatenated at runtime), so its text still feeds the
1684
- * `CACHE_KEY` md5 and any edit here invalidates the disk cache automatically.
1831
+ * `SCRIPT_HASH` md5 and any edit here invalidates the disk cache automatically.
1685
1832
  *
1686
1833
  * Exports (in the worker scope): `walkDeclarations`, `scanVarReads`,
1687
1834
  * `isPureVarRead`.
@@ -2584,23 +2731,20 @@ function cacheDirName() {
2584
2731
  }
2585
2732
  }
2586
2733
  const CACHE_DIR = join(tmpdir(), cacheDirName());
2734
+ /** md5 of the precompute script (no version) — the version is folded in per entry point. */
2735
+ const SCRIPT_HASH = createHash("md5").update(PRECOMPUTE_SCRIPT).digest("hex").slice(0, 8);
2587
2736
  /**
2588
- * Cache key derived from:
2589
- * - md5(PRECOMPUTE_SCRIPT): auto-invalidates when our precompute logic changes,
2590
- * since the shape and content of the cached JSON is fully determined by what
2591
- * this script prints to stdout.
2592
- * - @tailwindcss/node version: auto-invalidates when the consumer upgrades
2593
- * tailwindcss (e.g. 4.2 → 4.3 adding `zoom-*`, `tab-*`, `scrollbar-*` etc.),
2594
- * so `validClasses`, `cssProps`, `canonical`, and `arbitraryEquivalents`
2595
- * reflect the installed version. @tailwindcss/node and tailwindcss are
2596
- * published together, so their versions match.
2737
+ * The engine identifier folded into the content hash. Normally the resolved
2738
+ * `@tailwindcss/node` version; when that is `'unknown'` (unreadable
2739
+ * `package.json`) two genuinely different engines would both hash as `unknown`,
2740
+ * so tiebreak on the resolved path (machine-local, but the disk cache is
2741
+ * per-uid/per-machine anyway, and under pnpm the path encodes the version).
2597
2742
  */
2598
- function computeCacheKey(scriptContent, tailwindVersion) {
2599
- return `${createHash("md5").update(scriptContent).digest("hex").slice(0, 8)}:${tailwindVersion}`;
2743
+ function engineCacheKey(res) {
2744
+ return res.nodeVersion === "unknown" && res.nodePath !== null ? `unknown@${res.nodePath}` : res.nodeVersion;
2600
2745
  }
2601
- const CACHE_KEY = computeCacheKey(PRECOMPUTE_SCRIPT, TAILWIND_NODE_VERSION);
2602
- function computeContentHash(content) {
2603
- return createHash("md5").update(`${CACHE_KEY}:${content}`).digest("hex");
2746
+ function computeContentHash(content, engineVersion) {
2747
+ return createHash("md5").update(`${SCRIPT_HASH}:${engineVersion}:${content}`).digest("hex");
2604
2748
  }
2605
2749
  const IMPORT_RE = /@import\s+(?:url\(\s*)?['"]([^'"]+)['"]/g;
2606
2750
  /**
@@ -2612,7 +2756,7 @@ const IMPORT_RE = /@import\s+(?:url\(\s*)?['"]([^'"]+)['"]/g;
2612
2756
  *
2613
2757
  * Resolves RELATIVE imports (`./`, `../`) recursively up to a small depth;
2614
2758
  * package imports (`@import "tailwindcss"`, `tw-animate-css`) are already
2615
- * covered by the `@tailwindcss/node` version baked into CACHE_KEY. Best-effort:
2759
+ * covered by the engine version folded into the content hash. Best-effort:
2616
2760
  * an unreadable import contributes nothing (it can't affect the DS either).
2617
2761
  */
2618
2762
  function hashableContent(entryPath, entryContent) {
@@ -2652,7 +2796,9 @@ function getContentCachePath(contentHash) {
2652
2796
  */
2653
2797
  function cacheArtifactPaths(cssPath) {
2654
2798
  const resolved = resolve(cssPath);
2655
- const hash = computeContentHash(hashableContent(resolved, readFileSync(resolved, "utf-8")));
2799
+ const content = readFileSync(resolved, "utf-8");
2800
+ const res = resolveTailwindNodeFor(resolved);
2801
+ const hash = computeContentHash(hashableContent(resolved, content), engineCacheKey(res));
2656
2802
  return {
2657
2803
  json: getContentCachePath(hash),
2658
2804
  lock: join(CACHE_DIR, `${hash}.lock`)
@@ -2862,12 +3008,13 @@ function loadDesignSystemSync(cssPath, timeout) {
2862
3008
  } catch (cause) {
2863
3009
  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 });
2864
3010
  }
2865
- const contentHash = computeContentHash(hashableContent(resolvedPath, content));
3011
+ const engine = resolveTailwindNodeFor(resolvedPath);
3012
+ const contentHash = computeContentHash(hashableContent(resolvedPath, content), engineCacheKey(engine));
2866
3013
  const contentCachePath = getContentCachePath(contentHash);
2867
3014
  const cached = tryReadCache(contentCachePath);
2868
3015
  if (cached) return cached;
2869
- 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.");
2870
- return computeWithLock(resolvedPath, TAILWIND_NODE_PATH, contentHash, contentCachePath, timeout ?? 6e4);
3016
+ if (engine.nodePath === null) throw new DesignSystemLoadError(`Could not resolve '@tailwindcss/node' while loading "${resolvedPath}".`, "Install '@tailwindcss/node' (or upgrade oxlint-tailwindcss) and re-run.");
3017
+ return computeWithLock(resolvedPath, engine.nodePath, contentHash, contentCachePath, timeout ?? 6e4);
2871
3018
  }
2872
3019
  //#endregion
2873
3020
  //#region src/design-system/debug.ts
@@ -2898,6 +3045,207 @@ function debugLog(message) {
2898
3045
  if (_enabled || process.env.DEBUG === "oxlint-tailwindcss") console.error(`${PREFIX} ${message}`);
2899
3046
  }
2900
3047
  //#endregion
3048
+ //#region src/design-system/engine-guard.ts
3049
+ /**
3050
+ * Version safeguards for the consumer-resolved Tailwind engine.
3051
+ *
3052
+ * Once the plugin loads the CONSUMER's Tailwind (`resolveTailwindNodeFor`),
3053
+ * two version facts matter per entry point:
3054
+ *
3055
+ * - `E` — the `@tailwindcss/node` version the plugin will actually run.
3056
+ * - `B` — the `tailwindcss` version the consumer's build compiles with.
3057
+ *
3058
+ * `assessEngine` grades `(E, B)` against the plugin's supported range and the
3059
+ * drift between the two, returning `ok` / `warn` / `fatal`. `emitEngineVerdict`
3060
+ * turns a `fatal` into an `UnsupportedEngineError` (which the fatal-reporter
3061
+ * routes to `designSystemUnavailable` with no per-rule `meta` change) and a
3062
+ * `warn` into a one-time stderr notice.
3063
+ *
3064
+ * The comparator is a hand-rolled subset of semver (no `semver` dependency —
3065
+ * runtime deps stay `@tailwindcss/node` + `tailwindcss` only). It is total and
3066
+ * never throws; unparseable input reads as "unknown".
3067
+ */
3068
+ const WARN_PREFIX = "[oxlint-tailwindcss]";
3069
+ /** The lowest Tailwind major this plugin supports. */
3070
+ const SUPPORTED_MAJOR = 4;
3071
+ /**
3072
+ * `4.1.0`, the minimum engine version. The precompute calls
3073
+ * `ds.canonicalizeCandidates`, which the design system only exposes from
3074
+ * Tailwind 4.1 onward — on 4.0.x it throws `is not a function`, so we fail loud
3075
+ * with a clear message before spawning the worker. A `4.1.0-*` prerelease sorts
3076
+ * below it.
3077
+ */
3078
+ const MIN_ENGINE = {
3079
+ major: 4,
3080
+ minor: 1,
3081
+ patch: 0,
3082
+ prerelease: null
3083
+ };
3084
+ /**
3085
+ * Parse a version string into `{ major, minor, patch, prerelease }`, or `null`
3086
+ * for anything unparseable (`''`, `'unknown'`, a range like `'^4.3.3'`, a dist
3087
+ * tag like `'next'`, non-strings). Total — never throws.
3088
+ */
3089
+ function parseVersion(v) {
3090
+ if (typeof v !== "string") return null;
3091
+ let s = v.trim();
3092
+ if (s === "" || s === "unknown") return null;
3093
+ if (s[0] === "v" || s[0] === "V") s = s.slice(1);
3094
+ const plus = s.indexOf("+");
3095
+ if (plus !== -1) s = s.slice(0, plus);
3096
+ let prerelease = null;
3097
+ const dash = s.indexOf("-");
3098
+ if (dash !== -1) {
3099
+ prerelease = s.slice(dash + 1) || null;
3100
+ s = s.slice(0, dash);
3101
+ }
3102
+ const parts = s.split(".");
3103
+ const major = Number.parseInt(parts[0], 10);
3104
+ if (Number.isNaN(major)) return null;
3105
+ const minor = Number.parseInt(parts[1] ?? "0", 10);
3106
+ const patch = Number.parseInt(parts[2] ?? "0", 10);
3107
+ return {
3108
+ major,
3109
+ minor: Number.isNaN(minor) ? 0 : minor,
3110
+ patch: Number.isNaN(patch) ? 0 : patch,
3111
+ prerelease
3112
+ };
3113
+ }
3114
+ /** Compare by major, minor, patch; at equal core, a release outranks a prerelease. */
3115
+ function compareVersions(a, b) {
3116
+ if (a.major !== b.major) return a.major < b.major ? -1 : 1;
3117
+ if (a.minor !== b.minor) return a.minor < b.minor ? -1 : 1;
3118
+ if (a.patch !== b.patch) return a.patch < b.patch ? -1 : 1;
3119
+ if (a.prerelease === b.prerelease) return 0;
3120
+ if (a.prerelease === null) return 1;
3121
+ if (b.prerelease === null) return -1;
3122
+ return a.prerelease < b.prerelease ? -1 : a.prerelease > b.prerelease ? 1 : 0;
3123
+ }
3124
+ function sameMajor(a, b) {
3125
+ return a.major === b.major;
3126
+ }
3127
+ function sameMinor(a, b) {
3128
+ return a.major === b.major && a.minor === b.minor;
3129
+ }
3130
+ /**
3131
+ * Grade `(E, B)` against the supported range and build drift. First matching
3132
+ * row wins (see the decision table in the PR / plan). Pure and total: safe to
3133
+ * unit-test with literal version strings.
3134
+ */
3135
+ function assessEngine(E, B, opts) {
3136
+ const pe = parseVersion(E);
3137
+ const pb = parseVersion(B);
3138
+ const bundled = opts.bundledVersion;
3139
+ if (pe === null) return {
3140
+ verdict: "ok",
3141
+ kind: "engine-version-unknown",
3142
+ message: "Could not determine the resolved Tailwind engine version; skipping the version guard."
3143
+ };
3144
+ if (pe.major < SUPPORTED_MAJOR || compareVersions(pe, MIN_ENGINE) < 0) return {
3145
+ verdict: "fatal",
3146
+ kind: "engine-too-old",
3147
+ message: `oxlint-tailwindcss requires Tailwind CSS v4.1 or newer, but the resolved engine is ${E}.`,
3148
+ hint: "Upgrade tailwindcss / @tailwindcss/node to v4.1+, or pin an older oxlint-tailwindcss."
3149
+ };
3150
+ if (pe.major > SUPPORTED_MAJOR) {
3151
+ if (opts.allowUntested) return {
3152
+ verdict: "warn",
3153
+ kind: "engine-future-major-allowed",
3154
+ message: `Running against untested Tailwind engine ${E} (a major newer than the tested ${bundled}) because allowUntestedEngine is set — results may be inaccurate.`
3155
+ };
3156
+ return {
3157
+ verdict: "fatal",
3158
+ kind: "engine-future-major",
3159
+ message: `The resolved Tailwind engine ${E} is a major version newer than this plugin was built for (tested against ${bundled}); its behavior is unverified.`,
3160
+ hint: "Set settings.tailwindcss.allowUntestedEngine: true to run anyway (results may be inaccurate), or upgrade oxlint-tailwindcss."
3161
+ };
3162
+ }
3163
+ if (pb !== null && !sameMajor(pe, pb)) {
3164
+ if (opts.allowUntested) return {
3165
+ verdict: "warn",
3166
+ kind: "engine-build-drift-major-allowed",
3167
+ message: `Linting with Tailwind engine ${E} while your build uses tailwindcss@${B} (a different major) because allowUntestedEngine is set — the plugin enforces different semantics than your build produces.`
3168
+ };
3169
+ return {
3170
+ verdict: "fatal",
3171
+ kind: "engine-build-drift-major",
3172
+ message: `Linting with Tailwind engine ${E} but your build uses tailwindcss@${B} (a different major); the plugin would enforce different Tailwind semantics than your build produces.`,
3173
+ hint: "Align the versions, or set settings.tailwindcss.allowUntestedEngine: true to override."
3174
+ };
3175
+ }
3176
+ if (pb !== null && !sameMinor(pe, pb)) return {
3177
+ verdict: "warn",
3178
+ kind: "engine-build-drift-minor",
3179
+ message: `Linting with Tailwind engine ${E} but your build uses tailwindcss@${B}; lint results may differ from your compiled CSS.`,
3180
+ hint: "Align the versions, or ignore if intentional."
3181
+ };
3182
+ const pBundled = parseVersion(bundled);
3183
+ if (pBundled !== null && compareVersions(pe, pBundled) > 0) return {
3184
+ verdict: "warn",
3185
+ kind: "engine-newer-minor",
3186
+ message: `The resolved Tailwind engine ${E} is newer than the version this plugin was tested against (${bundled}); newly added utilities may be reported as unknown.`,
3187
+ hint: "Usually safe; upgrade oxlint-tailwindcss if you see false positives."
3188
+ };
3189
+ return {
3190
+ verdict: "ok",
3191
+ kind: "ok",
3192
+ message: ""
3193
+ };
3194
+ }
3195
+ const warnedEngineKeys = /* @__PURE__ */ new Set();
3196
+ /**
3197
+ * Act on a verdict: `fatal` throws `UnsupportedEngineError` (routed to
3198
+ * `designSystemUnavailable`), `warn` emits a one-time stderr notice keyed by
3199
+ * `(entryPoint, kind, E, B)`, `ok` is silent. `debugLog` (self-gated) always
3200
+ * records the structured detail when debug is on.
3201
+ */
3202
+ function emitEngineVerdict(v, ctx) {
3203
+ if (v.verdict === "fatal") throw new UnsupportedEngineError(v.message, v.hint);
3204
+ if (v.verdict === "warn") {
3205
+ const key = `${ctx.resolvedPath}\0${v.kind}\0${ctx.E}\0${ctx.B}`;
3206
+ if (!warnedEngineKeys.has(key)) {
3207
+ warnedEngineKeys.add(key);
3208
+ console.warn(`${WARN_PREFIX} ${v.message}`);
3209
+ }
3210
+ }
3211
+ debugLog(`engine E=${ctx.E} B=${ctx.B} → ${v.kind}`);
3212
+ }
3213
+ /**
3214
+ * Resolve the engine for `resolvedPath` (or use injected facts), assess it, and
3215
+ * emit the verdict. Throws `UnsupportedEngineError` on a fatal verdict. Called
3216
+ * once per entry point from `getLoadedDesignSystem`, inside its fatal-caching
3217
+ * `try`.
3218
+ */
3219
+ function guardEngine(resolvedPath, allowUntested, override) {
3220
+ let E;
3221
+ let B;
3222
+ let bundledVersion;
3223
+ if (override) {
3224
+ E = override.E;
3225
+ B = override.B;
3226
+ bundledVersion = override.bundledVersion ?? TAILWIND_NODE_VERSION;
3227
+ } else {
3228
+ const res = resolveTailwindNodeFor(resolvedPath);
3229
+ E = res.nodeVersion;
3230
+ B = res.buildVersion;
3231
+ bundledVersion = TAILWIND_NODE_VERSION;
3232
+ }
3233
+ emitEngineVerdict(assessEngine(E, B, {
3234
+ allowUntested,
3235
+ bundledVersion
3236
+ }), {
3237
+ resolvedPath,
3238
+ E,
3239
+ B
3240
+ });
3241
+ }
3242
+ /** Read `settings.tailwindcss.allowUntestedEngine` (default `false`). */
3243
+ function allowUntestedEngineFromSettings(settings) {
3244
+ const tw = settings?.tailwindcss;
3245
+ if (tw && typeof tw === "object" && "allowUntestedEngine" in tw) return tw.allowUntestedEngine === true;
3246
+ return false;
3247
+ }
3248
+ //#endregion
2901
3249
  //#region src/utils/context.ts
2902
3250
  /**
2903
3251
  * Safely read `context.options[0]`. Returns `undefined` if the getter throws
@@ -2930,6 +3278,22 @@ function safeFilename(context) {
2930
3278
  }
2931
3279
  }
2932
3280
  /**
3281
+ * Safely read `context.sourceCode`. Same try/catch pattern as the other
3282
+ * accessors (the getter may throw inside `createOnce`). Used by
3283
+ * `enforce-consistent-line-wrapping` to derive a statement's real base
3284
+ * indentation (the line's leading whitespace) when wrapping a single-line
3285
+ * template into the block convention — the backtick column
3286
+ * (`node.loc.start.column`) is NOT the base indent. Returns `undefined` if
3287
+ * unavailable; callers fall back to a zero base indent.
3288
+ */
3289
+ function safeSourceCode(context) {
3290
+ try {
3291
+ return context.sourceCode ?? void 0;
3292
+ } catch {
3293
+ return;
3294
+ }
3295
+ }
3296
+ /**
2933
3297
  * Safely read `context.cwd`, falling back to `process.cwd()`. Same try/catch
2934
3298
  * pattern as the other accessors (the getter throws in `createOnce` on older
2935
3299
  * oxlint). The fallback keeps relative-path resolution working even when the
@@ -3155,7 +3519,7 @@ function timeoutFromSettings(settings) {
3155
3519
  * Cached per absolute entry-point path, keyed by mtime. In monorepos each
3156
3520
  * unique CSS gets its own cache entry.
3157
3521
  */
3158
- function getLoadedDesignSystem(cssPath, settings) {
3522
+ function getLoadedDesignSystem(cssPath, settings, engineInfo) {
3159
3523
  const resolvedPath = resolve(cssPath);
3160
3524
  let mtime;
3161
3525
  try {
@@ -3172,6 +3536,7 @@ function getLoadedDesignSystem(cssPath, settings) {
3172
3536
  if (failed && failed.mtime === mtime) throw failed.error;
3173
3537
  let data;
3174
3538
  try {
3539
+ guardEngine(resolvedPath, allowUntestedEngineFromSettings(settings), engineInfo);
3175
3540
  data = loadDesignSystemSync(resolvedPath, timeoutFromSettings(settings));
3176
3541
  } catch (err) {
3177
3542
  if (isFatalError(err)) dsFailureCache.set(resolvedPath, {
@@ -3397,7 +3762,8 @@ var DesignSystemWorker = class {
3397
3762
  this.workers.set(cssPath, existing);
3398
3763
  return existing;
3399
3764
  }
3400
- 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."));
3765
+ const { nodePath: tailwindNodePath } = resolveTailwindNodeFor(cssPath);
3766
+ if (tailwindNodePath === 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."));
3401
3767
  const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
3402
3768
  const controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
3403
3769
  const lengthView = new DataView(sharedBuffer, HEADER_INTS * 4, 4);
@@ -3409,7 +3775,7 @@ var DesignSystemWorker = class {
3409
3775
  workerData: {
3410
3776
  sharedBuffer,
3411
3777
  cssPath,
3412
- tailwindNodePath: TAILWIND_NODE_PATH
3778
+ tailwindNodePath
3413
3779
  }
3414
3780
  });
3415
3781
  } catch (cause) {
@@ -5212,8 +5578,22 @@ const enforceShorthand = defineRule({
5212
5578
  if (!mergeIsSafe(family, group.value, cache)) continue;
5213
5579
  const matched = family.parts.map((part) => group.byPart.get(part));
5214
5580
  const replacement = group.variant + reattachImportant(`${family.to}-${group.value}`, group.position);
5215
- const remaining = classes.filter((cls) => !matched.includes(cls));
5216
- if (!remaining.includes(replacement)) remaining.push(replacement);
5581
+ const matchedSet = new Set(matched);
5582
+ const remaining = [];
5583
+ const sourceIndices = [];
5584
+ let firstMatchedIdx = -1;
5585
+ classes.forEach((cls, i) => {
5586
+ if (matchedSet.has(cls)) {
5587
+ if (firstMatchedIdx === -1) firstMatchedIdx = i;
5588
+ return;
5589
+ }
5590
+ remaining.push(cls);
5591
+ sourceIndices.push(i);
5592
+ });
5593
+ if (!remaining.includes(replacement)) {
5594
+ remaining.push(replacement);
5595
+ sourceIndices.push(firstMatchedIdx);
5596
+ }
5217
5597
  for (const part of family.parts) consumed.add(part);
5218
5598
  context.report({
5219
5599
  node: loc.node,
@@ -5223,7 +5603,7 @@ const enforceShorthand = defineRule({
5223
5603
  replacement
5224
5604
  },
5225
5605
  fix(fixer) {
5226
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, rebuildClassString(split, remaining)));
5606
+ return fixer.replaceTextRange(loc.range, preserveSpaces(loc, rebuildClassString(split, remaining, sourceIndices)));
5227
5607
  }
5228
5608
  });
5229
5609
  }
@@ -6452,6 +6832,14 @@ const consistentVariantOrder = defineRule({
6452
6832
  //#endregion
6453
6833
  //#region src/rules/enforce-consistent-line-wrapping.ts
6454
6834
  const DEFAULT_PRINT_WIDTH = 80;
6835
+ /** One indentation level added below the statement's base indent for wrapped lines. */
6836
+ const INDENT_UNIT = " ";
6837
+ /** Group `classes` into chunks of at most `n`, each chunk space-joined. */
6838
+ function chunkList(classes, n) {
6839
+ const chunks = [];
6840
+ for (let i = 0; i < classes.length; i += n) chunks.push(classes.slice(i, i + n).join(" "));
6841
+ return chunks;
6842
+ }
6455
6843
  const enforceConsistentLineWrapping = defineRule({
6456
6844
  meta: {
6457
6845
  type: "suggestion",
@@ -6467,52 +6855,97 @@ const enforceConsistentLineWrapping = defineRule({
6467
6855
  }],
6468
6856
  defaultOptions: [{ printWidth: DEFAULT_PRINT_WIDTH }],
6469
6857
  messages: {
6470
- tooLong: "Class string is {{length}} characters long, exceeding the print width of {{printWidth}}. Consider splitting into multiple lines or extracting into a component.",
6858
+ tooLong: "Class string exceeds the print width of {{printWidth}} (longest line is {{length}} characters). Consider splitting into multiple lines or extracting into a component.",
6471
6859
  tooManyPerLine: "Too many classes on a single line ({{count}}). Maximum allowed per line is {{max}}."
6472
6860
  }
6473
6861
  },
6474
6862
  createOnce(context) {
6475
6863
  const getPrintWidth = createLazyOptions(context, (o) => o?.printWidth ?? DEFAULT_PRINT_WIDTH);
6476
6864
  const getClassesPerLine = createLazyOptions(context, (o) => o?.classesPerLine);
6865
+ /**
6866
+ * The statement's real base indentation — the leading whitespace of the
6867
+ * source line the opening backtick sits on. NOT `node.loc.start.column`,
6868
+ * which is the backtick's column (e.g. 18 for `const className = ` and
6869
+ * deeper still inside nested JSX). Falls back to `''` when `sourceCode`
6870
+ * is unavailable (block still lands correctly for top-level statements).
6871
+ */
6872
+ function deriveBaseIndent(loc) {
6873
+ const sc = safeSourceCode(context);
6874
+ const line = loc.node.loc?.start.line;
6875
+ if (sc?.lines && typeof line === "number" && line >= 1 && line <= sc.lines.length) {
6876
+ const src = sc.lines[line - 1] ?? "";
6877
+ const m = /^[ \t]*/.exec(src);
6878
+ return m ? m[0] : "";
6879
+ }
6880
+ return "";
6881
+ }
6882
+ /**
6883
+ * Re-wrap a template literal's classes into the block convention,
6884
+ * non-destructively:
6885
+ * - single-line → convert to a `\n` + indent block (unless the quasi is
6886
+ * glued to a `${}`, in which case keep it inline/hanging so adjacency
6887
+ * survives);
6888
+ * - already multiline → re-wrap ONLY the lines that exceed the budget,
6889
+ * reusing each line's own indent; conforming lines are left verbatim.
6890
+ */
6891
+ function rewrapTemplate(loc, lines, classesPerLine) {
6892
+ const baseIndent = deriveBaseIndent(loc);
6893
+ const interiorIndent = baseIndent + INDENT_UNIT;
6894
+ if (lines.length === 1) {
6895
+ const chunks = chunkList(splitClasses(loc.value), classesPerLine);
6896
+ if (!loc.preserveLeadingSpace && !loc.preserveTrailingSpace) return "\n" + chunks.map((c) => interiorIndent + c).join("\n") + "\n" + baseIndent;
6897
+ return chunks.join("\n" + interiorIndent);
6898
+ }
6899
+ return lines.map((line) => {
6900
+ const classes = splitClasses(line);
6901
+ if (classes.length <= classesPerLine) return line;
6902
+ const m = /^[ \t]*/.exec(line);
6903
+ const lineIndent = m && m[0].length > 0 ? m[0] : interiorIndent;
6904
+ return chunkList(classes, classesPerLine).map((c) => lineIndent + c).join("\n");
6905
+ }).join("\n");
6906
+ }
6477
6907
  function check(locations) {
6478
6908
  const printWidth = getPrintWidth();
6479
6909
  const classesPerLine = getClassesPerLine();
6480
6910
  for (const loc of locations) {
6481
- if (loc.value.length > printWidth) context.report({
6911
+ let maxLine = 0;
6912
+ for (const line of loc.value.split("\n")) if (line.length > maxLine) maxLine = line.length;
6913
+ if (maxLine > printWidth) context.report({
6482
6914
  node: loc.node,
6483
6915
  messageId: "tooLong",
6484
6916
  data: {
6485
- length: String(loc.value.length),
6917
+ length: String(maxLine),
6486
6918
  printWidth: String(printWidth)
6487
6919
  }
6488
6920
  });
6489
6921
  if (classesPerLine !== void 0) {
6490
- const classes = splitClasses(loc.value);
6491
- if (classes.length > classesPerLine) if (loc.node.type === "TemplateElement") {
6492
- const chunks = [];
6493
- for (let i = 0; i < classes.length; i += classesPerLine) chunks.push(classes.slice(i, i + classesPerLine).join(" "));
6494
- const startCol = loc.node.loc?.start.column ?? 0;
6495
- const indent = " ".repeat(startCol);
6496
- const fixedValue = chunks.join("\n" + indent);
6497
- context.report({
6922
+ const lines = loc.value.split("\n");
6923
+ let maxPerLine = 0;
6924
+ for (const line of lines) {
6925
+ const n = splitClasses(line).length;
6926
+ if (n > maxPerLine) maxPerLine = n;
6927
+ }
6928
+ if (maxPerLine > classesPerLine) {
6929
+ const data = {
6930
+ count: String(maxPerLine),
6931
+ max: String(classesPerLine)
6932
+ };
6933
+ if (loc.node.type === "TemplateElement") {
6934
+ const fixedValue = rewrapTemplate(loc, lines, classesPerLine);
6935
+ context.report({
6936
+ node: loc.node,
6937
+ messageId: "tooManyPerLine",
6938
+ data,
6939
+ fix(fixer) {
6940
+ return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
6941
+ }
6942
+ });
6943
+ } else context.report({
6498
6944
  node: loc.node,
6499
6945
  messageId: "tooManyPerLine",
6500
- data: {
6501
- count: String(classes.length),
6502
- max: String(classesPerLine)
6503
- },
6504
- fix(fixer) {
6505
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
6506
- }
6946
+ data
6507
6947
  });
6508
- } else context.report({
6509
- node: loc.node,
6510
- messageId: "tooManyPerLine",
6511
- data: {
6512
- count: String(classes.length),
6513
- max: String(classesPerLine)
6514
- }
6515
- });
6948
+ }
6516
6949
  }
6517
6950
  }
6518
6951
  }