oxlint-tailwindcss 1.10.2 → 1.11.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/README.md CHANGED
@@ -34,8 +34,8 @@ Read the story behind this plugin:
34
34
  possible.
35
35
  - **Variable detection** — Lints variables matching `/^classNames?$/`, `/^classes$/`, `/^styles?$/`
36
36
  (e.g. `className`, `classNames`, `classes`, `styles`) automatically.
37
- - **Customizable** — Extend class detection with custom attributes, callees, tags, and variable
38
- patterns.
37
+ - **Customizable** — Extend class detection with custom attributes, attribute patterns (regex, for
38
+ `*ClassName` props), callees, tags, and variable patterns.
39
39
  - **Component class support** — Recognizes `@layer components { .btn {} }` in your CSS.
40
40
 
41
41
  Full documentation: **https://oxlint-tailwindcss.pages.dev** (English) ·
@@ -165,6 +165,18 @@ For slow environments (large monorepos, CI), you can increase the design system
165
165
  }
166
166
  ```
167
167
 
168
+ This `timeout` governs the **precompute loader** only. The sort/canonicalize/declaration worker
169
+ services used while linting have a separate **30 s per-request** timeout. If a slow-but-functional
170
+ machine or CI runner reports `worker request timed out after 30000ms` on valid class lists, raise it
171
+ with the `OXLINT_TAILWINDCSS_WORKER_REQUEST_TIMEOUT` environment variable (milliseconds):
172
+
173
+ ```bash
174
+ OXLINT_TAILWINDCSS_WORKER_REQUEST_TIMEOUT=60000 oxlint
175
+ ```
176
+
177
+ A timeout no longer costs O(files): after a few consecutive timeouts for one entry point the rest of
178
+ the run fails fast, and the state self-heals once the machine recovers.
179
+
168
180
  ### Root font size
169
181
 
170
182
  The `enforce-canonical` rule converts px-based arbitrary values to named classes (e.g. `p-[2px]` →
@@ -230,8 +242,11 @@ entries are appended to the built-in defaults:
230
242
  "jsPlugins": ["oxlint-tailwindcss"],
231
243
  "settings": {
232
244
  "tailwindcss": {
233
- // Additional JSX attribute names to scan
245
+ // Additional JSX attribute names to scan (exact match)
234
246
  "attributes": ["xyzClassName", "classNames", "overlayClassName"],
247
+ // Regex patterns for JSX attribute names — catches *ClassName conventions
248
+ // (React Native / Uniwind) without listing every prop
249
+ "attributePatterns": ["ClassName$"],
235
250
  // Additional function names to scan
236
251
  "callees": ["myHelper"],
237
252
  // Additional tagged template tags to scan
@@ -250,6 +265,12 @@ entries are appended to the built-in defaults:
250
265
  This applies to all 24 rules at once. For example, adding `"classNames"` to `attributes` makes every
251
266
  rule lint `<Input classNames={{ root: "..." }} />`.
252
267
 
268
+ > **`attributePatterns` vs `variablePatterns`** — both match by regex, but on different things.
269
+ > `attributePatterns` matches **JSX attribute names** (`contentContainerClassName`,
270
+ > `tintColorClassName`, …); `variablePatterns` matches **variable declaration names only**
271
+ > (`const fooClassName = "..."`), never JSX attributes — despite its default `/^classNames?$/`
272
+ > looking like the `className` attribute.
273
+
253
274
  To **remove** specific items from the built-in defaults, use `exclude`:
254
275
 
255
276
  ```jsonc
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.80.0/node_modules/@oxlint/plugins/index.js
6
+ //#region ../../node_modules/.pnpm/@oxlint+plugins@1.82.0/node_modules/@oxlint/plugins/index.js
7
7
  /**
8
8
  * Define a plugin.
9
9
  *
@@ -115,6 +115,7 @@ function preserveSpaces(loc, fixed) {
115
115
  }
116
116
  const DEFAULT_EXTRACTOR_CONFIG = {
117
117
  attributes: ["className", "class"],
118
+ attributePatterns: [],
118
119
  callees: [
119
120
  "cn",
120
121
  "clsx",
@@ -178,6 +179,7 @@ function getExtractorConfig(context) {
178
179
  const filteredPatterns = excludedPatternSources.size > 0 ? DEFAULT_EXTRACTOR_CONFIG.variablePatterns.filter((re) => !excludedPatternSources.has(re.source)) : DEFAULT_EXTRACTOR_CONFIG.variablePatterns;
179
180
  const resolved = {
180
181
  attributes: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.attributes, tw.attributes, exclude?.attributes),
182
+ attributePatterns: compileRegexList(tw.attributePatterns),
181
183
  callees: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.callees, tw.callees, exclude?.callees),
182
184
  tags: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.tags, tw.tags, exclude?.tags),
183
185
  variablePatterns: [...filteredPatterns, ...compileRegexList(tw.variablePatterns)]
@@ -237,7 +239,7 @@ function jsxHostOrigin(node) {
237
239
  */
238
240
  function extractFromJSXAttribute(node, config = DEFAULT_EXTRACTOR_CONFIG) {
239
241
  const name = node.name.type === "JSXIdentifier" ? node.name.name : void 0;
240
- if (!name || !config.attributes.includes(name)) return [];
242
+ if (!name || !config.attributes.includes(name) && !config.attributePatterns.some((p) => p.test(name))) return [];
241
243
  if (!node.value) return [];
242
244
  const hostOrigin = jsxHostOrigin(node);
243
245
  if (node.value.type === "Literal" && typeof node.value.value === "string") return [{
@@ -461,7 +463,8 @@ function appendFromTemplateLiteral(node, out) {
461
463
  node: quasi,
462
464
  range: [start, start + value.length],
463
465
  preserveLeadingSpace: i > 0,
464
- preserveTrailingSpace: i < node.quasis.length - 1
466
+ preserveTrailingSpace: i < node.quasis.length - 1,
467
+ templateLine: node.loc?.start.line
465
468
  });
466
469
  }
467
470
  }
@@ -792,6 +795,26 @@ function splitUtilityAndVariant(cls) {
792
795
  };
793
796
  }
794
797
  /**
798
+ * Strips a Tailwind v4 project prefix (`@import "tailwindcss" prefix(tw)` → `tw`)
799
+ * off a class, returning the matched prefix marker (`"tw:"`, or `""`) and the
800
+ * remaining body. The project prefix is structurally a variant but pinned FIRST
801
+ * (`tw:hover:flex`, never `hover:tw:flex`), so grouping/ordering rules strip it
802
+ * before reading the real variant chain — the prefix invariant shared by
803
+ * enforce-sort-order, consistent-variant-order and enforce-consistent-line-wrapping.
804
+ * `prefix === ""` (no project prefix / no design system) or a non-matching class
805
+ * passes through untouched.
806
+ */
807
+ function stripProjectPrefix(cls, prefix) {
808
+ if (prefix !== "" && cls.startsWith(prefix + ":")) return {
809
+ prefix: prefix + ":",
810
+ body: cls.slice(prefix.length + 1)
811
+ };
812
+ return {
813
+ prefix: "",
814
+ body: cls
815
+ };
816
+ }
817
+ /**
795
818
  * Checks if a class has an arbitrary value (bracket syntax in the utility part).
796
819
  * Distinguishes from arbitrary variants: [&>svg]:w-4 does NOT have an arbitrary value,
797
820
  * but w-[200px] does.
@@ -2769,7 +2792,30 @@ function cacheDirName() {
2769
2792
  return "oxlint-tailwindcss";
2770
2793
  }
2771
2794
  }
2772
- const CACHE_DIR = (0, node_path.join)((0, node_os.tmpdir)(), cacheDirName());
2795
+ /**
2796
+ * The disk-cache directory.
2797
+ *
2798
+ * Defaults to a per-uid dir under the system temp dir (see `cacheDirName`), but
2799
+ * honours `OXLINT_TAILWINDCSS_CACHE_DIR` when set to a non-empty value. Two uses:
2800
+ * - CI / sandboxed builds that want the cache at a controlled, pruneable
2801
+ * location instead of the shared system temp dir.
2802
+ * - The test suite, which points each `pnpm test` invocation at its OWN dir
2803
+ * (`vitest.config.ts`) so two concurrent runs — a background run and the
2804
+ * stop-hook's run, or a dev's editor running oxlint alongside the tests —
2805
+ * never share cache files and race on them (the source of the
2806
+ * `canonicalize-persistence` EISDIR / stale-read flakes).
2807
+ *
2808
+ * The dir the plugin creates is still `mode 0o700` (see `computeWithLock`), so
2809
+ * an override the plugin creates stays private to its owner; pointing the
2810
+ * override at a pre-existing world-writable dir re-opens the poisoning vector
2811
+ * `cacheDirName` closes, so that is the caller's responsibility.
2812
+ */
2813
+ function resolveCacheDir() {
2814
+ const override = process.env.OXLINT_TAILWINDCSS_CACHE_DIR;
2815
+ if (typeof override === "string" && override.trim() !== "") return override.trim();
2816
+ return (0, node_path.join)((0, node_os.tmpdir)(), cacheDirName());
2817
+ }
2818
+ const CACHE_DIR = resolveCacheDir();
2773
2819
  /** md5 of the precompute script (no version) — the version is folded in per entry point. */
2774
2820
  const SCRIPT_HASH = (0, node_crypto.createHash)("md5").update(PRECOMPUTE_SCRIPT).digest("hex").slice(0, 8);
2775
2821
  /**
@@ -2912,7 +2958,7 @@ function reclaimStaleLock$1(lockPath) {
2912
2958
  }
2913
2959
  /** control[2] — the worker's ready/done signal (0=loading, 1=done, -1=error). */
2914
2960
  const PRECOMPUTE_SIGNAL_INDEX = 2;
2915
- const ERR_BUFFER_SIZE = 64 * 1024;
2961
+ const ERR_BUFFER_SIZE = 65536;
2916
2962
  let precomputeSeq = 0;
2917
2963
  /**
2918
2964
  * Choose the diagnostic hint based on the underlying error code. ENOMEM/EAGAIN
@@ -3681,17 +3727,38 @@ function resolveEntryPointForFile(ruleOptionEntry, settingsEntry, filePath, cwd
3681
3727
  * — SharedArrayBuffer layout, state machine, lifecycle, fail-loud — and each
3682
3728
  * service shrinks to ~40 LOC of singleton + public signature.
3683
3729
  *
3684
- * v1: failures throw `SortServiceError`. The error is sticky for the lifetime
3685
- * of the process (per cssPath) so subsequent calls don't pay another
3686
- * init-timeout cost. Callers wrap via `safeGetDS` to surface the failure as a
3687
- * single `designSystemUnavailable` diagnostic.
3688
- */
3689
- const BUFFER_SIZE = 4 * 1024 * 1024;
3730
+ * v1: failures throw `SortServiceError`. Init/spawn/crash/DS-load failures are
3731
+ * HARD sticky per cssPath for the process lifetime, so subsequent calls don't
3732
+ * pay another init-timeout cost. Per-request failures (timeout / non-JSON /
3733
+ * null) are SOFT sticky (#145): unbounded retrying re-pays the full request
3734
+ * timeout on every class list (O(files)), so after a few consecutive failures
3735
+ * the error goes sticky for a backoff window and the rest of the run fails fast;
3736
+ * any success clears it. Callers wrap via `safeGetDS` to surface the failure as
3737
+ * a single `designSystemUnavailable` diagnostic.
3738
+ */
3739
+ const BUFFER_SIZE = 4194304;
3690
3740
  const HEADER_INTS = 4;
3691
- const LENGTH_OFFSET = HEADER_INTS * 4;
3741
+ const LENGTH_OFFSET = 16;
3692
3742
  const DATA_OFFSET = 20;
3693
3743
  const INIT_TIMEOUT = 6e4;
3694
3744
  const REQUEST_TIMEOUT = 3e4;
3745
+ const MAX_CONSECUTIVE_REQUEST_FAILURES = 3;
3746
+ const REQUEST_STICKY_BACKOFF_MS = 6e4;
3747
+ /**
3748
+ * Per-request timeout override for slow-but-functional machines (#145). A
3749
+ * machine whose cold canonicalize sits close to the 30 s default times out
3750
+ * spuriously; raising this lets the request COMPLETE (the rule keeps working)
3751
+ * rather than only failing fast. An env var — not a `settings.tailwindcss` key —
3752
+ * keeps the documented invariant that worker services don't read
3753
+ * `settings.tailwindcss.timeout`, and sidesteps the settings-timing problem
3754
+ * (settings throw inside `createOnce`). Read once per worker construction.
3755
+ */
3756
+ function envRequestTimeout() {
3757
+ const raw = process.env.OXLINT_TAILWINDCSS_WORKER_REQUEST_TIMEOUT;
3758
+ if (raw === void 0 || raw === "") return void 0;
3759
+ const n = Number(raw);
3760
+ return Number.isFinite(n) && n > 0 ? n : void 0;
3761
+ }
3695
3762
  const MAX_WORKERS = 8;
3696
3763
  /**
3697
3764
  * Build the worker script shared by `sort-service` and `canonicalize-service`.
@@ -3778,15 +3845,41 @@ var DesignSystemWorker = class {
3778
3845
  opts;
3779
3846
  workers = /* @__PURE__ */ new Map();
3780
3847
  errors = /* @__PURE__ */ new Map();
3848
+ requestFailCount = /* @__PURE__ */ new Map();
3849
+ requestStick = /* @__PURE__ */ new Map();
3850
+ /** Resolved per-request timeout (option > env var > REQUEST_TIMEOUT). */
3851
+ requestTimeoutMs;
3852
+ /** Resolved consecutive-failure budget before a per-request error goes soft-sticky. */
3853
+ maxConsecutiveRequestFailures;
3781
3854
  constructor(opts) {
3782
3855
  this.opts = opts;
3856
+ this.requestTimeoutMs = opts.requestTimeoutMs ?? envRequestTimeout() ?? REQUEST_TIMEOUT;
3857
+ this.maxConsecutiveRequestFailures = opts.maxConsecutiveRequestFailures ?? MAX_CONSECUTIVE_REQUEST_FAILURES;
3783
3858
  }
3784
- /** Record an error as sticky for `cssPath` and return it for `throw`. */
3859
+ /** Record an error as HARD sticky for `cssPath` and return it for `throw`. */
3785
3860
  remember(cssPath, err) {
3786
3861
  this.errors.set(cssPath, err);
3787
3862
  return err;
3788
3863
  }
3789
3864
  /**
3865
+ * Handle a per-request (SOFT) failure (#145): drop the worker so the next call
3866
+ * re-spawns, count consecutive failures for this cssPath, and once the budget
3867
+ * is spent record a soft sticky good for a backoff window so the rest of the
3868
+ * run fails fast instead of re-paying the timeout per class list. A later
3869
+ * success (see `callSync`) clears the count and the soft sticky. Returns the
3870
+ * error for `throw` (mirrors `remember`).
3871
+ */
3872
+ failRequest(cssPath, err) {
3873
+ this.dropWorker(cssPath);
3874
+ const count = (this.requestFailCount.get(cssPath) ?? 0) + 1;
3875
+ this.requestFailCount.set(cssPath, count);
3876
+ if (count >= this.maxConsecutiveRequestFailures) this.requestStick.set(cssPath, {
3877
+ err,
3878
+ until: Date.now() + REQUEST_STICKY_BACKOFF_MS
3879
+ });
3880
+ return err;
3881
+ }
3882
+ /**
3790
3883
  * Ensure the worker is running and pointed at `cssPath`. Returns the
3791
3884
  * ready state. Throws `SortServiceError` on any failure (init timeout,
3792
3885
  * spawn error, DS-load error). Sticky: subsequent calls for the same
@@ -3795,6 +3888,12 @@ var DesignSystemWorker = class {
3795
3888
  ensure(cssPath) {
3796
3889
  const sticky = this.errors.get(cssPath);
3797
3890
  if (sticky) throw sticky;
3891
+ const soft = this.requestStick.get(cssPath);
3892
+ if (soft) {
3893
+ if (Date.now() < soft.until) throw soft.err;
3894
+ this.requestStick.delete(cssPath);
3895
+ this.requestFailCount.delete(cssPath);
3896
+ }
3798
3897
  const existing = this.workers.get(cssPath);
3799
3898
  if (existing) {
3800
3899
  this.workers.delete(cssPath);
@@ -3805,7 +3904,7 @@ var DesignSystemWorker = class {
3805
3904
  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."));
3806
3905
  const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
3807
3906
  const controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
3808
- const lengthView = new DataView(sharedBuffer, HEADER_INTS * 4, 4);
3907
+ const lengthView = new DataView(sharedBuffer, 16, 4);
3809
3908
  const dataArea = new Uint8Array(sharedBuffer, DATA_OFFSET);
3810
3909
  let worker;
3811
3910
  try {
@@ -3864,15 +3963,12 @@ var DesignSystemWorker = class {
3864
3963
  callSync(cssPath, req) {
3865
3964
  const state = this.ensure(cssPath);
3866
3965
  const requestBytes = Buffer.from(JSON.stringify(req), "utf-8");
3867
- if (requestBytes.length > BUFFER_SIZE - DATA_OFFSET) throw new SortServiceError(`${this.opts.serviceName} request payload is too large (${requestBytes.length} > ${BUFFER_SIZE - DATA_OFFSET} bytes).`, "This is unexpected with typical class lists; please open an issue.");
3966
+ if (requestBytes.length > 4194284) throw new SortServiceError(`${this.opts.serviceName} request payload is too large (${requestBytes.length} > 4194284 bytes).`, "This is unexpected with typical class lists; please open an issue.");
3868
3967
  state.dataArea.set(requestBytes, 0);
3869
3968
  state.lengthView.setUint32(0, requestBytes.length);
3870
3969
  Atomics.store(state.controlArray, 0, 1);
3871
3970
  Atomics.notify(state.controlArray, 0);
3872
- if (Atomics.wait(state.controlArray, 1, 0, REQUEST_TIMEOUT) === "timed-out") {
3873
- this.dropWorker(cssPath);
3874
- throw 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.");
3875
- }
3971
+ if (Atomics.wait(state.controlArray, 1, 0, this.requestTimeoutMs) === "timed-out") throw this.failRequest(cssPath, new SortServiceError(`${this.opts.serviceName} worker request timed out after ${this.requestTimeoutMs}ms.`, "A slow machine or CI runner can cause this. If the class lists are valid, raise OXLINT_TAILWINDCSS_WORKER_REQUEST_TIMEOUT; otherwise please open an issue."));
3876
3972
  const responseLen = state.lengthView.getUint32(0);
3877
3973
  const responseStr = Buffer.from(state.dataArea.slice(0, responseLen)).toString("utf-8");
3878
3974
  Atomics.store(state.controlArray, 1, 0);
@@ -3880,19 +3976,19 @@ var DesignSystemWorker = class {
3880
3976
  try {
3881
3977
  parsed = JSON.parse(responseStr);
3882
3978
  } catch (cause) {
3883
- this.dropWorker(cssPath);
3884
- throw 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 });
3885
- }
3886
- if (parsed === null) {
3887
- this.dropWorker(cssPath);
3888
- throw 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.");
3979
+ throw this.failRequest(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 }));
3889
3980
  }
3981
+ if (parsed === null) throw this.failRequest(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."));
3982
+ this.requestFailCount.delete(cssPath);
3983
+ this.requestStick.delete(cssPath);
3890
3984
  return parsed;
3891
3985
  }
3892
3986
  reset() {
3893
3987
  for (const state of this.workers.values()) this.terminateWorker(state.worker);
3894
3988
  this.workers.clear();
3895
3989
  this.errors.clear();
3990
+ this.requestFailCount.clear();
3991
+ this.requestStick.clear();
3896
3992
  }
3897
3993
  /** Terminate and forget the worker for a single cssPath (on request failure). */
3898
3994
  dropWorker(cssPath) {
@@ -4852,7 +4948,7 @@ const noDeprecatedClasses = defineRule({
4852
4948
  return createExtractorVisitors(context, check);
4853
4949
  }
4854
4950
  });
4855
- const WORKER_SCRIPT = makeWorkerScript(`(ds, request) => {
4951
+ const WORKER_SCRIPT$1 = makeWorkerScript(`(ds, request) => {
4856
4952
  const { classes, rem } = request;
4857
4953
  const options = rem ? { rem } : undefined;
4858
4954
  const declsOf = (cls) => {
@@ -4885,7 +4981,7 @@ const WORKER_SCRIPT = makeWorkerScript(`(ds, request) => {
4885
4981
  });
4886
4982
  }`);
4887
4983
  const canonWorker = new DesignSystemWorker({
4888
- workerScript: WORKER_SCRIPT,
4984
+ workerScript: WORKER_SCRIPT$1,
4889
4985
  serviceName: "canonicalize"
4890
4986
  });
4891
4987
  /**
@@ -4919,7 +5015,7 @@ const canonCache = /* @__PURE__ */ new Map();
4919
5015
  * Best-effort everywhere: a missing/corrupt/unwritable cache file must never
4920
5016
  * break linting — it only costs worker round-trips.
4921
5017
  */
4922
- const CANON_LOGIC_HASH = (0, node_crypto.createHash)("md5").update(WORKER_SCRIPT + roundRemValue.toString()).digest("hex").slice(0, 8);
5018
+ const CANON_LOGIC_HASH = (0, node_crypto.createHash)("md5").update(WORKER_SCRIPT$1 + roundRemValue.toString()).digest("hex").slice(0, 8);
4923
5019
  let tmpSeq = 0;
4924
5020
  const LOCK_STALE_MS = 1e4;
4925
5021
  /** One persistence state per `${cssPath}\0${rem}\0` cache prefix. */
@@ -5283,7 +5379,7 @@ const enforceSortOrder = defineRule({
5283
5379
  groupClasses.length = 0;
5284
5380
  for (const [name] of ordered) groupClasses.push(name);
5285
5381
  }
5286
- const stripKey = (k) => cache.prefix && k.startsWith(cache.prefix + ":") ? k.slice(cache.prefix.length + 1) : k;
5382
+ const stripKey = (k) => stripProjectPrefix(k, cache.prefix).body;
5287
5383
  const sortedGroupKeys = [...groups.keys()].sort((ka, kb) => {
5288
5384
  const a = stripKey(ka);
5289
5385
  const b = stripKey(kb);
@@ -6793,12 +6889,7 @@ const consistentVariantOrder = defineRule({
6793
6889
  }
6794
6890
  function reorderClass(cls) {
6795
6891
  const { priorityOf, prefix, factsFor } = resolveForFile();
6796
- let pfx = "";
6797
- let body = cls;
6798
- if (prefix && cls.startsWith(prefix + ":")) {
6799
- pfx = prefix + ":";
6800
- body = cls.slice(prefix.length + 1);
6801
- }
6892
+ const { prefix: pfx, body } = stripProjectPrefix(cls, prefix);
6802
6893
  const variants = extractVariants(body);
6803
6894
  if (variants.length < 2) return null;
6804
6895
  const pseudo = [];
@@ -6879,6 +6970,7 @@ const consistentVariantOrder = defineRule({
6879
6970
  //#endregion
6880
6971
  //#region src/rules/enforce-consistent-line-wrapping.ts
6881
6972
  const DEFAULT_PRINT_WIDTH = 80;
6973
+ const DEFAULT_GROUP = "newLine";
6882
6974
  /** One indentation level added below the statement's base indent for wrapped lines. */
6883
6975
  const INDENT_UNIT = " ";
6884
6976
  /** Group `classes` into chunks of at most `n`, each chunk space-joined. */
@@ -6887,28 +6979,114 @@ function chunkList(classes, n) {
6887
6979
  for (let i = 0; i < classes.length; i += n) chunks.push(classes.slice(i, i + n).join(" "));
6888
6980
  return chunks;
6889
6981
  }
6982
+ /**
6983
+ * Greedily pack `classes` into space-joined lines: a line takes classes until
6984
+ * `indent` + the next one would exceed `width`; a single class over the
6985
+ * budget still gets its own line. Widths count characters, so a tab in
6986
+ * `indent` is 1 column (detection uses the same yardstick, so tabs converge).
6987
+ */
6988
+ function packToWidth(classes, indent, width) {
6989
+ const lines = [];
6990
+ let current = "";
6991
+ for (const cls of classes) {
6992
+ const candidate = current === "" ? cls : current + " " + cls;
6993
+ if (current !== "" && indent.length + candidate.length > width) {
6994
+ lines.push(current);
6995
+ current = cls;
6996
+ } else current = candidate;
6997
+ }
6998
+ if (current !== "") lines.push(current);
6999
+ return lines;
7000
+ }
7001
+ /**
7002
+ * Variant chain used as the grouping key. A Tailwind v4 project prefix
7003
+ * (`tw:`) is structurally a variant but pinned first, so it is stripped
7004
+ * before the key is computed — `tw:flex` keys as a base utility (grouping
7005
+ * with unprefixed component classes) and `tw:hover:x` keys as `hover:`,
7006
+ * matching how consistent-variant-order / enforce-sort-order treat the
7007
+ * prefix. Grouping only: emitted classes are never rewritten.
7008
+ */
7009
+ function groupingKey(cls, prefix) {
7010
+ return getVariantPrefix(stripProjectPrefix(cls, prefix).body);
7011
+ }
7012
+ /**
7013
+ * Split `classes` into runs of consecutive classes sharing the same variant
7014
+ * chain ("hover:", "md:hover:", "" for base utilities), so wrapping breaks
7015
+ * between variant groups rather than mid-group.
7016
+ */
7017
+ function groupByVariantRun(classes, prefix) {
7018
+ const groups = [];
7019
+ let current = [];
7020
+ let currentVariant = null;
7021
+ for (const cls of classes) {
7022
+ const variant = groupingKey(cls, prefix);
7023
+ if (currentVariant !== null && variant !== currentVariant) {
7024
+ groups.push(current);
7025
+ current = [];
7026
+ }
7027
+ currentVariant = variant;
7028
+ current.push(cls);
7029
+ }
7030
+ if (current.length > 0) groups.push(current);
7031
+ return groups;
7032
+ }
7033
+ /**
7034
+ * Pack `classes` per the `group` mode: 'never' packs greedily across
7035
+ * variant-run boundaries, 'newLine' starts each run on its own line(s), and
7036
+ * 'emptyLine' additionally inserts an extra line between runs — emitted as a
7037
+ * blank line with no indent.
7038
+ */
7039
+ function packGroupedToWidth(classes, indent, width, group, prefix) {
7040
+ if (group === "never") return packToWidth(classes, indent, width);
7041
+ const lines = [];
7042
+ for (const run of groupByVariantRun(classes, prefix)) {
7043
+ if (group === "emptyLine" && lines.length > 0) lines.push("");
7044
+ lines.push(...packToWidth(run, indent, width));
7045
+ }
7046
+ return lines;
7047
+ }
6890
7048
  const enforceConsistentLineWrapping = defineRule({
6891
7049
  meta: {
6892
7050
  type: "suggestion",
6893
- docs: { description: "Warn when a class string exceeds the configured print width" },
7051
+ docs: { description: "Warn (and optionally autofix) when a class string exceeds the configured print width or classes-per-line budget" },
6894
7052
  fixable: "whitespace",
6895
7053
  schema: [{
6896
7054
  type: "object",
6897
7055
  properties: {
7056
+ entryPoint: { type: "string" },
6898
7057
  printWidth: { type: "number" },
6899
- classesPerLine: { type: "number" }
7058
+ classesPerLine: { type: "number" },
7059
+ wrapLines: {
7060
+ type: "string",
7061
+ enum: ["overWidth", "all"]
7062
+ },
7063
+ group: {
7064
+ type: "string",
7065
+ enum: [
7066
+ "newLine",
7067
+ "emptyLine",
7068
+ "never"
7069
+ ]
7070
+ }
6900
7071
  },
6901
7072
  additionalProperties: false
6902
7073
  }],
6903
- defaultOptions: [{ printWidth: DEFAULT_PRINT_WIDTH }],
7074
+ defaultOptions: [{
7075
+ printWidth: DEFAULT_PRINT_WIDTH,
7076
+ group: DEFAULT_GROUP
7077
+ }],
6904
7078
  messages: {
6905
7079
  tooLong: "Class string exceeds the print width of {{printWidth}} (longest line is {{length}} characters). Consider splitting into multiple lines or extracting into a component.",
6906
- tooManyPerLine: "Too many classes on a single line ({{count}}). Maximum allowed per line is {{max}}."
7080
+ tooManyPerLine: "Too many classes on a single line ({{count}}). Maximum allowed per line is {{max}}.",
7081
+ inconsistentWrapping: "Class string is not wrapped consistently. Classes should be re-wrapped to the configured layout within the print width of {{printWidth}}."
6907
7082
  }
6908
7083
  },
6909
7084
  createOnce(context) {
6910
7085
  const getPrintWidth = createLazyOptions(context, (o) => o?.printWidth ?? DEFAULT_PRINT_WIDTH);
6911
7086
  const getClassesPerLine = createLazyOptions(context, (o) => o?.classesPerLine);
7087
+ const getWrapLines = createLazyOptions(context, (o) => o?.wrapLines);
7088
+ const getGroup = createLazyOptions(context, (o) => o?.group ?? DEFAULT_GROUP);
7089
+ const getDS = createLazyLoader(context);
6912
7090
  /**
6913
7091
  * The statement's real base indentation — the leading whitespace of the
6914
7092
  * source line the opening backtick sits on. NOT `node.loc.start.column`,
@@ -6918,7 +7096,7 @@ const enforceConsistentLineWrapping = defineRule({
6918
7096
  */
6919
7097
  function deriveBaseIndent(loc) {
6920
7098
  const sc = safeSourceCode(context);
6921
- const line = loc.node.loc?.start.line;
7099
+ const line = loc.templateLine ?? loc.node.loc?.start.line;
6922
7100
  if (sc?.lines && typeof line === "number" && line >= 1 && line <= sc.lines.length) {
6923
7101
  const src = sc.lines[line - 1] ?? "";
6924
7102
  const m = /^[ \t]*/.exec(src);
@@ -6951,19 +7129,93 @@ const enforceConsistentLineWrapping = defineRule({
6951
7129
  return chunkList(classes, classesPerLine).map((c) => lineIndent + c).join("\n");
6952
7130
  }).join("\n");
6953
7131
  }
7132
+ /**
7133
+ * `wrapLines: 'all'` fixer (also the single-line conversion for
7134
+ * 'overWidth', which passes `group: 'never'`): the WHOLE quasi is
7135
+ * re-laid-out into `printWidth`-packed lines per the `group` mode, in the
7136
+ * BLOCK form regardless of position — every class run lands on its own
7137
+ * indented line below the backtick.
7138
+ *
7139
+ * A quasi that follows a `${}` (`preserveLeadingSpace`) starts on its own
7140
+ * fresh interior-indented line rather than hanging inline after the
7141
+ * interpolation, and a `${}` that follows the quasi
7142
+ * (`preserveTrailingSpace`) lands alone on the closing interior-indented
7143
+ * line. So no emitted line ever shares its physical row with the opaque
7144
+ * `${expr}`, and every line stays within `printWidth` — bounding the
7145
+ * hanging-join over-width case that per-quasi measurement cannot re-detect.
7146
+ *
7147
+ * The returned value BEGINS with `\n` and ENDS with indentation, so the
7148
+ * newlines already separate it from any bordering `${}`: it must NOT be run
7149
+ * through `preserveSpaces`, which would prepend a stray space before the
7150
+ * leading `\n`.
7151
+ */
7152
+ function rewrapTemplateToWidth(loc, printWidth, group, prefix) {
7153
+ const baseIndent = deriveBaseIndent(loc);
7154
+ const interiorIndent = baseIndent + INDENT_UNIT;
7155
+ const classes = splitClasses(loc.value);
7156
+ if (classes.length === 0) return loc.value;
7157
+ const packed = packGroupedToWidth(classes, interiorIndent, printWidth, group, prefix);
7158
+ const close = loc.preserveTrailingSpace ? interiorIndent : baseIndent;
7159
+ return "\n" + packed.map((c) => c === "" ? c : interiorIndent + c).join("\n") + "\n" + close;
7160
+ }
7161
+ /**
7162
+ * `wrapLines: 'overWidth'` fixer: non-destructive like `rewrapTemplate`
7163
+ * — only lines exceeding `printWidth` are greedily re-packed, each
7164
+ * keeping its own indent; conforming lines are left verbatim. A
7165
+ * single-line value has no layout to preserve and converts to the block
7166
+ * form. Returns the FINAL value, `${}` boundary spaces included — never
7167
+ * run it through `preserveSpaces`, which would prepend a stray space to
7168
+ * a quasi that legitimately starts with `\n`.
7169
+ */
7170
+ function rewrapOverBudgetLinesToWidth(loc, printWidth) {
7171
+ const lines = loc.value.split("\n");
7172
+ if (lines.length === 1) return rewrapTemplateToWidth(loc, printWidth, "never", "");
7173
+ const interiorIndent = deriveBaseIndent(loc) + INDENT_UNIT;
7174
+ const width = printWidth - (loc.preserveTrailingSpace ? 1 : 0);
7175
+ const fixed = lines.map((line) => {
7176
+ const classes = splitClasses(line);
7177
+ if (line.length <= printWidth || classes.length <= 1) return line;
7178
+ const m = /^[ \t]*/.exec(line);
7179
+ const lead = m ? m[0] : "";
7180
+ const contIndent = lead.length > 0 ? lead : interiorIndent;
7181
+ return packToWidth(classes, contIndent, width).map((c, i) => i === 0 ? lead + c : contIndent + c).join("\n");
7182
+ }).join("\n");
7183
+ if (loc.preserveTrailingSpace && !/\s$/.test(fixed)) return fixed + " ";
7184
+ return fixed;
7185
+ }
6954
7186
  function check(locations) {
6955
7187
  const printWidth = getPrintWidth();
6956
7188
  const classesPerLine = getClassesPerLine();
7189
+ const wrapLines = getWrapLines();
7190
+ const group = getGroup();
7191
+ const prefix = wrapLines === "all" && group !== "never" && classesPerLine === void 0 ? softGetDS(getDS)?.cache.prefix ?? "" : "";
6957
7192
  for (const loc of locations) {
6958
7193
  let maxLine = 0;
6959
- for (const line of loc.value.split("\n")) if (line.length > maxLine) maxLine = line.length;
6960
- if (maxLine > printWidth) context.report({
7194
+ for (const line of loc.value.split("\n")) {
7195
+ if (line.length <= maxLine) continue;
7196
+ if (line.length > printWidth && splitClasses(line).length <= 1) continue;
7197
+ maxLine = line.length;
7198
+ }
7199
+ const data = {
7200
+ length: String(maxLine),
7201
+ printWidth: String(printWidth)
7202
+ };
7203
+ const isMultiline = loc.value.includes("\n");
7204
+ const glued = loc.preserveLeadingSpace === true && !/^\s/.test(loc.value) || loc.preserveTrailingSpace === true && !/\s$/.test(loc.value);
7205
+ if (wrapLines !== void 0 && classesPerLine === void 0 && loc.node.type === "TemplateElement" && !glued && (maxLine > printWidth || wrapLines === "all" && isMultiline)) {
7206
+ const fixedValue = wrapLines === "all" ? rewrapTemplateToWidth(loc, printWidth, group, prefix) : rewrapOverBudgetLinesToWidth(loc, printWidth);
7207
+ if (fixedValue !== loc.value) context.report({
7208
+ node: loc.node,
7209
+ messageId: maxLine > printWidth ? "tooLong" : "inconsistentWrapping",
7210
+ data,
7211
+ fix(fixer) {
7212
+ return fixer.replaceTextRange(loc.range, fixedValue);
7213
+ }
7214
+ });
7215
+ } else if (maxLine > printWidth) context.report({
6961
7216
  node: loc.node,
6962
7217
  messageId: "tooLong",
6963
- data: {
6964
- length: String(maxLine),
6965
- printWidth: String(printWidth)
6966
- }
7218
+ data
6967
7219
  });
6968
7220
  if (classesPerLine !== void 0) {
6969
7221
  const lines = loc.value.split("\n");
@@ -6977,7 +7229,7 @@ const enforceConsistentLineWrapping = defineRule({
6977
7229
  count: String(maxPerLine),
6978
7230
  max: String(classesPerLine)
6979
7231
  };
6980
- if (loc.node.type === "TemplateElement") {
7232
+ if (loc.node.type === "TemplateElement" && !glued) {
6981
7233
  const fixedValue = rewrapTemplate(loc, lines, classesPerLine);
6982
7234
  context.report({
6983
7235
  node: loc.node,