oxlint-tailwindcss 1.10.1 → 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/dist/index.mjs CHANGED
@@ -7,7 +7,7 @@ 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.80.0/node_modules/@oxlint/plugins/index.js
10
+ //#region ../../node_modules/.pnpm/@oxlint+plugins@1.82.0/node_modules/@oxlint/plugins/index.js
11
11
  /**
12
12
  * Define a plugin.
13
13
  *
@@ -119,6 +119,7 @@ function preserveSpaces(loc, fixed) {
119
119
  }
120
120
  const DEFAULT_EXTRACTOR_CONFIG = {
121
121
  attributes: ["className", "class"],
122
+ attributePatterns: [],
122
123
  callees: [
123
124
  "cn",
124
125
  "clsx",
@@ -182,6 +183,7 @@ function getExtractorConfig(context) {
182
183
  const filteredPatterns = excludedPatternSources.size > 0 ? DEFAULT_EXTRACTOR_CONFIG.variablePatterns.filter((re) => !excludedPatternSources.has(re.source)) : DEFAULT_EXTRACTOR_CONFIG.variablePatterns;
183
184
  const resolved = {
184
185
  attributes: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.attributes, tw.attributes, exclude?.attributes),
186
+ attributePatterns: compileRegexList(tw.attributePatterns),
185
187
  callees: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.callees, tw.callees, exclude?.callees),
186
188
  tags: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.tags, tw.tags, exclude?.tags),
187
189
  variablePatterns: [...filteredPatterns, ...compileRegexList(tw.variablePatterns)]
@@ -241,7 +243,7 @@ function jsxHostOrigin(node) {
241
243
  */
242
244
  function extractFromJSXAttribute(node, config = DEFAULT_EXTRACTOR_CONFIG) {
243
245
  const name = node.name.type === "JSXIdentifier" ? node.name.name : void 0;
244
- if (!name || !config.attributes.includes(name)) return [];
246
+ if (!name || !config.attributes.includes(name) && !config.attributePatterns.some((p) => p.test(name))) return [];
245
247
  if (!node.value) return [];
246
248
  const hostOrigin = jsxHostOrigin(node);
247
249
  if (node.value.type === "Literal" && typeof node.value.value === "string") return [{
@@ -465,7 +467,8 @@ function appendFromTemplateLiteral(node, out) {
465
467
  node: quasi,
466
468
  range: [start, start + value.length],
467
469
  preserveLeadingSpace: i > 0,
468
- preserveTrailingSpace: i < node.quasis.length - 1
470
+ preserveTrailingSpace: i < node.quasis.length - 1,
471
+ templateLine: node.loc?.start.line
469
472
  });
470
473
  }
471
474
  }
@@ -796,6 +799,26 @@ function splitUtilityAndVariant(cls) {
796
799
  };
797
800
  }
798
801
  /**
802
+ * Strips a Tailwind v4 project prefix (`@import "tailwindcss" prefix(tw)` → `tw`)
803
+ * off a class, returning the matched prefix marker (`"tw:"`, or `""`) and the
804
+ * remaining body. The project prefix is structurally a variant but pinned FIRST
805
+ * (`tw:hover:flex`, never `hover:tw:flex`), so grouping/ordering rules strip it
806
+ * before reading the real variant chain — the prefix invariant shared by
807
+ * enforce-sort-order, consistent-variant-order and enforce-consistent-line-wrapping.
808
+ * `prefix === ""` (no project prefix / no design system) or a non-matching class
809
+ * passes through untouched.
810
+ */
811
+ function stripProjectPrefix(cls, prefix) {
812
+ if (prefix !== "" && cls.startsWith(prefix + ":")) return {
813
+ prefix: prefix + ":",
814
+ body: cls.slice(prefix.length + 1)
815
+ };
816
+ return {
817
+ prefix: "",
818
+ body: cls
819
+ };
820
+ }
821
+ /**
799
822
  * Checks if a class has an arbitrary value (bracket syntax in the utility part).
800
823
  * Distinguishes from arbitrary variants: [&>svg]:w-4 does NOT have an arbitrary value,
801
824
  * but w-[200px] does.
@@ -2773,7 +2796,30 @@ function cacheDirName() {
2773
2796
  return "oxlint-tailwindcss";
2774
2797
  }
2775
2798
  }
2776
- const CACHE_DIR = join(tmpdir(), cacheDirName());
2799
+ /**
2800
+ * The disk-cache directory.
2801
+ *
2802
+ * Defaults to a per-uid dir under the system temp dir (see `cacheDirName`), but
2803
+ * honours `OXLINT_TAILWINDCSS_CACHE_DIR` when set to a non-empty value. Two uses:
2804
+ * - CI / sandboxed builds that want the cache at a controlled, pruneable
2805
+ * location instead of the shared system temp dir.
2806
+ * - The test suite, which points each `pnpm test` invocation at its OWN dir
2807
+ * (`vitest.config.ts`) so two concurrent runs — a background run and the
2808
+ * stop-hook's run, or a dev's editor running oxlint alongside the tests —
2809
+ * never share cache files and race on them (the source of the
2810
+ * `canonicalize-persistence` EISDIR / stale-read flakes).
2811
+ *
2812
+ * The dir the plugin creates is still `mode 0o700` (see `computeWithLock`), so
2813
+ * an override the plugin creates stays private to its owner; pointing the
2814
+ * override at a pre-existing world-writable dir re-opens the poisoning vector
2815
+ * `cacheDirName` closes, so that is the caller's responsibility.
2816
+ */
2817
+ function resolveCacheDir() {
2818
+ const override = process.env.OXLINT_TAILWINDCSS_CACHE_DIR;
2819
+ if (typeof override === "string" && override.trim() !== "") return override.trim();
2820
+ return join(tmpdir(), cacheDirName());
2821
+ }
2822
+ const CACHE_DIR = resolveCacheDir();
2777
2823
  /** md5 of the precompute script (no version) — the version is folded in per entry point. */
2778
2824
  const SCRIPT_HASH = createHash("md5").update(PRECOMPUTE_SCRIPT).digest("hex").slice(0, 8);
2779
2825
  /**
@@ -2916,7 +2962,7 @@ function reclaimStaleLock$1(lockPath) {
2916
2962
  }
2917
2963
  /** control[2] — the worker's ready/done signal (0=loading, 1=done, -1=error). */
2918
2964
  const PRECOMPUTE_SIGNAL_INDEX = 2;
2919
- const ERR_BUFFER_SIZE = 64 * 1024;
2965
+ const ERR_BUFFER_SIZE = 65536;
2920
2966
  let precomputeSeq = 0;
2921
2967
  /**
2922
2968
  * Choose the diagnostic hint based on the underlying error code. ENOMEM/EAGAIN
@@ -3685,17 +3731,38 @@ function resolveEntryPointForFile(ruleOptionEntry, settingsEntry, filePath, cwd
3685
3731
  * — SharedArrayBuffer layout, state machine, lifecycle, fail-loud — and each
3686
3732
  * service shrinks to ~40 LOC of singleton + public signature.
3687
3733
  *
3688
- * v1: failures throw `SortServiceError`. The error is sticky for the lifetime
3689
- * of the process (per cssPath) so subsequent calls don't pay another
3690
- * init-timeout cost. Callers wrap via `safeGetDS` to surface the failure as a
3691
- * single `designSystemUnavailable` diagnostic.
3692
- */
3693
- const BUFFER_SIZE = 4 * 1024 * 1024;
3734
+ * v1: failures throw `SortServiceError`. Init/spawn/crash/DS-load failures are
3735
+ * HARD sticky per cssPath for the process lifetime, so subsequent calls don't
3736
+ * pay another init-timeout cost. Per-request failures (timeout / non-JSON /
3737
+ * null) are SOFT sticky (#145): unbounded retrying re-pays the full request
3738
+ * timeout on every class list (O(files)), so after a few consecutive failures
3739
+ * the error goes sticky for a backoff window and the rest of the run fails fast;
3740
+ * any success clears it. Callers wrap via `safeGetDS` to surface the failure as
3741
+ * a single `designSystemUnavailable` diagnostic.
3742
+ */
3743
+ const BUFFER_SIZE = 4194304;
3694
3744
  const HEADER_INTS = 4;
3695
- const LENGTH_OFFSET = HEADER_INTS * 4;
3745
+ const LENGTH_OFFSET = 16;
3696
3746
  const DATA_OFFSET = 20;
3697
3747
  const INIT_TIMEOUT = 6e4;
3698
3748
  const REQUEST_TIMEOUT = 3e4;
3749
+ const MAX_CONSECUTIVE_REQUEST_FAILURES = 3;
3750
+ const REQUEST_STICKY_BACKOFF_MS = 6e4;
3751
+ /**
3752
+ * Per-request timeout override for slow-but-functional machines (#145). A
3753
+ * machine whose cold canonicalize sits close to the 30 s default times out
3754
+ * spuriously; raising this lets the request COMPLETE (the rule keeps working)
3755
+ * rather than only failing fast. An env var — not a `settings.tailwindcss` key —
3756
+ * keeps the documented invariant that worker services don't read
3757
+ * `settings.tailwindcss.timeout`, and sidesteps the settings-timing problem
3758
+ * (settings throw inside `createOnce`). Read once per worker construction.
3759
+ */
3760
+ function envRequestTimeout() {
3761
+ const raw = process.env.OXLINT_TAILWINDCSS_WORKER_REQUEST_TIMEOUT;
3762
+ if (raw === void 0 || raw === "") return void 0;
3763
+ const n = Number(raw);
3764
+ return Number.isFinite(n) && n > 0 ? n : void 0;
3765
+ }
3699
3766
  const MAX_WORKERS = 8;
3700
3767
  /**
3701
3768
  * Build the worker script shared by `sort-service` and `canonicalize-service`.
@@ -3782,15 +3849,41 @@ var DesignSystemWorker = class {
3782
3849
  opts;
3783
3850
  workers = /* @__PURE__ */ new Map();
3784
3851
  errors = /* @__PURE__ */ new Map();
3852
+ requestFailCount = /* @__PURE__ */ new Map();
3853
+ requestStick = /* @__PURE__ */ new Map();
3854
+ /** Resolved per-request timeout (option > env var > REQUEST_TIMEOUT). */
3855
+ requestTimeoutMs;
3856
+ /** Resolved consecutive-failure budget before a per-request error goes soft-sticky. */
3857
+ maxConsecutiveRequestFailures;
3785
3858
  constructor(opts) {
3786
3859
  this.opts = opts;
3860
+ this.requestTimeoutMs = opts.requestTimeoutMs ?? envRequestTimeout() ?? REQUEST_TIMEOUT;
3861
+ this.maxConsecutiveRequestFailures = opts.maxConsecutiveRequestFailures ?? MAX_CONSECUTIVE_REQUEST_FAILURES;
3787
3862
  }
3788
- /** Record an error as sticky for `cssPath` and return it for `throw`. */
3863
+ /** Record an error as HARD sticky for `cssPath` and return it for `throw`. */
3789
3864
  remember(cssPath, err) {
3790
3865
  this.errors.set(cssPath, err);
3791
3866
  return err;
3792
3867
  }
3793
3868
  /**
3869
+ * Handle a per-request (SOFT) failure (#145): drop the worker so the next call
3870
+ * re-spawns, count consecutive failures for this cssPath, and once the budget
3871
+ * is spent record a soft sticky good for a backoff window so the rest of the
3872
+ * run fails fast instead of re-paying the timeout per class list. A later
3873
+ * success (see `callSync`) clears the count and the soft sticky. Returns the
3874
+ * error for `throw` (mirrors `remember`).
3875
+ */
3876
+ failRequest(cssPath, err) {
3877
+ this.dropWorker(cssPath);
3878
+ const count = (this.requestFailCount.get(cssPath) ?? 0) + 1;
3879
+ this.requestFailCount.set(cssPath, count);
3880
+ if (count >= this.maxConsecutiveRequestFailures) this.requestStick.set(cssPath, {
3881
+ err,
3882
+ until: Date.now() + REQUEST_STICKY_BACKOFF_MS
3883
+ });
3884
+ return err;
3885
+ }
3886
+ /**
3794
3887
  * Ensure the worker is running and pointed at `cssPath`. Returns the
3795
3888
  * ready state. Throws `SortServiceError` on any failure (init timeout,
3796
3889
  * spawn error, DS-load error). Sticky: subsequent calls for the same
@@ -3799,6 +3892,12 @@ var DesignSystemWorker = class {
3799
3892
  ensure(cssPath) {
3800
3893
  const sticky = this.errors.get(cssPath);
3801
3894
  if (sticky) throw sticky;
3895
+ const soft = this.requestStick.get(cssPath);
3896
+ if (soft) {
3897
+ if (Date.now() < soft.until) throw soft.err;
3898
+ this.requestStick.delete(cssPath);
3899
+ this.requestFailCount.delete(cssPath);
3900
+ }
3802
3901
  const existing = this.workers.get(cssPath);
3803
3902
  if (existing) {
3804
3903
  this.workers.delete(cssPath);
@@ -3809,7 +3908,7 @@ var DesignSystemWorker = class {
3809
3908
  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."));
3810
3909
  const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
3811
3910
  const controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
3812
- const lengthView = new DataView(sharedBuffer, HEADER_INTS * 4, 4);
3911
+ const lengthView = new DataView(sharedBuffer, 16, 4);
3813
3912
  const dataArea = new Uint8Array(sharedBuffer, DATA_OFFSET);
3814
3913
  let worker;
3815
3914
  try {
@@ -3868,15 +3967,12 @@ var DesignSystemWorker = class {
3868
3967
  callSync(cssPath, req) {
3869
3968
  const state = this.ensure(cssPath);
3870
3969
  const requestBytes = Buffer.from(JSON.stringify(req), "utf-8");
3871
- 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.");
3970
+ 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.");
3872
3971
  state.dataArea.set(requestBytes, 0);
3873
3972
  state.lengthView.setUint32(0, requestBytes.length);
3874
3973
  Atomics.store(state.controlArray, 0, 1);
3875
3974
  Atomics.notify(state.controlArray, 0);
3876
- if (Atomics.wait(state.controlArray, 1, 0, REQUEST_TIMEOUT) === "timed-out") {
3877
- this.dropWorker(cssPath);
3878
- throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker request timed out after ${REQUEST_TIMEOUT}ms.`, "This is unexpected for typical class lists; please open an issue if it persists."));
3879
- }
3975
+ 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."));
3880
3976
  const responseLen = state.lengthView.getUint32(0);
3881
3977
  const responseStr = Buffer.from(state.dataArea.slice(0, responseLen)).toString("utf-8");
3882
3978
  Atomics.store(state.controlArray, 1, 0);
@@ -3884,19 +3980,19 @@ var DesignSystemWorker = class {
3884
3980
  try {
3885
3981
  parsed = JSON.parse(responseStr);
3886
3982
  } catch (cause) {
3887
- this.dropWorker(cssPath);
3888
- throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker returned non-JSON response.`, "This is a bug; please open an issue.", { cause: cause instanceof Error ? cause : void 0 }));
3889
- }
3890
- if (parsed === null) {
3891
- this.dropWorker(cssPath);
3892
- throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker returned null — the request body was rejected or its response did not fit the buffer.`, "This is a bug; please open an issue with the input that triggered it."));
3983
+ 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 }));
3893
3984
  }
3985
+ 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."));
3986
+ this.requestFailCount.delete(cssPath);
3987
+ this.requestStick.delete(cssPath);
3894
3988
  return parsed;
3895
3989
  }
3896
3990
  reset() {
3897
3991
  for (const state of this.workers.values()) this.terminateWorker(state.worker);
3898
3992
  this.workers.clear();
3899
3993
  this.errors.clear();
3994
+ this.requestFailCount.clear();
3995
+ this.requestStick.clear();
3900
3996
  }
3901
3997
  /** Terminate and forget the worker for a single cssPath (on request failure). */
3902
3998
  dropWorker(cssPath) {
@@ -3913,8 +4009,6 @@ var DesignSystemWorker = class {
3913
4009
  } catch {}
3914
4010
  }
3915
4011
  };
3916
- //#endregion
3917
- //#region src/design-system/declaration-service.ts
3918
4012
  const declWorker = new DesignSystemWorker({
3919
4013
  workerScript: makeWorkerScript(`(ds, request) => {
3920
4014
  const decls = {};
@@ -3928,14 +4022,28 @@ const declWorker = new DesignSystemWorker({
3928
4022
  // so every user-written value went silently uncompared.
3929
4023
  const prefix = (ds.theme && ds.theme.prefix) || '';
3930
4024
  const pfx = (c) => (prefix && !c.startsWith(prefix + ':')) ? prefix + ':' + c : c;
3931
- const css = ds.candidatesToCss(request.classes.map(pfx));
4025
+ // Resolve one class at a time rather than a single batch call: a malformed/
4026
+ // mid-typing arbitrary value can make ds.candidatesToCss throw on some engine
4027
+ // versions (#130), and a batched throw blanked the whole request AND masked
4028
+ // real typos (a valid sibling like \`bg-red-5000\` went unflagged), then became
4029
+ // the worker's 'null' sentinel → a process-sticky fatal error. Per-class,
4030
+ // distinguish a THROW (incanonicalizable input → OMIT, so no-unknown-classes
4031
+ // stays lenient instead of flagging a transient false "unknown class") from a
4032
+ // FALSY result (compiles to nothing → invalid).
3932
4033
  for (let i = 0; i < request.classes.length; i++) {
3933
- if (!css[i]) { invalid.push(request.classes[i]); continue; }
3934
4034
  const cls = request.classes[i];
4035
+ let one;
4036
+ try {
4037
+ const out = ds.candidatesToCss([pfx(cls)]);
4038
+ one = out && out[0];
4039
+ } catch (e) {
4040
+ continue; // omit: neither decls nor invalid
4041
+ }
4042
+ if (!one) { invalid.push(cls); continue; }
3935
4043
  const list = [];
3936
4044
  // The selector carries the prefix, so the scope classifier needs the
3937
4045
  // prefixed name even though the result is keyed by the bare one.
3938
- walkDeclarations(css[i], pfx(cls), (scope, prop, value) => {
4046
+ walkDeclarations(one, pfx(cls), (scope, prop, value) => {
3939
4047
  list.push([scope, prop, value]);
3940
4048
  if (!(value in values)) {
3941
4049
  const reads = scanVarReads(value);
@@ -4844,24 +4952,7 @@ const noDeprecatedClasses = defineRule({
4844
4952
  return createExtractorVisitors(context, check);
4845
4953
  }
4846
4954
  });
4847
- //#endregion
4848
- //#region src/design-system/canonicalize-service.ts
4849
- /**
4850
- * Persistent canonicalize service backed by `DesignSystemWorker`.
4851
- *
4852
- * Calls `ds.canonicalizeCandidates([cls], { rem })` one class at a time
4853
- * (the design system deduplicates its input, so batching changes the
4854
- * result shape — see sync-loader.ts). The shared protocol lives in
4855
- * `./ds-worker.ts`.
4856
- *
4857
- * ## Per-class cache (process-wide)
4858
- *
4859
- * Results are cached by `${cssPath}\0${rem}\0${class}`. The worker is
4860
- * invoked only for cache misses. In practice the cache converges quickly —
4861
- * after the first few files any given class has been seen, and every
4862
- * subsequent lookup is O(1).
4863
- */
4864
- const WORKER_SCRIPT = makeWorkerScript(`(ds, request) => {
4955
+ const WORKER_SCRIPT$1 = makeWorkerScript(`(ds, request) => {
4865
4956
  const { classes, rem } = request;
4866
4957
  const options = rem ? { rem } : undefined;
4867
4958
  const declsOf = (cls) => {
@@ -4875,7 +4966,17 @@ const WORKER_SCRIPT = makeWorkerScript(`(ds, request) => {
4875
4966
  return css.slice(open + 1, close).replace(/\\s+/g, ' ').trim();
4876
4967
  };
4877
4968
  return classes.map((cls) => {
4878
- const r = ds.canonicalizeCandidates([cls], options);
4969
+ // A malformed/mid-typing arbitrary value (e.g. \`px-[calc(var(--a)+)]\`) can
4970
+ // make the Tailwind parser throw on some engine versions (#130). Treat it
4971
+ // as an incanonicalizable no-op — same posture declsOf already takes for
4972
+ // candidatesToCss — instead of letting the throw become the worker's 'null'
4973
+ // sentinel, which the host used to turn into a process-sticky fatal error.
4974
+ let r;
4975
+ try {
4976
+ r = ds.canonicalizeCandidates([cls], options);
4977
+ } catch (e) {
4978
+ return { canonical: cls, safe: true };
4979
+ }
4879
4980
  const canonical = r[0] ?? cls;
4880
4981
  if (canonical === cls) return { canonical: cls, safe: true };
4881
4982
  const a = declsOf(cls);
@@ -4884,7 +4985,7 @@ const WORKER_SCRIPT = makeWorkerScript(`(ds, request) => {
4884
4985
  });
4885
4986
  }`);
4886
4987
  const canonWorker = new DesignSystemWorker({
4887
- workerScript: WORKER_SCRIPT,
4988
+ workerScript: WORKER_SCRIPT$1,
4888
4989
  serviceName: "canonicalize"
4889
4990
  });
4890
4991
  /**
@@ -4918,7 +5019,7 @@ const canonCache = /* @__PURE__ */ new Map();
4918
5019
  * Best-effort everywhere: a missing/corrupt/unwritable cache file must never
4919
5020
  * break linting — it only costs worker round-trips.
4920
5021
  */
4921
- const CANON_LOGIC_HASH = createHash("md5").update(WORKER_SCRIPT + roundRemValue.toString()).digest("hex").slice(0, 8);
5022
+ const CANON_LOGIC_HASH = createHash("md5").update(WORKER_SCRIPT$1 + roundRemValue.toString()).digest("hex").slice(0, 8);
4922
5023
  let tmpSeq = 0;
4923
5024
  const LOCK_STALE_MS = 1e4;
4924
5025
  /** One persistence state per `${cssPath}\0${rem}\0` cache prefix. */
@@ -5191,18 +5292,19 @@ const enforceCanonical = defineRule({
5191
5292
  return createExtractorVisitors(context, check);
5192
5293
  }
5193
5294
  });
5194
- //#endregion
5195
- //#region src/design-system/sort-service.ts
5196
- /**
5197
- * Persistent sort service backed by `DesignSystemWorker`.
5198
- *
5199
- * Calls `ds.getClassOrder(classes)` and returns the class names in the
5200
- * Tailwind-canonical order. The shared protocol (SharedArrayBuffer,
5201
- * Atomics.wait, fail-loud, sticky lastError) lives in `./ds-worker.ts`.
5202
- */
5203
5295
  const sortWorker = new DesignSystemWorker({
5204
5296
  workerScript: makeWorkerScript(`(ds, classes) => {
5205
- const ordered = ds.getClassOrder(classes);
5297
+ // A malformed/mid-typing arbitrary value can make ds.getClassOrder throw on
5298
+ // some engine versions (#130). Degrade to the input order (no reordering):
5299
+ // the rule reads an unchanged order as "already sorted" and emits nothing,
5300
+ // instead of the throw becoming the worker's 'null' sentinel → a
5301
+ // process-sticky fatal error that disabled the rule until restart.
5302
+ let ordered;
5303
+ try {
5304
+ ordered = ds.getClassOrder(classes);
5305
+ } catch (e) {
5306
+ return classes;
5307
+ }
5206
5308
  return [...ordered]
5207
5309
  .sort((a, b) => {
5208
5310
  if (a[1] === null && b[1] === null) return 0;
@@ -5281,7 +5383,7 @@ const enforceSortOrder = defineRule({
5281
5383
  groupClasses.length = 0;
5282
5384
  for (const [name] of ordered) groupClasses.push(name);
5283
5385
  }
5284
- const stripKey = (k) => cache.prefix && k.startsWith(cache.prefix + ":") ? k.slice(cache.prefix.length + 1) : k;
5386
+ const stripKey = (k) => stripProjectPrefix(k, cache.prefix).body;
5285
5387
  const sortedGroupKeys = [...groups.keys()].sort((ka, kb) => {
5286
5388
  const a = stripKey(ka);
5287
5389
  const b = stripKey(kb);
@@ -6791,12 +6893,7 @@ const consistentVariantOrder = defineRule({
6791
6893
  }
6792
6894
  function reorderClass(cls) {
6793
6895
  const { priorityOf, prefix, factsFor } = resolveForFile();
6794
- let pfx = "";
6795
- let body = cls;
6796
- if (prefix && cls.startsWith(prefix + ":")) {
6797
- pfx = prefix + ":";
6798
- body = cls.slice(prefix.length + 1);
6799
- }
6896
+ const { prefix: pfx, body } = stripProjectPrefix(cls, prefix);
6800
6897
  const variants = extractVariants(body);
6801
6898
  if (variants.length < 2) return null;
6802
6899
  const pseudo = [];
@@ -6877,6 +6974,7 @@ const consistentVariantOrder = defineRule({
6877
6974
  //#endregion
6878
6975
  //#region src/rules/enforce-consistent-line-wrapping.ts
6879
6976
  const DEFAULT_PRINT_WIDTH = 80;
6977
+ const DEFAULT_GROUP = "newLine";
6880
6978
  /** One indentation level added below the statement's base indent for wrapped lines. */
6881
6979
  const INDENT_UNIT = " ";
6882
6980
  /** Group `classes` into chunks of at most `n`, each chunk space-joined. */
@@ -6885,28 +6983,114 @@ function chunkList(classes, n) {
6885
6983
  for (let i = 0; i < classes.length; i += n) chunks.push(classes.slice(i, i + n).join(" "));
6886
6984
  return chunks;
6887
6985
  }
6986
+ /**
6987
+ * Greedily pack `classes` into space-joined lines: a line takes classes until
6988
+ * `indent` + the next one would exceed `width`; a single class over the
6989
+ * budget still gets its own line. Widths count characters, so a tab in
6990
+ * `indent` is 1 column (detection uses the same yardstick, so tabs converge).
6991
+ */
6992
+ function packToWidth(classes, indent, width) {
6993
+ const lines = [];
6994
+ let current = "";
6995
+ for (const cls of classes) {
6996
+ const candidate = current === "" ? cls : current + " " + cls;
6997
+ if (current !== "" && indent.length + candidate.length > width) {
6998
+ lines.push(current);
6999
+ current = cls;
7000
+ } else current = candidate;
7001
+ }
7002
+ if (current !== "") lines.push(current);
7003
+ return lines;
7004
+ }
7005
+ /**
7006
+ * Variant chain used as the grouping key. A Tailwind v4 project prefix
7007
+ * (`tw:`) is structurally a variant but pinned first, so it is stripped
7008
+ * before the key is computed — `tw:flex` keys as a base utility (grouping
7009
+ * with unprefixed component classes) and `tw:hover:x` keys as `hover:`,
7010
+ * matching how consistent-variant-order / enforce-sort-order treat the
7011
+ * prefix. Grouping only: emitted classes are never rewritten.
7012
+ */
7013
+ function groupingKey(cls, prefix) {
7014
+ return getVariantPrefix(stripProjectPrefix(cls, prefix).body);
7015
+ }
7016
+ /**
7017
+ * Split `classes` into runs of consecutive classes sharing the same variant
7018
+ * chain ("hover:", "md:hover:", "" for base utilities), so wrapping breaks
7019
+ * between variant groups rather than mid-group.
7020
+ */
7021
+ function groupByVariantRun(classes, prefix) {
7022
+ const groups = [];
7023
+ let current = [];
7024
+ let currentVariant = null;
7025
+ for (const cls of classes) {
7026
+ const variant = groupingKey(cls, prefix);
7027
+ if (currentVariant !== null && variant !== currentVariant) {
7028
+ groups.push(current);
7029
+ current = [];
7030
+ }
7031
+ currentVariant = variant;
7032
+ current.push(cls);
7033
+ }
7034
+ if (current.length > 0) groups.push(current);
7035
+ return groups;
7036
+ }
7037
+ /**
7038
+ * Pack `classes` per the `group` mode: 'never' packs greedily across
7039
+ * variant-run boundaries, 'newLine' starts each run on its own line(s), and
7040
+ * 'emptyLine' additionally inserts an extra line between runs — emitted as a
7041
+ * blank line with no indent.
7042
+ */
7043
+ function packGroupedToWidth(classes, indent, width, group, prefix) {
7044
+ if (group === "never") return packToWidth(classes, indent, width);
7045
+ const lines = [];
7046
+ for (const run of groupByVariantRun(classes, prefix)) {
7047
+ if (group === "emptyLine" && lines.length > 0) lines.push("");
7048
+ lines.push(...packToWidth(run, indent, width));
7049
+ }
7050
+ return lines;
7051
+ }
6888
7052
  const enforceConsistentLineWrapping = defineRule({
6889
7053
  meta: {
6890
7054
  type: "suggestion",
6891
- docs: { description: "Warn when a class string exceeds the configured print width" },
7055
+ docs: { description: "Warn (and optionally autofix) when a class string exceeds the configured print width or classes-per-line budget" },
6892
7056
  fixable: "whitespace",
6893
7057
  schema: [{
6894
7058
  type: "object",
6895
7059
  properties: {
7060
+ entryPoint: { type: "string" },
6896
7061
  printWidth: { type: "number" },
6897
- classesPerLine: { type: "number" }
7062
+ classesPerLine: { type: "number" },
7063
+ wrapLines: {
7064
+ type: "string",
7065
+ enum: ["overWidth", "all"]
7066
+ },
7067
+ group: {
7068
+ type: "string",
7069
+ enum: [
7070
+ "newLine",
7071
+ "emptyLine",
7072
+ "never"
7073
+ ]
7074
+ }
6898
7075
  },
6899
7076
  additionalProperties: false
6900
7077
  }],
6901
- defaultOptions: [{ printWidth: DEFAULT_PRINT_WIDTH }],
7078
+ defaultOptions: [{
7079
+ printWidth: DEFAULT_PRINT_WIDTH,
7080
+ group: DEFAULT_GROUP
7081
+ }],
6902
7082
  messages: {
6903
7083
  tooLong: "Class string exceeds the print width of {{printWidth}} (longest line is {{length}} characters). Consider splitting into multiple lines or extracting into a component.",
6904
- tooManyPerLine: "Too many classes on a single line ({{count}}). Maximum allowed per line is {{max}}."
7084
+ tooManyPerLine: "Too many classes on a single line ({{count}}). Maximum allowed per line is {{max}}.",
7085
+ inconsistentWrapping: "Class string is not wrapped consistently. Classes should be re-wrapped to the configured layout within the print width of {{printWidth}}."
6905
7086
  }
6906
7087
  },
6907
7088
  createOnce(context) {
6908
7089
  const getPrintWidth = createLazyOptions(context, (o) => o?.printWidth ?? DEFAULT_PRINT_WIDTH);
6909
7090
  const getClassesPerLine = createLazyOptions(context, (o) => o?.classesPerLine);
7091
+ const getWrapLines = createLazyOptions(context, (o) => o?.wrapLines);
7092
+ const getGroup = createLazyOptions(context, (o) => o?.group ?? DEFAULT_GROUP);
7093
+ const getDS = createLazyLoader(context);
6910
7094
  /**
6911
7095
  * The statement's real base indentation — the leading whitespace of the
6912
7096
  * source line the opening backtick sits on. NOT `node.loc.start.column`,
@@ -6916,7 +7100,7 @@ const enforceConsistentLineWrapping = defineRule({
6916
7100
  */
6917
7101
  function deriveBaseIndent(loc) {
6918
7102
  const sc = safeSourceCode(context);
6919
- const line = loc.node.loc?.start.line;
7103
+ const line = loc.templateLine ?? loc.node.loc?.start.line;
6920
7104
  if (sc?.lines && typeof line === "number" && line >= 1 && line <= sc.lines.length) {
6921
7105
  const src = sc.lines[line - 1] ?? "";
6922
7106
  const m = /^[ \t]*/.exec(src);
@@ -6949,19 +7133,93 @@ const enforceConsistentLineWrapping = defineRule({
6949
7133
  return chunkList(classes, classesPerLine).map((c) => lineIndent + c).join("\n");
6950
7134
  }).join("\n");
6951
7135
  }
7136
+ /**
7137
+ * `wrapLines: 'all'` fixer (also the single-line conversion for
7138
+ * 'overWidth', which passes `group: 'never'`): the WHOLE quasi is
7139
+ * re-laid-out into `printWidth`-packed lines per the `group` mode, in the
7140
+ * BLOCK form regardless of position — every class run lands on its own
7141
+ * indented line below the backtick.
7142
+ *
7143
+ * A quasi that follows a `${}` (`preserveLeadingSpace`) starts on its own
7144
+ * fresh interior-indented line rather than hanging inline after the
7145
+ * interpolation, and a `${}` that follows the quasi
7146
+ * (`preserveTrailingSpace`) lands alone on the closing interior-indented
7147
+ * line. So no emitted line ever shares its physical row with the opaque
7148
+ * `${expr}`, and every line stays within `printWidth` — bounding the
7149
+ * hanging-join over-width case that per-quasi measurement cannot re-detect.
7150
+ *
7151
+ * The returned value BEGINS with `\n` and ENDS with indentation, so the
7152
+ * newlines already separate it from any bordering `${}`: it must NOT be run
7153
+ * through `preserveSpaces`, which would prepend a stray space before the
7154
+ * leading `\n`.
7155
+ */
7156
+ function rewrapTemplateToWidth(loc, printWidth, group, prefix) {
7157
+ const baseIndent = deriveBaseIndent(loc);
7158
+ const interiorIndent = baseIndent + INDENT_UNIT;
7159
+ const classes = splitClasses(loc.value);
7160
+ if (classes.length === 0) return loc.value;
7161
+ const packed = packGroupedToWidth(classes, interiorIndent, printWidth, group, prefix);
7162
+ const close = loc.preserveTrailingSpace ? interiorIndent : baseIndent;
7163
+ return "\n" + packed.map((c) => c === "" ? c : interiorIndent + c).join("\n") + "\n" + close;
7164
+ }
7165
+ /**
7166
+ * `wrapLines: 'overWidth'` fixer: non-destructive like `rewrapTemplate`
7167
+ * — only lines exceeding `printWidth` are greedily re-packed, each
7168
+ * keeping its own indent; conforming lines are left verbatim. A
7169
+ * single-line value has no layout to preserve and converts to the block
7170
+ * form. Returns the FINAL value, `${}` boundary spaces included — never
7171
+ * run it through `preserveSpaces`, which would prepend a stray space to
7172
+ * a quasi that legitimately starts with `\n`.
7173
+ */
7174
+ function rewrapOverBudgetLinesToWidth(loc, printWidth) {
7175
+ const lines = loc.value.split("\n");
7176
+ if (lines.length === 1) return rewrapTemplateToWidth(loc, printWidth, "never", "");
7177
+ const interiorIndent = deriveBaseIndent(loc) + INDENT_UNIT;
7178
+ const width = printWidth - (loc.preserveTrailingSpace ? 1 : 0);
7179
+ const fixed = lines.map((line) => {
7180
+ const classes = splitClasses(line);
7181
+ if (line.length <= printWidth || classes.length <= 1) return line;
7182
+ const m = /^[ \t]*/.exec(line);
7183
+ const lead = m ? m[0] : "";
7184
+ const contIndent = lead.length > 0 ? lead : interiorIndent;
7185
+ return packToWidth(classes, contIndent, width).map((c, i) => i === 0 ? lead + c : contIndent + c).join("\n");
7186
+ }).join("\n");
7187
+ if (loc.preserveTrailingSpace && !/\s$/.test(fixed)) return fixed + " ";
7188
+ return fixed;
7189
+ }
6952
7190
  function check(locations) {
6953
7191
  const printWidth = getPrintWidth();
6954
7192
  const classesPerLine = getClassesPerLine();
7193
+ const wrapLines = getWrapLines();
7194
+ const group = getGroup();
7195
+ const prefix = wrapLines === "all" && group !== "never" && classesPerLine === void 0 ? softGetDS(getDS)?.cache.prefix ?? "" : "";
6955
7196
  for (const loc of locations) {
6956
7197
  let maxLine = 0;
6957
- for (const line of loc.value.split("\n")) if (line.length > maxLine) maxLine = line.length;
6958
- if (maxLine > printWidth) context.report({
7198
+ for (const line of loc.value.split("\n")) {
7199
+ if (line.length <= maxLine) continue;
7200
+ if (line.length > printWidth && splitClasses(line).length <= 1) continue;
7201
+ maxLine = line.length;
7202
+ }
7203
+ const data = {
7204
+ length: String(maxLine),
7205
+ printWidth: String(printWidth)
7206
+ };
7207
+ const isMultiline = loc.value.includes("\n");
7208
+ const glued = loc.preserveLeadingSpace === true && !/^\s/.test(loc.value) || loc.preserveTrailingSpace === true && !/\s$/.test(loc.value);
7209
+ if (wrapLines !== void 0 && classesPerLine === void 0 && loc.node.type === "TemplateElement" && !glued && (maxLine > printWidth || wrapLines === "all" && isMultiline)) {
7210
+ const fixedValue = wrapLines === "all" ? rewrapTemplateToWidth(loc, printWidth, group, prefix) : rewrapOverBudgetLinesToWidth(loc, printWidth);
7211
+ if (fixedValue !== loc.value) context.report({
7212
+ node: loc.node,
7213
+ messageId: maxLine > printWidth ? "tooLong" : "inconsistentWrapping",
7214
+ data,
7215
+ fix(fixer) {
7216
+ return fixer.replaceTextRange(loc.range, fixedValue);
7217
+ }
7218
+ });
7219
+ } else if (maxLine > printWidth) context.report({
6959
7220
  node: loc.node,
6960
7221
  messageId: "tooLong",
6961
- data: {
6962
- length: String(maxLine),
6963
- printWidth: String(printWidth)
6964
- }
7222
+ data
6965
7223
  });
6966
7224
  if (classesPerLine !== void 0) {
6967
7225
  const lines = loc.value.split("\n");
@@ -6975,7 +7233,7 @@ const enforceConsistentLineWrapping = defineRule({
6975
7233
  count: String(maxPerLine),
6976
7234
  max: String(classesPerLine)
6977
7235
  };
6978
- if (loc.node.type === "TemplateElement") {
7236
+ if (loc.node.type === "TemplateElement" && !glued) {
6979
7237
  const fixedValue = rewrapTemplate(loc, lines, classesPerLine);
6980
7238
  context.report({
6981
7239
  node: loc.node,