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.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 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."));
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 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 }));
3885
- }
3886
- if (parsed === null) {
3887
- this.dropWorker(cssPath);
3888
- 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."));
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) {
@@ -3909,8 +4005,6 @@ var DesignSystemWorker = class {
3909
4005
  } catch {}
3910
4006
  }
3911
4007
  };
3912
- //#endregion
3913
- //#region src/design-system/declaration-service.ts
3914
4008
  const declWorker = new DesignSystemWorker({
3915
4009
  workerScript: makeWorkerScript(`(ds, request) => {
3916
4010
  const decls = {};
@@ -3924,14 +4018,28 @@ const declWorker = new DesignSystemWorker({
3924
4018
  // so every user-written value went silently uncompared.
3925
4019
  const prefix = (ds.theme && ds.theme.prefix) || '';
3926
4020
  const pfx = (c) => (prefix && !c.startsWith(prefix + ':')) ? prefix + ':' + c : c;
3927
- const css = ds.candidatesToCss(request.classes.map(pfx));
4021
+ // Resolve one class at a time rather than a single batch call: a malformed/
4022
+ // mid-typing arbitrary value can make ds.candidatesToCss throw on some engine
4023
+ // versions (#130), and a batched throw blanked the whole request AND masked
4024
+ // real typos (a valid sibling like \`bg-red-5000\` went unflagged), then became
4025
+ // the worker's 'null' sentinel → a process-sticky fatal error. Per-class,
4026
+ // distinguish a THROW (incanonicalizable input → OMIT, so no-unknown-classes
4027
+ // stays lenient instead of flagging a transient false "unknown class") from a
4028
+ // FALSY result (compiles to nothing → invalid).
3928
4029
  for (let i = 0; i < request.classes.length; i++) {
3929
- if (!css[i]) { invalid.push(request.classes[i]); continue; }
3930
4030
  const cls = request.classes[i];
4031
+ let one;
4032
+ try {
4033
+ const out = ds.candidatesToCss([pfx(cls)]);
4034
+ one = out && out[0];
4035
+ } catch (e) {
4036
+ continue; // omit: neither decls nor invalid
4037
+ }
4038
+ if (!one) { invalid.push(cls); continue; }
3931
4039
  const list = [];
3932
4040
  // The selector carries the prefix, so the scope classifier needs the
3933
4041
  // prefixed name even though the result is keyed by the bare one.
3934
- walkDeclarations(css[i], pfx(cls), (scope, prop, value) => {
4042
+ walkDeclarations(one, pfx(cls), (scope, prop, value) => {
3935
4043
  list.push([scope, prop, value]);
3936
4044
  if (!(value in values)) {
3937
4045
  const reads = scanVarReads(value);
@@ -4840,24 +4948,7 @@ const noDeprecatedClasses = defineRule({
4840
4948
  return createExtractorVisitors(context, check);
4841
4949
  }
4842
4950
  });
4843
- //#endregion
4844
- //#region src/design-system/canonicalize-service.ts
4845
- /**
4846
- * Persistent canonicalize service backed by `DesignSystemWorker`.
4847
- *
4848
- * Calls `ds.canonicalizeCandidates([cls], { rem })` one class at a time
4849
- * (the design system deduplicates its input, so batching changes the
4850
- * result shape — see sync-loader.ts). The shared protocol lives in
4851
- * `./ds-worker.ts`.
4852
- *
4853
- * ## Per-class cache (process-wide)
4854
- *
4855
- * Results are cached by `${cssPath}\0${rem}\0${class}`. The worker is
4856
- * invoked only for cache misses. In practice the cache converges quickly —
4857
- * after the first few files any given class has been seen, and every
4858
- * subsequent lookup is O(1).
4859
- */
4860
- const WORKER_SCRIPT = makeWorkerScript(`(ds, request) => {
4951
+ const WORKER_SCRIPT$1 = makeWorkerScript(`(ds, request) => {
4861
4952
  const { classes, rem } = request;
4862
4953
  const options = rem ? { rem } : undefined;
4863
4954
  const declsOf = (cls) => {
@@ -4871,7 +4962,17 @@ const WORKER_SCRIPT = makeWorkerScript(`(ds, request) => {
4871
4962
  return css.slice(open + 1, close).replace(/\\s+/g, ' ').trim();
4872
4963
  };
4873
4964
  return classes.map((cls) => {
4874
- const r = ds.canonicalizeCandidates([cls], options);
4965
+ // A malformed/mid-typing arbitrary value (e.g. \`px-[calc(var(--a)+)]\`) can
4966
+ // make the Tailwind parser throw on some engine versions (#130). Treat it
4967
+ // as an incanonicalizable no-op — same posture declsOf already takes for
4968
+ // candidatesToCss — instead of letting the throw become the worker's 'null'
4969
+ // sentinel, which the host used to turn into a process-sticky fatal error.
4970
+ let r;
4971
+ try {
4972
+ r = ds.canonicalizeCandidates([cls], options);
4973
+ } catch (e) {
4974
+ return { canonical: cls, safe: true };
4975
+ }
4875
4976
  const canonical = r[0] ?? cls;
4876
4977
  if (canonical === cls) return { canonical: cls, safe: true };
4877
4978
  const a = declsOf(cls);
@@ -4880,7 +4981,7 @@ const WORKER_SCRIPT = makeWorkerScript(`(ds, request) => {
4880
4981
  });
4881
4982
  }`);
4882
4983
  const canonWorker = new DesignSystemWorker({
4883
- workerScript: WORKER_SCRIPT,
4984
+ workerScript: WORKER_SCRIPT$1,
4884
4985
  serviceName: "canonicalize"
4885
4986
  });
4886
4987
  /**
@@ -4914,7 +5015,7 @@ const canonCache = /* @__PURE__ */ new Map();
4914
5015
  * Best-effort everywhere: a missing/corrupt/unwritable cache file must never
4915
5016
  * break linting — it only costs worker round-trips.
4916
5017
  */
4917
- 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);
4918
5019
  let tmpSeq = 0;
4919
5020
  const LOCK_STALE_MS = 1e4;
4920
5021
  /** One persistence state per `${cssPath}\0${rem}\0` cache prefix. */
@@ -5187,18 +5288,19 @@ const enforceCanonical = defineRule({
5187
5288
  return createExtractorVisitors(context, check);
5188
5289
  }
5189
5290
  });
5190
- //#endregion
5191
- //#region src/design-system/sort-service.ts
5192
- /**
5193
- * Persistent sort service backed by `DesignSystemWorker`.
5194
- *
5195
- * Calls `ds.getClassOrder(classes)` and returns the class names in the
5196
- * Tailwind-canonical order. The shared protocol (SharedArrayBuffer,
5197
- * Atomics.wait, fail-loud, sticky lastError) lives in `./ds-worker.ts`.
5198
- */
5199
5291
  const sortWorker = new DesignSystemWorker({
5200
5292
  workerScript: makeWorkerScript(`(ds, classes) => {
5201
- const ordered = ds.getClassOrder(classes);
5293
+ // A malformed/mid-typing arbitrary value can make ds.getClassOrder throw on
5294
+ // some engine versions (#130). Degrade to the input order (no reordering):
5295
+ // the rule reads an unchanged order as "already sorted" and emits nothing,
5296
+ // instead of the throw becoming the worker's 'null' sentinel → a
5297
+ // process-sticky fatal error that disabled the rule until restart.
5298
+ let ordered;
5299
+ try {
5300
+ ordered = ds.getClassOrder(classes);
5301
+ } catch (e) {
5302
+ return classes;
5303
+ }
5202
5304
  return [...ordered]
5203
5305
  .sort((a, b) => {
5204
5306
  if (a[1] === null && b[1] === null) return 0;
@@ -5277,7 +5379,7 @@ const enforceSortOrder = defineRule({
5277
5379
  groupClasses.length = 0;
5278
5380
  for (const [name] of ordered) groupClasses.push(name);
5279
5381
  }
5280
- 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;
5281
5383
  const sortedGroupKeys = [...groups.keys()].sort((ka, kb) => {
5282
5384
  const a = stripKey(ka);
5283
5385
  const b = stripKey(kb);
@@ -6787,12 +6889,7 @@ const consistentVariantOrder = defineRule({
6787
6889
  }
6788
6890
  function reorderClass(cls) {
6789
6891
  const { priorityOf, prefix, factsFor } = resolveForFile();
6790
- let pfx = "";
6791
- let body = cls;
6792
- if (prefix && cls.startsWith(prefix + ":")) {
6793
- pfx = prefix + ":";
6794
- body = cls.slice(prefix.length + 1);
6795
- }
6892
+ const { prefix: pfx, body } = stripProjectPrefix(cls, prefix);
6796
6893
  const variants = extractVariants(body);
6797
6894
  if (variants.length < 2) return null;
6798
6895
  const pseudo = [];
@@ -6873,6 +6970,7 @@ const consistentVariantOrder = defineRule({
6873
6970
  //#endregion
6874
6971
  //#region src/rules/enforce-consistent-line-wrapping.ts
6875
6972
  const DEFAULT_PRINT_WIDTH = 80;
6973
+ const DEFAULT_GROUP = "newLine";
6876
6974
  /** One indentation level added below the statement's base indent for wrapped lines. */
6877
6975
  const INDENT_UNIT = " ";
6878
6976
  /** Group `classes` into chunks of at most `n`, each chunk space-joined. */
@@ -6881,28 +6979,114 @@ function chunkList(classes, n) {
6881
6979
  for (let i = 0; i < classes.length; i += n) chunks.push(classes.slice(i, i + n).join(" "));
6882
6980
  return chunks;
6883
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
+ }
6884
7048
  const enforceConsistentLineWrapping = defineRule({
6885
7049
  meta: {
6886
7050
  type: "suggestion",
6887
- 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" },
6888
7052
  fixable: "whitespace",
6889
7053
  schema: [{
6890
7054
  type: "object",
6891
7055
  properties: {
7056
+ entryPoint: { type: "string" },
6892
7057
  printWidth: { type: "number" },
6893
- 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
+ }
6894
7071
  },
6895
7072
  additionalProperties: false
6896
7073
  }],
6897
- defaultOptions: [{ printWidth: DEFAULT_PRINT_WIDTH }],
7074
+ defaultOptions: [{
7075
+ printWidth: DEFAULT_PRINT_WIDTH,
7076
+ group: DEFAULT_GROUP
7077
+ }],
6898
7078
  messages: {
6899
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.",
6900
- 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}}."
6901
7082
  }
6902
7083
  },
6903
7084
  createOnce(context) {
6904
7085
  const getPrintWidth = createLazyOptions(context, (o) => o?.printWidth ?? DEFAULT_PRINT_WIDTH);
6905
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);
6906
7090
  /**
6907
7091
  * The statement's real base indentation — the leading whitespace of the
6908
7092
  * source line the opening backtick sits on. NOT `node.loc.start.column`,
@@ -6912,7 +7096,7 @@ const enforceConsistentLineWrapping = defineRule({
6912
7096
  */
6913
7097
  function deriveBaseIndent(loc) {
6914
7098
  const sc = safeSourceCode(context);
6915
- const line = loc.node.loc?.start.line;
7099
+ const line = loc.templateLine ?? loc.node.loc?.start.line;
6916
7100
  if (sc?.lines && typeof line === "number" && line >= 1 && line <= sc.lines.length) {
6917
7101
  const src = sc.lines[line - 1] ?? "";
6918
7102
  const m = /^[ \t]*/.exec(src);
@@ -6945,19 +7129,93 @@ const enforceConsistentLineWrapping = defineRule({
6945
7129
  return chunkList(classes, classesPerLine).map((c) => lineIndent + c).join("\n");
6946
7130
  }).join("\n");
6947
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
+ }
6948
7186
  function check(locations) {
6949
7187
  const printWidth = getPrintWidth();
6950
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 ?? "" : "";
6951
7192
  for (const loc of locations) {
6952
7193
  let maxLine = 0;
6953
- for (const line of loc.value.split("\n")) if (line.length > maxLine) maxLine = line.length;
6954
- 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({
6955
7216
  node: loc.node,
6956
7217
  messageId: "tooLong",
6957
- data: {
6958
- length: String(maxLine),
6959
- printWidth: String(printWidth)
6960
- }
7218
+ data
6961
7219
  });
6962
7220
  if (classesPerLine !== void 0) {
6963
7221
  const lines = loc.value.split("\n");
@@ -6971,7 +7229,7 @@ const enforceConsistentLineWrapping = defineRule({
6971
7229
  count: String(maxPerLine),
6972
7230
  max: String(classesPerLine)
6973
7231
  };
6974
- if (loc.node.type === "TemplateElement") {
7232
+ if (loc.node.type === "TemplateElement" && !glued) {
6975
7233
  const fixedValue = rewrapTemplate(loc, lines, classesPerLine);
6976
7234
  context.report({
6977
7235
  node: loc.node,