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